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;
83 // Is non-null if type is AttributeUsageAttribute
84 AttributeUsageAttribute usage_attribute;
86 public AttributeUsageAttribute UsageAttribute {
88 return usage_attribute;
92 MethodImplOptions ImplOptions;
93 UnmanagedType UnmanagedType;
94 CustomAttributeBuilder cb;
96 // non-null if named args present after Resolve () is called
97 PropertyInfo [] prop_info_arr;
98 FieldInfo [] field_info_arr;
99 object [] field_values_arr;
100 object [] prop_values_arr;
101 object [] pos_values;
103 static PtrHashtable usage_attr_cache = new PtrHashtable ();
105 public Attribute (string target, string name, ArrayList args, Location loc)
110 ExplicitTarget = target;
113 void Error_InvalidNamedArgument (string name)
115 Report.Error (617, Location, "Invalid attribute argument: '{0}'. Argument must be fields " +
116 "fields which are not readonly, static or const; or read-write instance properties.",
120 static void Error_AttributeArgumentNotValid (Location loc)
122 Report.Error (182, loc,
123 "An attribute argument must be a constant expression, typeof " +
124 "expression or array creation expression");
128 /// This is rather hack. We report many emit attribute error with same error to be compatible with
129 /// csc. But because csc has to report them this way because error came from ilasm we needn't.
131 public void Error_AttributeEmitError (string inner)
133 Report.Error (647, Location, "Error emitting '{0}' attribute because '{1}'", Name, inner);
136 public void Error_InvalidSecurityParent ()
138 Error_AttributeEmitError ("it is attached to invalid parent");
141 void Error_AttributeConstructorMismatch ()
143 Report.Error (-6, Location,
144 "Could not find a constructor for this argument list.");
148 /// Tries to resolve the type of the attribute. Flags an error if it can't, and complain is true.
150 protected virtual Type CheckAttributeType (EmitContext ec)
152 string NameAttribute = Name + "Attribute";
154 Type t1 = ec.ResolvingTypeTree
155 ? ec.DeclSpace.FindType (Location, Name)
156 : RootContext.LookupType (ec.DeclSpace, Name, true, Location);
158 // FIXME: Shouldn't do this for quoted attributes: [@A]
159 Type t2 = ec.ResolvingTypeTree
160 ? ec.DeclSpace.FindType (Location, NameAttribute)
161 : RootContext.LookupType (ec.DeclSpace, NameAttribute, true, Location);
163 String err0616 = null;
165 if (t1 != null && ! t1.IsSubclassOf (TypeManager.attribute_type)) {
167 err0616 = "'" + Name + "': is not an attribute class";
169 if (t2 != null && ! t2.IsSubclassOf (TypeManager.attribute_type)) {
171 err0616 = (err0616 != null)
172 ? "Neither '" + Name + "' nor '" + NameAttribute +"' is an attribute class"
173 : "'" + Name + "Attribute': is not an attribute class";
176 if (t1 != null && t2 != null) {
177 Report.Error(1614, Location, "'" + Name + "': is ambiguous; "
178 + " use either '@" + Name + "' or '" + NameAttribute + "'");
186 if (err0616 != null) {
187 Report.Error (616, Location, err0616);
191 Report.Error (246, Location,
192 "Could not find attribute '" + Name
193 + "' (are you missing a using directive or an assembly reference ?)");
198 public Type ResolveType (EmitContext ec)
201 Type = CheckAttributeType (ec);
206 /// Validates the guid string
208 bool ValidateGuid (string guid)
214 Report.Error (647, Location, "Format of GUID is invalid: " + guid);
219 string GetFullMemberName (string member)
221 return Type.FullName + '.' + member;
225 // Given an expression, if the expression is a valid attribute-argument-expression
226 // returns an object that can be used to encode it, or null on failure.
228 public static bool GetAttributeArgumentExpression (Expression e, Location loc, Type arg_type, out object result)
230 if (e is EnumConstant) {
231 if (RootContext.StdLib)
232 result = ((EnumConstant)e).GetValueAsEnumType ();
234 result = ((EnumConstant)e).GetValue ();
239 Constant constant = e as Constant;
240 if (constant != null) {
241 if (e.Type != arg_type) {
242 constant = Const.ChangeType (loc, constant, arg_type);
243 if (constant == null) {
245 Error_AttributeArgumentNotValid (loc);
249 result = constant.GetValue ();
251 } else if (e is TypeOf) {
252 result = ((TypeOf) e).TypeArg;
254 } else if (e is ArrayCreation){
255 result = ((ArrayCreation) e).EncodeAsAttribute ();
258 } else if (e is EmptyCast) {
259 Expression child = ((EmptyCast)e).Child;
260 return GetAttributeArgumentExpression (child, loc, child.Type, out result);
264 Error_AttributeArgumentNotValid (loc);
268 public CustomAttributeBuilder Resolve (EmitContext ec)
273 resolve_error = true;
278 Type = CheckAttributeType (ec);
280 if (oldType == null && Type == null)
282 if (oldType != null && oldType != Type){
283 Report.Error (-27, Location,
284 "Attribute {0} resolved to different types at different times: {1} vs. {2}",
285 Name, oldType, Type);
289 if (Type.IsAbstract) {
290 Report.Error (653, Location, "Cannot apply attribute class '{0}' because it is abstract", Name);
294 bool MethodImplAttr = false;
295 bool MarshalAsAttr = false;
296 bool GuidAttr = false;
297 bool usage_attr = false;
299 bool DoCompares = true;
302 // If we are a certain special attribute, we
303 // set the information accordingly
306 if (Type == TypeManager.attribute_usage_type)
308 else if (Type == TypeManager.methodimpl_attr_type)
309 MethodImplAttr = true;
310 else if (Type == TypeManager.marshal_as_attr_type)
311 MarshalAsAttr = true;
312 else if (Type == TypeManager.guid_attr_type)
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;
356 Report.Error (591, Location, "Invalid value for argument to 'System.AttributeUsage' attribute");
359 usage_attribute = new AttributeUsageAttribute ((AttributeTargets)val);
360 } else if (MethodImplAttr) {
361 this.ImplOptions = (MethodImplOptions) val;
362 } else if (GuidAttr){
364 // we will later check the validity of the type
367 if (!ValidateGuid ((string) val))
371 } else if (MarshalAsAttr)
373 (System.Runtime.InteropServices.UnmanagedType) val;
378 // Now process named arguments
381 ArrayList field_infos = null;
382 ArrayList prop_infos = null;
383 ArrayList field_values = null;
384 ArrayList prop_values = null;
386 if (named_args.Count > 0) {
387 field_infos = new ArrayList ();
388 prop_infos = new ArrayList ();
389 field_values = new ArrayList ();
390 prop_values = new ArrayList ();
393 Hashtable seen_names = new Hashtable();
395 for (i = 0; i < named_args.Count; i++) {
396 DictionaryEntry de = (DictionaryEntry) named_args [i];
397 string member_name = (string) de.Key;
398 Argument a = (Argument) de.Value;
401 if (seen_names.Contains(member_name)) {
402 Report.Error(643, Location, "'" + member_name + "' duplicate named attribute argument");
405 seen_names.Add(member_name, 1);
407 if (!a.Resolve (ec, Location))
410 Expression member = Expression.MemberLookup (
411 ec, Type, member_name,
412 MemberTypes.Field | MemberTypes.Property,
413 BindingFlags.Public | BindingFlags.Instance,
416 if (member == null) {
417 member = Expression.MemberLookup (ec, Type, member_name,
418 MemberTypes.Field | MemberTypes.Property, BindingFlags.NonPublic | BindingFlags.Instance,
421 if (member != null) {
422 Report.Error (122, Location, "'{0}' is inaccessible due to its protection level", GetFullMemberName (member_name));
428 Report.Error (117, Location, "Attribute `{0}' does not contain a definition for `{1}'",
433 if (!(member is PropertyExpr || member is FieldExpr)) {
434 Error_InvalidNamedArgument (member_name);
439 if (member is PropertyExpr) {
440 PropertyExpr pe = (PropertyExpr) member;
441 PropertyInfo pi = pe.PropertyInfo;
443 if (!pi.CanWrite || !pi.CanRead) {
444 Report.SymbolRelatedToPreviousError (pi);
445 Error_InvalidNamedArgument (member_name);
450 if (!GetAttributeArgumentExpression (e, Location, pi.PropertyType, out value))
453 if (usage_attribute != null) {
454 if (member_name == "AllowMultiple")
455 usage_attribute.AllowMultiple = (bool) value;
456 if (member_name == "Inherited")
457 usage_attribute.Inherited = (bool) value;
460 prop_values.Add (value);
463 } else if (member is FieldExpr) {
464 FieldExpr fe = (FieldExpr) member;
465 FieldInfo fi = fe.FieldInfo;
468 Error_InvalidNamedArgument (member_name);
473 if (!GetAttributeArgumentExpression (e, Location, fi.FieldType, out value))
476 field_values.Add (value);
477 field_infos.Add (fi);
481 Expression mg = Expression.MemberLookup (
482 ec, Type, ".ctor", MemberTypes.Constructor,
483 BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly,
487 Error_AttributeConstructorMismatch ();
491 MethodBase constructor = Invocation.OverloadResolve (
492 ec, (MethodGroupExpr) mg, pos_args, false, Location);
494 if (constructor == null) {
499 // Now we perform some checks on the positional args as they
500 // cannot be null for a constructor which expects a parameter
504 ParameterData pd = Invocation.GetParameterData (constructor);
506 int last_real_param = pd.Count;
508 // When the params is not filled we need to put one
509 if (last_real_param > pos_arg_count) {
510 object [] new_pos_values = new object [pos_arg_count + 1];
511 pos_values.CopyTo (new_pos_values, 0);
512 new_pos_values [pos_arg_count] = new object [] {} ;
513 pos_values = new_pos_values;
518 for (int j = 0; j < pos_arg_count; ++j) {
519 Argument a = (Argument) pos_args [j];
521 if (a.Expr is NullLiteral && pd.ParameterType (j) == TypeManager.object_type) {
522 Error_AttributeArgumentNotValid (Location);
526 if (j < last_real_param)
529 if (j == last_real_param) {
530 object [] array = new object [pos_arg_count - last_real_param];
531 array [0] = pos_values [j];
532 pos_values [j] = array;
536 object [] params_array = (object []) pos_values [last_real_param];
537 params_array [j - last_real_param] = pos_values [j];
540 // Adjust the size of the pos_values if it had params
541 if (last_real_param != pos_arg_count) {
542 object [] new_pos_values = new object [last_real_param + 1];
543 Array.Copy (pos_values, new_pos_values, last_real_param + 1);
544 pos_values = new_pos_values;
548 if (named_args.Count > 0) {
549 prop_info_arr = new PropertyInfo [prop_infos.Count];
550 field_info_arr = new FieldInfo [field_infos.Count];
551 field_values_arr = new object [field_values.Count];
552 prop_values_arr = new object [prop_values.Count];
554 field_infos.CopyTo (field_info_arr, 0);
555 field_values.CopyTo (field_values_arr, 0);
557 prop_values.CopyTo (prop_values_arr, 0);
558 prop_infos.CopyTo (prop_info_arr, 0);
560 cb = new CustomAttributeBuilder (
561 (ConstructorInfo) constructor, pos_values,
562 prop_info_arr, prop_values_arr,
563 field_info_arr, field_values_arr);
566 cb = new CustomAttributeBuilder (
567 (ConstructorInfo) constructor, pos_values);
568 } catch (Exception e) {
571 // using System.ComponentModel;
572 // [DefaultValue (CollectionChangeAction.Add)]
573 // class X { static void Main () {} }
575 Error_AttributeArgumentNotValid (Location);
579 resolve_error = false;
584 /// Get a string containing a list of valid targets for the attribute 'attr'
586 public string GetValidTargets ()
588 StringBuilder sb = new StringBuilder ();
589 AttributeTargets targets = GetAttributeUsage ().ValidOn;
591 if ((targets & AttributeTargets.Assembly) != 0)
592 sb.Append ("'assembly' ");
594 if ((targets & AttributeTargets.Class) != 0)
595 sb.Append ("'class' ");
597 if ((targets & AttributeTargets.Constructor) != 0)
598 sb.Append ("'constructor' ");
600 if ((targets & AttributeTargets.Delegate) != 0)
601 sb.Append ("'delegate' ");
603 if ((targets & AttributeTargets.Enum) != 0)
604 sb.Append ("'enum' ");
606 if ((targets & AttributeTargets.Event) != 0)
607 sb.Append ("'event' ");
609 if ((targets & AttributeTargets.Field) != 0)
610 sb.Append ("'field' ");
612 if ((targets & AttributeTargets.Interface) != 0)
613 sb.Append ("'interface' ");
615 if ((targets & AttributeTargets.Method) != 0)
616 sb.Append ("'method' ");
618 if ((targets & AttributeTargets.Module) != 0)
619 sb.Append ("'module' ");
621 if ((targets & AttributeTargets.Parameter) != 0)
622 sb.Append ("'parameter' ");
624 if ((targets & AttributeTargets.Property) != 0)
625 sb.Append ("'property' ");
627 if ((targets & AttributeTargets.ReturnValue) != 0)
628 sb.Append ("'return' ");
630 if ((targets & AttributeTargets.Struct) != 0)
631 sb.Append ("'struct' ");
633 return sb.ToString ();
638 /// Returns AttributeUsage attribute for this type
640 public AttributeUsageAttribute GetAttributeUsage ()
642 AttributeUsageAttribute ua = usage_attr_cache [Type] as AttributeUsageAttribute;
646 Class attr_class = TypeManager.LookupClass (Type);
648 if (attr_class == null) {
649 object[] usage_attr = Type.GetCustomAttributes (TypeManager.attribute_usage_type, true);
650 ua = (AttributeUsageAttribute)usage_attr [0];
651 usage_attr_cache.Add (Type, ua);
655 return attr_class.AttributeUsage;
659 /// Returns custom name of indexer
661 public string GetIndexerAttributeValue (EmitContext ec)
663 if (pos_values == null) {
664 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
665 // But because a lot of attribute class code must be rewritten will be better to wait...
669 return pos_values [0] as string;
673 /// Returns condition of ConditionalAttribute
675 public string GetConditionalAttributeValue (DeclSpace ds)
677 if (pos_values == null) {
678 EmitContext ec = new EmitContext (ds, ds, Location, null, null, 0, false);
680 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
681 // But because a lot of attribute class code must be rewritten will be better to wait...
685 // Some error occurred
686 if (pos_values [0] == null)
689 return (string)pos_values [0];
693 /// Creates the instance of ObsoleteAttribute from this attribute instance
695 public ObsoleteAttribute GetObsoleteAttribute (DeclSpace ds)
697 if (pos_values == null) {
698 EmitContext ec = new EmitContext (ds, ds, Location, null, null, 0, false);
700 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
701 // But because a lot of attribute class code must be rewritten will be better to wait...
705 // Some error occurred
706 if (pos_values == null)
709 if (pos_values.Length == 0)
710 return new ObsoleteAttribute ();
712 if (pos_values.Length == 1)
713 return new ObsoleteAttribute ((string)pos_values [0]);
715 return new ObsoleteAttribute ((string)pos_values [0], (bool)pos_values [1]);
719 /// Returns value of CLSCompliantAttribute contructor parameter but because the method can be called
720 /// before ApplyAttribute. We need to resolve the arguments.
721 /// This situation occurs when class deps is differs from Emit order.
723 public bool GetClsCompliantAttributeValue (DeclSpace ds)
725 if (pos_values == null) {
726 EmitContext ec = new EmitContext (ds, ds, Location, null, null, 0, false);
728 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
729 // But because a lot of attribute class code must be rewritten will be better to wait...
733 // Some error occurred
734 if (pos_values [0] == null)
737 return (bool)pos_values [0];
741 /// Tests permitted SecurityAction for assembly or other types
743 public bool CheckSecurityActionValidity (bool for_assembly)
745 SecurityAction action = GetSecurityActionValue ();
747 if ((action == SecurityAction.RequestMinimum || action == SecurityAction.RequestOptional || action == SecurityAction.RequestRefuse) && for_assembly)
751 if (action < SecurityAction.Demand || action > SecurityAction.InheritanceDemand) {
752 Error_AttributeEmitError ("SecurityAction is out of range");
756 if ((action != SecurityAction.RequestMinimum && action != SecurityAction.RequestOptional && action != SecurityAction.RequestRefuse) && !for_assembly)
760 Error_AttributeEmitError (String.Concat ("SecurityAction '", action, "' is not valid for this declaration"));
764 System.Security.Permissions.SecurityAction GetSecurityActionValue ()
766 return (SecurityAction)pos_values [0];
770 /// Creates instance of SecurityAttribute class and add result of CreatePermission method to permission table.
772 /// <returns></returns>
773 public void ExtractSecurityPermissionSet (ListDictionary permissions)
775 if (TypeManager.LookupDeclSpace (Type) != null && RootContext.StdLib) {
776 Error_AttributeEmitError ("security custom attributes can not be referenced from defining assembly");
780 SecurityAttribute sa;
781 // For all assemblies except corlib we can avoid all hacks
782 if (RootContext.StdLib) {
783 sa = (SecurityAttribute) Activator.CreateInstance (Type, pos_values);
785 if (prop_info_arr != null) {
786 for (int i = 0; i < prop_info_arr.Length; ++i) {
787 PropertyInfo pi = prop_info_arr [i];
788 pi.SetValue (sa, prop_values_arr [i], null);
792 Type temp_type = Type.GetType (Type.FullName);
793 // HACK: All mscorlib attributes have same ctor syntax
794 sa = (SecurityAttribute) Activator.CreateInstance (temp_type, new object[] { GetSecurityActionValue () } );
796 // All types are from newly created corlib but for invocation with old we need to convert them
797 if (prop_info_arr != null) {
798 for (int i = 0; i < prop_info_arr.Length; ++i) {
799 PropertyInfo emited_pi = prop_info_arr [i];
800 PropertyInfo pi = temp_type.GetProperty (emited_pi.Name, emited_pi.PropertyType);
802 object old_instance = pi.PropertyType.IsEnum ?
803 System.Enum.ToObject (pi.PropertyType, prop_values_arr [i]) :
806 pi.SetValue (sa, old_instance, null);
811 IPermission perm = sa.CreatePermission ();
812 SecurityAction action;
814 // IS is correct because for corlib we are using an instance from old corlib
815 if (perm is System.Security.CodeAccessPermission) {
816 action = GetSecurityActionValue ();
818 switch (GetSecurityActionValue ()) {
819 case SecurityAction.Demand:
820 action = (SecurityAction)13;
822 case SecurityAction.LinkDemand:
823 action = (SecurityAction)14;
825 case SecurityAction.InheritanceDemand:
826 action = (SecurityAction)15;
829 Error_AttributeEmitError ("Invalid SecurityAction for non-Code Access Security permission");
834 PermissionSet ps = (PermissionSet)permissions [action];
836 ps = new PermissionSet (PermissionState.None);
837 permissions.Add (action, ps);
839 ps.AddPermission (sa.CreatePermission ());
842 object GetValue (object value)
844 if (value is EnumConstant)
845 return ((EnumConstant) value).GetValue ();
850 public object GetPositionalValue (int i)
852 return (pos_values == null) ? null : pos_values[i];
855 object GetFieldValue (string name)
858 if (field_info_arr == null)
861 foreach (FieldInfo fi in field_info_arr) {
863 return GetValue (field_values_arr [i]);
869 public UnmanagedMarshal GetMarshal (Attributable attr)
871 object value = GetFieldValue ("SizeParamIndex");
872 if (value != null && UnmanagedType != UnmanagedType.LPArray) {
873 Error_AttributeEmitError ("SizeParamIndex field is not valid for the specified unmanaged type");
877 object o = GetFieldValue ("ArraySubType");
878 UnmanagedType array_sub_type = o == null ? UnmanagedType.I4 : (UnmanagedType) o;
880 switch (UnmanagedType) {
881 case UnmanagedType.CustomMarshaler:
882 MethodInfo define_custom = typeof (UnmanagedMarshal).GetMethod ("DefineCustom",
883 BindingFlags.Static | BindingFlags.Public);
884 if (define_custom == null) {
885 Report.RuntimeMissingSupport (Location, "set marshal info");
889 object [] args = new object [4];
890 args [0] = GetFieldValue ("MarshalTypeRef");
891 args [1] = GetFieldValue ("MarshalCookie");
892 args [2] = GetFieldValue ("MarshalType");
893 args [3] = Guid.Empty;
894 return (UnmanagedMarshal) define_custom.Invoke (null, args);
896 case UnmanagedType.LPArray:
897 return UnmanagedMarshal.DefineLPArray (array_sub_type);
899 case UnmanagedType.SafeArray:
900 return UnmanagedMarshal.DefineSafeArray (array_sub_type);
902 case UnmanagedType.ByValArray:
903 FieldMember fm = attr as FieldMember;
905 Error_AttributeEmitError ("Specified unmanaged type is only valid on fields");
908 return UnmanagedMarshal.DefineByValArray ((int) GetFieldValue ("SizeConst"));
910 case UnmanagedType.ByValTStr:
911 return UnmanagedMarshal.DefineByValTStr ((int) GetFieldValue ("SizeConst"));
914 return UnmanagedMarshal.DefineUnmanagedMarshal (UnmanagedType);
918 public bool IsInternalCall
920 get { return ImplOptions == MethodImplOptions.InternalCall; }
924 /// Emit attribute for Attributable symbol
926 public void Emit (EmitContext ec, Attributable ias, ListDictionary emitted_attr)
928 CustomAttributeBuilder cb = Resolve (ec);
932 AttributeUsageAttribute usage_attr = GetAttributeUsage ();
933 if ((usage_attr.ValidOn & Target) == 0) {
934 Report.Error (592, Location, "Attribute '{0}' is not valid on this declaration type. It is valid on {1} declarations only.", Name, GetValidTargets ());
938 ias.ApplyAttributeBuilder (this, cb);
940 if (!usage_attr.AllowMultiple) {
941 ArrayList emitted_targets = (ArrayList)emitted_attr [Type];
942 if (emitted_targets == null) {
943 emitted_targets = new ArrayList ();
944 emitted_attr.Add (Type, emitted_targets);
945 } else if (emitted_targets.Contains (Target)) {
946 Report.Error (579, Location, "Duplicate '" + Name + "' attribute");
949 emitted_targets.Add (Target);
952 if (!RootContext.VerifyClsCompliance)
955 // Here we are testing attribute arguments for array usage (error 3016)
956 if (ias.IsClsCompliaceRequired (ec.DeclSpace)) {
957 if (Arguments == null)
960 ArrayList pos_args = (ArrayList) Arguments [0];
961 if (pos_args != null) {
962 foreach (Argument arg in pos_args) {
963 // Type is undefined (was error 246)
964 if (arg.Type == null)
967 if (arg.Type.IsArray) {
968 Report.Error (3016, Location, "Arrays as attribute arguments are not CLS-compliant");
974 if (Arguments.Count < 2)
977 ArrayList named_args = (ArrayList) Arguments [1];
978 foreach (DictionaryEntry de in named_args) {
979 Argument arg = (Argument) de.Value;
981 // Type is undefined (was error 246)
982 if (arg.Type == null)
985 if (arg.Type.IsArray) {
986 Report.Error (3016, Location, "Arrays as attribute arguments are not CLS-compliant");
993 public object GetValue (EmitContext ec, Constant c, Type target)
995 if (Convert.ImplicitConversionExists (ec, c, target))
996 return c.GetValue ();
998 Convert.Error_CannotImplicitConversion (Location, c.Type, target);
1002 public MethodBuilder DefinePInvokeMethod (EmitContext ec, TypeBuilder builder, string name,
1003 MethodAttributes flags, Type ret_type, Type [] param_types)
1006 // We extract from the attribute the information we need
1009 if (Arguments == null) {
1010 Console.WriteLine ("Internal error : this is not supposed to happen !");
1018 ArrayList named_args = new ArrayList ();
1020 ArrayList pos_args = (ArrayList) Arguments [0];
1021 if (Arguments.Count > 1)
1022 named_args = (ArrayList) Arguments [1];
1025 string dll_name = null;
1027 Argument tmp = (Argument) pos_args [0];
1029 if (!tmp.Resolve (ec, Location))
1032 if (tmp.Expr is Constant)
1033 dll_name = (string) ((Constant) tmp.Expr).GetValue ();
1035 Error_AttributeArgumentNotValid (Location);
1039 // Now we process the named arguments
1040 CallingConvention cc = CallingConvention.Winapi;
1041 CharSet charset = CharSet.Ansi;
1042 bool preserve_sig = true;
1044 bool exact_spelling = false;
1046 bool set_last_err = false;
1047 string entry_point = null;
1049 for (int i = 0; i < named_args.Count; i++) {
1051 DictionaryEntry de = (DictionaryEntry) named_args [i];
1053 string member_name = (string) de.Key;
1054 Argument a = (Argument) de.Value;
1056 if (!a.Resolve (ec, Location))
1059 Expression member = Expression.MemberLookup (
1060 ec, Type, member_name,
1061 MemberTypes.Field | MemberTypes.Property,
1062 BindingFlags.Public | BindingFlags.Instance,
1065 if (member == null || !(member is FieldExpr)) {
1066 Error_InvalidNamedArgument (member_name);
1070 if (member is FieldExpr) {
1071 FieldExpr fe = (FieldExpr) member;
1072 FieldInfo fi = fe.FieldInfo;
1074 if (fi.IsInitOnly) {
1075 Error_InvalidNamedArgument (member_name);
1079 if (a.Expr is Constant) {
1080 Constant c = (Constant) a.Expr;
1083 if (member_name == "CallingConvention"){
1084 object val = GetValue (ec, c, typeof (CallingConvention));
1087 cc = (CallingConvention) val;
1088 } else if (member_name == "CharSet"){
1089 charset = (CharSet) c.GetValue ();
1090 } else if (member_name == "EntryPoint")
1091 entry_point = (string) c.GetValue ();
1092 else if (member_name == "SetLastError")
1093 set_last_err = (bool) c.GetValue ();
1095 else if (member_name == "ExactSpelling")
1096 exact_spelling = (bool) c.GetValue ();
1098 else if (member_name == "PreserveSig")
1099 preserve_sig = (bool) c.GetValue ();
1100 } catch (InvalidCastException){
1101 Error_InvalidNamedArgument (member_name);
1102 Error_AttributeArgumentNotValid (Location);
1105 Error_AttributeArgumentNotValid (Location);
1112 if (entry_point == null)
1115 charset = (CharSet)((int)charset | 0x40);
1117 MethodBuilder mb = builder.DefinePInvokeMethod (
1118 name, dll_name, entry_point, flags | MethodAttributes.HideBySig,
1119 CallingConventions.Standard,
1126 mb.SetImplementationFlags (MethodImplAttributes.PreserveSig);
1131 private Expression GetValue ()
1133 if ((Arguments == null) || (Arguments.Count < 1))
1135 ArrayList al = (ArrayList) Arguments [0];
1136 if ((al == null) || (al.Count < 1))
1138 Argument arg = (Argument) al [0];
1139 if ((arg == null) || (arg.Expr == null))
1144 public string GetString ()
1146 Expression e = GetValue ();
1147 if (e is StringLiteral)
1148 return (e as StringLiteral).Value;
1152 public bool GetBoolean ()
1154 Expression e = GetValue ();
1155 if (e is BoolLiteral)
1156 return (e as BoolLiteral).Value;
1163 /// For global attributes (assembly, module) we need special handling.
1164 /// Attributes can be located in the several files
1166 public class GlobalAttribute: Attribute
1168 public readonly NamespaceEntry ns;
1170 public GlobalAttribute (TypeContainer container, string target, string name, ArrayList args, Location loc):
1171 base (target, name, args, loc)
1173 ns = container.NamespaceEntry;
1176 protected override Type CheckAttributeType (EmitContext ec)
1178 // RootContext.Tree.Types has a single NamespaceEntry which gets overwritten
1179 // each time a new file is parsed. However, we need to use the NamespaceEntry
1180 // in effect where the attribute was used. Since code elsewhere cannot assume
1181 // that the NamespaceEntry is right, just overwrite it.
1183 // FIXME: Check every place the NamespaceEntry of RootContext.Tree.Types is used
1184 // to ensure the right one is used.
1185 if (ec.DeclSpace == RootContext.Tree.Types)
1186 ec.DeclSpace.NamespaceEntry = ns;
1188 return base.CheckAttributeType (ec);
1192 public class Attributes {
1193 public ArrayList Attrs;
1195 public Attributes (Attribute a)
1197 Attrs = new ArrayList ();
1201 public Attributes (ArrayList attrs)
1206 public void AddAttributes (ArrayList attrs)
1208 Attrs.AddRange (attrs);
1212 /// Checks whether attribute target is valid for the current element
1214 public bool CheckTargets (Attributable member)
1216 string[] valid_targets = member.ValidAttributeTargets;
1217 foreach (Attribute a in Attrs) {
1218 if (a.ExplicitTarget == null || a.ExplicitTarget == valid_targets [0]) {
1219 a.Target = member.AttributeTargets;
1223 // TODO: we can skip the first item
1224 if (((IList) valid_targets).Contains (a.ExplicitTarget)) {
1225 switch (a.ExplicitTarget) {
1226 case "return": a.Target = AttributeTargets.ReturnValue; continue;
1227 case "param": a.Target = AttributeTargets.Parameter; continue;
1228 case "field": a.Target = AttributeTargets.Field; continue;
1229 case "method": a.Target = AttributeTargets.Method; continue;
1230 case "property": a.Target = AttributeTargets.Property; continue;
1232 throw new InternalErrorException ("Unknown explicit target: " + a.ExplicitTarget);
1235 StringBuilder sb = new StringBuilder ();
1236 foreach (string s in valid_targets) {
1240 sb.Remove (sb.Length - 2, 2);
1241 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 ());
1247 public Attribute Search (Type t, EmitContext ec)
1249 foreach (Attribute a in Attrs) {
1250 if (a.ResolveType (ec) == t)
1257 /// Returns all attributes of type 't'. Use it when attribute is AllowMultiple = true
1259 public Attribute[] SearchMulti (Type t, EmitContext ec)
1261 ArrayList ar = null;
1263 foreach (Attribute a in Attrs) {
1264 if (a.ResolveType (ec) == t) {
1266 ar = new ArrayList ();
1271 return ar == null ? null : ar.ToArray (typeof (Attribute)) as Attribute[];
1274 public void Emit (EmitContext ec, Attributable ias)
1276 if (!CheckTargets (ias))
1279 ListDictionary ld = new ListDictionary ();
1281 foreach (Attribute a in Attrs)
1282 a.Emit (ec, ias, ld);
1285 public bool Contains (Type t, EmitContext ec)
1287 return Search (t, ec) != null;
1292 /// Helper class for attribute verification routine.
1294 sealed class AttributeTester
1296 static PtrHashtable analyzed_types = new PtrHashtable ();
1297 static PtrHashtable analyzed_types_obsolete = new PtrHashtable ();
1298 static PtrHashtable analyzed_member_obsolete = new PtrHashtable ();
1299 static PtrHashtable analyzed_method_excluded = new PtrHashtable ();
1301 private AttributeTester ()
1306 /// Returns true if parameters of two compared methods are CLS-Compliant.
1307 /// It tests differing only in ref or out, or in array rank.
1309 public static bool AreOverloadedMethodParamsClsCompliant (Type[] types_a, Type[] types_b)
1311 if (types_a == null || types_b == null)
1314 if (types_a.Length != types_b.Length)
1317 for (int i = 0; i < types_b.Length; ++i) {
1318 Type aType = types_a [i];
1319 Type bType = types_b [i];
1321 if (aType.IsArray && bType.IsArray && aType.GetArrayRank () != bType.GetArrayRank () && aType.GetElementType () == bType.GetElementType ()) {
1325 Type aBaseType = aType;
1326 bool is_either_ref_or_out = false;
1328 if (aType.IsByRef || aType.IsPointer) {
1329 aBaseType = aType.GetElementType ();
1330 is_either_ref_or_out = true;
1333 Type bBaseType = bType;
1334 if (bType.IsByRef || bType.IsPointer)
1336 bBaseType = bType.GetElementType ();
1337 is_either_ref_or_out = !is_either_ref_or_out;
1340 if (aBaseType != bBaseType)
1343 if (is_either_ref_or_out)
1350 /// Goes through all parameters and test if they are CLS-Compliant.
1352 public static bool AreParametersCompliant (Parameter[] fixedParameters, Location loc)
1354 if (fixedParameters == null)
1357 foreach (Parameter arg in fixedParameters) {
1358 if (!AttributeTester.IsClsCompliant (arg.ParameterType)) {
1359 Report.Error (3001, loc, "Argument type '{0}' is not CLS-compliant", arg.GetSignatureForError ());
1368 /// This method tests the CLS compliance of external types. It doesn't test type visibility.
1370 public static bool IsClsCompliant (Type type)
1375 object type_compliance = analyzed_types[type];
1376 if (type_compliance != null)
1377 return type_compliance == TRUE;
1379 if (type.IsPointer) {
1380 analyzed_types.Add (type, null);
1385 if (type.IsArray || type.IsByRef) {
1386 result = IsClsCompliant (TypeManager.GetElementType (type));
1388 result = AnalyzeTypeCompliance (type);
1390 analyzed_types.Add (type, result ? TRUE : FALSE);
1394 static object TRUE = new object ();
1395 static object FALSE = new object ();
1397 public static void VerifyModulesClsCompliance ()
1399 Module[] modules = TypeManager.Modules;
1400 if (modules == null)
1403 // The first module is generated assembly
1404 for (int i = 1; i < modules.Length; ++i) {
1405 Module module = modules [i];
1406 if (!IsClsCompliant (module)) {
1407 Report.Error (3013, "Added modules must be marked with the CLSCompliant attribute to match the assembly", module.Name);
1414 /// Tests container name for CLS-Compliant name (differing only in case)
1416 public static void VerifyTopLevelNameClsCompliance ()
1418 Hashtable locase_table = new Hashtable ();
1420 // Convert imported type names to lower case and ignore not cls compliant
1421 foreach (DictionaryEntry de in TypeManager.all_imported_types) {
1422 Type t = (Type)de.Value;
1423 if (!AttributeTester.IsClsCompliant (t))
1426 locase_table.Add (((string)de.Key).ToLower (System.Globalization.CultureInfo.InvariantCulture), t);
1429 foreach (DictionaryEntry de in RootContext.Tree.Decls) {
1430 DeclSpace decl = (DeclSpace)de.Value;
1431 if (!decl.IsClsCompliaceRequired (decl))
1434 string lcase = decl.Name.ToLower (System.Globalization.CultureInfo.InvariantCulture);
1435 if (!locase_table.Contains (lcase)) {
1436 locase_table.Add (lcase, decl);
1440 object conflict = locase_table [lcase];
1441 if (conflict is Type)
1442 Report.SymbolRelatedToPreviousError ((Type)conflict);
1444 Report.SymbolRelatedToPreviousError ((MemberCore)conflict);
1446 Report.Error (3005, decl.Location, "Identifier '{0}' differing only in case is not CLS-compliant", decl.GetSignatureForError ());
1450 static bool IsClsCompliant (ICustomAttributeProvider attribute_provider)
1452 object[] CompliantAttribute = attribute_provider.GetCustomAttributes (TypeManager.cls_compliant_attribute_type, false);
1453 if (CompliantAttribute.Length == 0)
1456 return ((CLSCompliantAttribute)CompliantAttribute[0]).IsCompliant;
1459 static bool AnalyzeTypeCompliance (Type type)
1461 DeclSpace ds = TypeManager.LookupDeclSpace (type);
1463 return ds.IsClsCompliaceRequired (ds.Parent);
1466 object[] CompliantAttribute = type.GetCustomAttributes (TypeManager.cls_compliant_attribute_type, false);
1467 if (CompliantAttribute.Length == 0)
1468 return IsClsCompliant (type.Assembly);
1470 return ((CLSCompliantAttribute)CompliantAttribute[0]).IsCompliant;
1474 /// Returns instance of ObsoleteAttribute when type is obsolete
1476 public static ObsoleteAttribute GetObsoleteAttribute (Type type)
1478 object type_obsolete = analyzed_types_obsolete [type];
1479 if (type_obsolete == FALSE)
1482 if (type_obsolete != null)
1483 return (ObsoleteAttribute)type_obsolete;
1485 ObsoleteAttribute result = null;
1486 if (type.IsByRef || type.IsArray || type.IsPointer) {
1487 result = GetObsoleteAttribute (TypeManager.GetElementType (type));
1489 DeclSpace type_ds = TypeManager.LookupDeclSpace (type);
1491 // Type is external, we can get attribute directly
1492 if (type_ds == null) {
1493 object[] attribute = type.GetCustomAttributes (TypeManager.obsolete_attribute_type, false);
1494 if (attribute.Length == 1)
1495 result = (ObsoleteAttribute)attribute [0];
1497 result = type_ds.GetObsoleteAttribute (type_ds);
1501 analyzed_types_obsolete.Add (type, result == null ? FALSE : result);
1506 /// Returns instance of ObsoleteAttribute when method is obsolete
1508 public static ObsoleteAttribute GetMethodObsoleteAttribute (MethodBase mb)
1510 IMethodData mc = TypeManager.GetMethod (mb);
1512 return mc.GetObsoleteAttribute ();
1514 // compiler generated methods are not registered by AddMethod
1515 if (mb.DeclaringType is TypeBuilder)
1518 return GetMemberObsoleteAttribute (mb);
1522 /// Returns instance of ObsoleteAttribute when member is obsolete
1524 public static ObsoleteAttribute GetMemberObsoleteAttribute (MemberInfo mi)
1526 object type_obsolete = analyzed_member_obsolete [mi];
1527 if (type_obsolete == FALSE)
1530 if (type_obsolete != null)
1531 return (ObsoleteAttribute)type_obsolete;
1533 ObsoleteAttribute oa = System.Attribute.GetCustomAttribute (mi, TypeManager.obsolete_attribute_type, false) as ObsoleteAttribute;
1534 analyzed_member_obsolete.Add (mi, oa == null ? FALSE : oa);
1539 /// Common method for Obsolete error/warning reporting.
1541 public static void Report_ObsoleteMessage (ObsoleteAttribute oa, string member, Location loc)
1544 Report.Error (619, loc, "'{0}' is obsolete: '{1}'", member, oa.Message);
1548 if (oa.Message == null) {
1549 Report.Warning (612, loc, "'{0}' is obsolete", member);
1552 if (RootContext.WarningLevel >= 2)
1553 Report.Warning (618, loc, "'{0}' is obsolete: '{1}'", member, oa.Message);
1556 public static bool IsConditionalMethodExcluded (MethodBase mb)
1558 object excluded = analyzed_method_excluded [mb];
1559 if (excluded != null)
1560 return excluded == TRUE ? true : false;
1562 ConditionalAttribute[] attrs = mb.GetCustomAttributes (TypeManager.conditional_attribute_type, true) as ConditionalAttribute[];
1563 if (attrs.Length == 0) {
1564 analyzed_method_excluded.Add (mb, FALSE);
1568 foreach (ConditionalAttribute a in attrs) {
1569 if (RootContext.AllDefines.Contains (a.ConditionString)) {
1570 analyzed_method_excluded.Add (mb, FALSE);
1574 analyzed_method_excluded.Add (mb, TRUE);