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)
39 if (attributes != null)
40 attributes.CheckTargets (this);
43 public Attributes OptAttributes
50 if (attributes != null)
51 attributes.CheckTargets (this);
56 /// Use member-specific procedure to apply attribute @a in @cb to the entity being built in @builder
58 public abstract void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb);
61 /// Returns one AttributeTarget for this element.
63 public abstract AttributeTargets AttributeTargets { get; }
65 public abstract bool IsClsCompliaceRequired (DeclSpace ds);
68 /// Gets list of valid attribute targets for explicit target declaration.
69 /// The first array item is default target. Don't break this rule.
71 public abstract string[] ValidAttributeTargets { get; }
74 public class Attribute {
75 public readonly string ExplicitTarget;
76 public AttributeTargets Target;
78 public readonly string Name;
79 public readonly ArrayList Arguments;
81 public readonly Location Location;
85 // Is non-null if type is AttributeUsageAttribute
86 AttributeUsageAttribute usage_attribute;
88 public AttributeUsageAttribute UsageAttribute {
90 return usage_attribute;
94 MethodImplOptions ImplOptions;
95 UnmanagedType UnmanagedType;
96 CustomAttributeBuilder cb;
98 // non-null if named args present after Resolve () is called
99 PropertyInfo [] prop_info_arr;
100 FieldInfo [] field_info_arr;
101 object [] field_values_arr;
102 object [] prop_values_arr;
103 object [] pos_values;
105 static PtrHashtable usage_attr_cache = new PtrHashtable ();
107 public Attribute (string target, string name, ArrayList args, Location loc)
112 ExplicitTarget = target;
115 void Error_InvalidNamedArgument (string name)
117 Report.Error (617, Location, "'" + name + "' is not a valid named attribute " +
118 "argument. Named attribute arguments must be fields which are not " +
119 "readonly, static or const, or read-write properties which are not static.");
122 static void Error_AttributeArgumentNotValid (Location loc)
124 Report.Error (182, loc,
125 "An attribute argument must be a constant expression, typeof " +
126 "expression or array creation expression");
130 /// This is rather hack. We report many emit attribute error with same error to be compatible with
131 /// csc. But because csc has to report them this way because error came from ilasm we needn't.
133 public void Error_AttributeEmitError (string inner)
135 Report.Error (647, Location, "Error emitting '{0}' attribute because '{1}'", Name, inner);
138 public void Error_InvalidSecurityParent ()
140 Error_AttributeEmitError ("it is attached to invalid parent");
143 void Error_AttributeConstructorMismatch ()
145 Report.Error (-6, Location,
146 "Could not find a constructor for this argument list.");
150 /// Tries to resolve the type of the attribute. Flags an error if it can't, and complain is true.
152 protected virtual Type CheckAttributeType (EmitContext ec, bool complain)
154 Type t1 = RootContext.LookupType (ec.DeclSpace, Name, true, Location);
156 // FIXME: Shouldn't do this for quoted attributes: [@A]
157 Type t2 = RootContext.LookupType (ec.DeclSpace, Name + "Attribute", true, Location);
159 String err0616 = null;
161 if (t1 != null && ! t1.IsSubclassOf (TypeManager.attribute_type)) {
163 err0616 = "'" + Name + "': is not an attribute class";
165 if (t2 != null && ! t2.IsSubclassOf (TypeManager.attribute_type)) {
167 err0616 = (err0616 != null)
168 ? "Neither '" + Name + "' nor '" + Name + "Attribute' is an attribute class"
169 : "'" + Name + "Attribute': is not an attribute class";
172 if (t1 != null && t2 != null) {
173 Report.Error(1614, Location, "'" + Name + "': is ambiguous; "
174 + " use either '@" + Name + "' or '" + Name + "Attribute'");
182 if (err0616 != null) {
183 Report.Error (616, Location, err0616);
188 Report.Error (246, Location,
189 "Could not find attribute '" + Name
190 + "' (are you missing a using directive or an assembly reference ?)");
194 public Type ResolveType (EmitContext ec, bool complain)
197 Type = CheckAttributeType (ec, complain);
202 /// Validates the guid string
204 bool ValidateGuid (string guid)
210 Report.Error (647, Location, "Format of GUID is invalid: " + guid);
215 string GetFullMemberName (string member)
217 return Type.FullName + '.' + member;
221 // Given an expression, if the expression is a valid attribute-argument-expression
222 // returns an object that can be used to encode it, or null on failure.
224 public static bool GetAttributeArgumentExpression (Expression e, Location loc, Type arg_type, out object result)
226 if (e is EnumConstant) {
227 if (RootContext.StdLib)
228 result = ((EnumConstant)e).GetValueAsEnumType ();
230 result = ((EnumConstant)e).GetValue ();
235 Constant constant = e as Constant;
236 if (constant != null) {
237 if (e.Type != arg_type) {
238 constant = Const.ChangeType (loc, constant, arg_type);
239 if (constant == null) {
241 Error_AttributeArgumentNotValid (loc);
245 result = constant.GetValue ();
247 } else if (e is TypeOf) {
248 result = ((TypeOf) e).TypeArg;
250 } else if (e is ArrayCreation){
251 result = ((ArrayCreation) e).EncodeAsAttribute ();
254 } else if (e is EmptyCast) {
255 Expression child = ((EmptyCast)e).Child;
256 return GetAttributeArgumentExpression (child, loc, child.Type, out result);
260 Error_AttributeArgumentNotValid (loc);
264 public CustomAttributeBuilder Resolve (EmitContext ec)
269 Type = CheckAttributeType (ec, true);
271 if (oldType == null && Type == null)
273 if (oldType != null && oldType != Type){
274 Report.Error (-27, Location,
275 "Attribute {0} resolved to different types at different times: {1} vs. {2}",
276 Name, oldType, Type);
280 if (Type.IsAbstract) {
281 Report.Error (653, Location, "Cannot apply attribute class '{0}' because it is abstract", Name);
285 bool MethodImplAttr = false;
286 bool MarshalAsAttr = false;
287 bool GuidAttr = false;
288 bool usage_attr = false;
290 bool DoCompares = true;
293 // If we are a certain special attribute, we
294 // set the information accordingly
297 if (Type == TypeManager.attribute_usage_type)
299 else if (Type == TypeManager.methodimpl_attr_type)
300 MethodImplAttr = true;
301 else if (Type == TypeManager.marshal_as_attr_type)
302 MarshalAsAttr = true;
303 else if (Type == TypeManager.guid_attr_type)
308 // Now we extract the positional and named arguments
310 ArrayList pos_args = new ArrayList ();
311 ArrayList named_args = new ArrayList ();
312 int pos_arg_count = 0;
314 if (Arguments != null) {
315 pos_args = (ArrayList) Arguments [0];
316 if (pos_args != null)
317 pos_arg_count = pos_args.Count;
318 if (Arguments.Count > 1)
319 named_args = (ArrayList) Arguments [1];
322 pos_values = new object [pos_arg_count];
325 // First process positional arguments
329 for (i = 0; i < pos_arg_count; i++) {
330 Argument a = (Argument) pos_args [i];
333 if (!a.Resolve (ec, Location))
339 if (!GetAttributeArgumentExpression (e, Location, a.Type, out val))
342 pos_values [i] = val;
346 usage_attribute = new AttributeUsageAttribute ((AttributeTargets)val);
347 } else if (MethodImplAttr) {
348 this.ImplOptions = (MethodImplOptions) val;
349 } else if (GuidAttr){
351 // we will later check the validity of the type
354 if (!ValidateGuid ((string) val))
358 } else if (MarshalAsAttr)
360 (System.Runtime.InteropServices.UnmanagedType) val;
365 // Now process named arguments
368 ArrayList field_infos = null;
369 ArrayList prop_infos = null;
370 ArrayList field_values = null;
371 ArrayList prop_values = null;
373 if (named_args.Count > 0) {
374 field_infos = new ArrayList ();
375 prop_infos = new ArrayList ();
376 field_values = new ArrayList ();
377 prop_values = new ArrayList ();
380 Hashtable seen_names = new Hashtable();
382 for (i = 0; i < named_args.Count; i++) {
383 DictionaryEntry de = (DictionaryEntry) named_args [i];
384 string member_name = (string) de.Key;
385 Argument a = (Argument) de.Value;
388 if (seen_names.Contains(member_name)) {
389 Report.Error(643, Location, "'" + member_name + "' duplicate named attribute argument");
392 seen_names.Add(member_name, 1);
394 if (!a.Resolve (ec, Location))
397 Expression member = Expression.MemberLookup (
398 ec, Type, member_name,
399 MemberTypes.Field | MemberTypes.Property,
400 BindingFlags.Public | BindingFlags.Instance,
403 if (member == null) {
404 member = Expression.MemberLookup (ec, Type, member_name,
405 MemberTypes.Field | MemberTypes.Property, BindingFlags.NonPublic | BindingFlags.Instance,
408 if (member != null) {
409 Report.Error (122, Location, "'{0}' is inaccessible due to its protection level", GetFullMemberName (member_name));
414 if (member == null || !(member is PropertyExpr || member is FieldExpr)) {
415 Error_InvalidNamedArgument (member_name);
420 if (member is PropertyExpr) {
421 PropertyExpr pe = (PropertyExpr) member;
422 PropertyInfo pi = pe.PropertyInfo;
424 if (!pi.CanWrite || !pi.CanRead) {
425 Report.SymbolRelatedToPreviousError (pi);
426 Error_InvalidNamedArgument (member_name);
431 if (!GetAttributeArgumentExpression (e, Location, pi.PropertyType, out value))
434 if (usage_attribute != null) {
435 if (member_name == "AllowMultiple")
436 usage_attribute.AllowMultiple = (bool) value;
437 if (member_name == "Inherited")
438 usage_attribute.Inherited = (bool) value;
441 prop_values.Add (value);
444 } else if (member is FieldExpr) {
445 FieldExpr fe = (FieldExpr) member;
446 FieldInfo fi = fe.FieldInfo;
449 Error_InvalidNamedArgument (member_name);
454 if (!GetAttributeArgumentExpression (e, Location, fi.FieldType, out value))
457 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 = Invocation.GetParameterData (constructor);
487 int group_in_params_array = Int32.MaxValue;
489 if (pc > 0 && pd.ParameterModifier (pc-1) == Parameter.Modifier.PARAMS)
490 group_in_params_array = pc-1;
492 for (int j = 0; j < pos_arg_count; ++j) {
493 Argument a = (Argument) pos_args [j];
495 if (a.Expr is NullLiteral && pd.ParameterType (j) == TypeManager.object_type) {
496 Error_AttributeArgumentNotValid (Location);
500 if (j < group_in_params_array)
503 if (j == group_in_params_array){
504 object v = pos_values [j];
505 int count = pos_arg_count - j;
507 object [] array = new object [count];
508 pos_values [j] = array;
511 object [] array = (object []) pos_values [group_in_params_array];
513 array [j - group_in_params_array] = pos_values [j];
518 // Adjust the size of the pos_values if it had params
520 if (group_in_params_array != Int32.MaxValue){
521 int argc = group_in_params_array+1;
522 object [] new_pos_values = new object [argc];
524 for (int p = 0; p < argc; p++)
525 new_pos_values [p] = pos_values [p];
526 pos_values = new_pos_values;
530 if (named_args.Count > 0) {
531 prop_info_arr = new PropertyInfo [prop_infos.Count];
532 field_info_arr = new FieldInfo [field_infos.Count];
533 field_values_arr = new object [field_values.Count];
534 prop_values_arr = new object [prop_values.Count];
536 field_infos.CopyTo (field_info_arr, 0);
537 field_values.CopyTo (field_values_arr, 0);
539 prop_values.CopyTo (prop_values_arr, 0);
540 prop_infos.CopyTo (prop_info_arr, 0);
542 cb = new CustomAttributeBuilder (
543 (ConstructorInfo) constructor, pos_values,
544 prop_info_arr, prop_values_arr,
545 field_info_arr, field_values_arr);
548 cb = new CustomAttributeBuilder (
549 (ConstructorInfo) constructor, pos_values);
550 } catch (NullReferenceException) {
552 // Don't know what to do here
555 -101, Location, "NullReferenceException while trying to create attribute." +
556 "Something's wrong!");
557 } catch (Exception e) {
560 // using System.ComponentModel;
561 // [DefaultValue (CollectionChangeAction.Add)]
562 // class X { static void Main () {} }
565 -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);
572 /// Get a string containing a list of valid targets for the attribute 'attr'
574 public string GetValidTargets ()
576 StringBuilder sb = new StringBuilder ();
577 AttributeTargets targets = GetAttributeUsage ().ValidOn;
579 if ((targets & AttributeTargets.Assembly) != 0)
580 sb.Append ("'assembly' ");
582 if ((targets & AttributeTargets.Class) != 0)
583 sb.Append ("'class' ");
585 if ((targets & AttributeTargets.Constructor) != 0)
586 sb.Append ("'constructor' ");
588 if ((targets & AttributeTargets.Delegate) != 0)
589 sb.Append ("'delegate' ");
591 if ((targets & AttributeTargets.Enum) != 0)
592 sb.Append ("'enum' ");
594 if ((targets & AttributeTargets.Event) != 0)
595 sb.Append ("'event' ");
597 if ((targets & AttributeTargets.Field) != 0)
598 sb.Append ("'field' ");
600 if ((targets & AttributeTargets.Interface) != 0)
601 sb.Append ("'interface' ");
603 if ((targets & AttributeTargets.Method) != 0)
604 sb.Append ("'method' ");
606 if ((targets & AttributeTargets.Module) != 0)
607 sb.Append ("'module' ");
609 if ((targets & AttributeTargets.Parameter) != 0)
610 sb.Append ("'parameter' ");
612 if ((targets & AttributeTargets.Property) != 0)
613 sb.Append ("'property' ");
615 if ((targets & AttributeTargets.ReturnValue) != 0)
616 sb.Append ("'return' ");
618 if ((targets & AttributeTargets.Struct) != 0)
619 sb.Append ("'struct' ");
621 return sb.ToString ();
626 /// Returns AttributeUsage attribute for this type
628 public AttributeUsageAttribute GetAttributeUsage ()
630 AttributeUsageAttribute ua = usage_attr_cache [Type] as AttributeUsageAttribute;
634 Class attr_class = TypeManager.LookupClass (Type);
636 if (attr_class == null) {
637 object[] usage_attr = Type.GetCustomAttributes (TypeManager.attribute_usage_type, true);
638 ua = (AttributeUsageAttribute)usage_attr [0];
639 usage_attr_cache.Add (Type, ua);
643 return attr_class.AttributeUsage;
647 /// Returns custom name of indexer
649 public string GetIndexerAttributeValue (EmitContext ec)
651 if (pos_values == null) {
652 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
653 // But because a lot of attribute class code must be rewritten will be better to wait...
657 return pos_values [0] as string;
661 /// Returns condition of ConditionalAttribute
663 public string GetConditionalAttributeValue (DeclSpace ds)
665 if (pos_values == null) {
666 EmitContext ec = new EmitContext (ds, ds, Location, null, null, 0, false);
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 // Some error occurred
674 if (pos_values [0] == null)
677 return (string)pos_values [0];
681 /// Creates the instance of ObsoleteAttribute from this attribute instance
683 public ObsoleteAttribute GetObsoleteAttribute (DeclSpace ds)
685 if (pos_values == null) {
686 EmitContext ec = new EmitContext (ds, ds, Location, null, null, 0, false);
688 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
689 // But because a lot of attribute class code must be rewritten will be better to wait...
693 // Some error occurred
694 if (pos_values == null)
697 if (pos_values.Length == 0)
698 return new ObsoleteAttribute ();
700 if (pos_values.Length == 1)
701 return new ObsoleteAttribute ((string)pos_values [0]);
703 return new ObsoleteAttribute ((string)pos_values [0], (bool)pos_values [1]);
707 /// Returns value of CLSCompliantAttribute contructor parameter but because the method can be called
708 /// before ApplyAttribute. We need to resolve the arguments.
709 /// This situation occurs when class deps is differs from Emit order.
711 public bool GetClsCompliantAttributeValue (DeclSpace ds)
713 if (pos_values == null) {
714 EmitContext ec = new EmitContext (ds, ds, Location, null, null, 0, false);
716 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
717 // But because a lot of attribute class code must be rewritten will be better to wait...
721 // Some error occurred
722 if (pos_values [0] == null)
725 return (bool)pos_values [0];
729 /// Tests permitted SecurityAction for assembly or other types
731 public bool CheckSecurityActionValidity (bool for_assembly)
733 SecurityAction action = GetSecurityActionValue ();
735 if ((action == SecurityAction.RequestMinimum || action == SecurityAction.RequestOptional || action == SecurityAction.RequestRefuse) && for_assembly)
739 if (action < SecurityAction.Demand || action > SecurityAction.InheritanceDemand) {
740 Error_AttributeEmitError ("SecurityAction is out of range");
744 if ((action != SecurityAction.RequestMinimum && action != SecurityAction.RequestOptional && action != SecurityAction.RequestRefuse) && !for_assembly)
748 Error_AttributeEmitError (String.Concat ("SecurityAction '", action, "' is not valid for this declaration"));
752 System.Security.Permissions.SecurityAction GetSecurityActionValue ()
754 return (SecurityAction)pos_values [0];
758 /// Creates instance of SecurityAttribute class and add result of CreatePermission method to permission table.
760 /// <returns></returns>
761 public void ExtractSecurityPermissionSet (ListDictionary permissions)
763 if (TypeManager.LookupDeclSpace (Type) != null && RootContext.StdLib) {
764 Error_AttributeEmitError ("security custom attributes can not be referenced from defining assembly");
768 SecurityAttribute sa;
769 // For all assemblies except corlib we can avoid all hacks
770 if (RootContext.StdLib) {
771 sa = (SecurityAttribute) Activator.CreateInstance (Type, pos_values);
773 if (prop_info_arr != null) {
774 for (int i = 0; i < prop_info_arr.Length; ++i) {
775 PropertyInfo pi = prop_info_arr [i];
776 pi.SetValue (sa, prop_values_arr [i], null);
780 Type temp_type = Type.GetType (Type.FullName);
781 // HACK: All mscorlib attributes have same ctor syntax
782 sa = (SecurityAttribute) Activator.CreateInstance (temp_type, new object[] { GetSecurityActionValue () } );
784 // All types are from newly created corlib but for invocation with old we need to convert them
785 if (prop_info_arr != null) {
786 for (int i = 0; i < prop_info_arr.Length; ++i) {
787 PropertyInfo emited_pi = prop_info_arr [i];
788 PropertyInfo pi = temp_type.GetProperty (emited_pi.Name, emited_pi.PropertyType);
790 object old_instance = pi.PropertyType.IsEnum ?
791 System.Enum.ToObject (pi.PropertyType, prop_values_arr [i]) :
794 pi.SetValue (sa, old_instance, null);
799 IPermission perm = sa.CreatePermission ();
800 SecurityAction action;
802 // IS is correct because for corlib we are using an instance from old corlib
803 if (perm is System.Security.CodeAccessPermission) {
804 action = GetSecurityActionValue ();
806 switch (GetSecurityActionValue ()) {
807 case SecurityAction.Demand:
808 action = (SecurityAction)13;
810 case SecurityAction.LinkDemand:
811 action = (SecurityAction)14;
813 case SecurityAction.InheritanceDemand:
814 action = (SecurityAction)15;
817 Error_AttributeEmitError ("Invalid SecurityAction for non-Code Access Security permission");
822 PermissionSet ps = (PermissionSet)permissions [action];
824 ps = new PermissionSet (PermissionState.None);
825 permissions.Add (action, ps);
827 ps.AddPermission (sa.CreatePermission ());
830 object GetValue (object value)
832 if (value is EnumConstant)
833 return ((EnumConstant) value).GetValue ();
838 public object GetPositionalValue (int i)
840 return (pos_values == null) ? null : pos_values[i];
843 object GetFieldValue (string name)
846 if (field_info_arr == null)
849 foreach (FieldInfo fi in field_info_arr) {
851 return GetValue (field_values_arr [i]);
857 public UnmanagedMarshal GetMarshal (Attributable attr)
859 object value = GetFieldValue ("SizeParamIndex");
860 if (value != null && UnmanagedType != UnmanagedType.LPArray) {
861 Error_AttributeEmitError ("SizeParamIndex field is not valid for the specified unmanaged type");
865 object o = GetFieldValue ("ArraySubType");
866 UnmanagedType array_sub_type = o == null ? UnmanagedType.I4 : (UnmanagedType) o;
868 switch (UnmanagedType) {
869 case UnmanagedType.CustomMarshaler:
870 MethodInfo define_custom = typeof (UnmanagedMarshal).GetMethod ("DefineCustom",
871 BindingFlags.Static | BindingFlags.Public);
872 if (define_custom == null) {
873 Report.RuntimeMissingSupport (Location, "set marshal info");
877 object [] args = new object [4];
878 args [0] = GetFieldValue ("MarshalTypeRef");
879 args [1] = GetFieldValue ("MarshalCookie");
880 args [2] = GetFieldValue ("MarshalType");
881 args [3] = Guid.Empty;
882 return (UnmanagedMarshal) define_custom.Invoke (null, args);
884 case UnmanagedType.LPArray:
885 return UnmanagedMarshal.DefineLPArray (array_sub_type);
887 case UnmanagedType.SafeArray:
888 return UnmanagedMarshal.DefineSafeArray (array_sub_type);
890 case UnmanagedType.ByValArray:
891 FieldMember fm = attr as FieldMember;
893 Error_AttributeEmitError ("Specified unmanaged type is only valid on fields");
896 return UnmanagedMarshal.DefineByValArray ((int) GetFieldValue ("SizeConst"));
898 case UnmanagedType.ByValTStr:
899 return UnmanagedMarshal.DefineByValTStr ((int) GetFieldValue ("SizeConst"));
902 return UnmanagedMarshal.DefineUnmanagedMarshal (UnmanagedType);
906 public bool IsInternalCall
908 get { return ImplOptions == MethodImplOptions.InternalCall; }
912 /// Emit attribute for Attributable symbol
914 public void Emit (EmitContext ec, Attributable ias, ListDictionary emitted_attr)
916 CustomAttributeBuilder cb = Resolve (ec);
920 AttributeUsageAttribute usage_attr = GetAttributeUsage ();
921 if ((usage_attr.ValidOn & Target) == 0) {
922 Report.Error (592, Location, "Attribute '{0}' is not valid on this declaration type. It is valid on {1} declarations only.", Name, GetValidTargets ());
926 ias.ApplyAttributeBuilder (this, cb);
928 if (!usage_attr.AllowMultiple) {
929 ArrayList emitted_targets = (ArrayList)emitted_attr [Type];
930 if (emitted_targets == null) {
931 emitted_targets = new ArrayList ();
932 emitted_attr.Add (Type, emitted_targets);
933 } else if (emitted_targets.Contains (Target)) {
934 Report.Error (579, Location, "Duplicate '" + Name + "' attribute");
937 emitted_targets.Add (Target);
940 if (!RootContext.VerifyClsCompliance)
943 // Here we are testing attribute arguments for array usage (error 3016)
944 if (ias.IsClsCompliaceRequired (ec.DeclSpace)) {
945 if (Arguments == null)
948 ArrayList pos_args = (ArrayList) Arguments [0];
949 if (pos_args != null) {
950 foreach (Argument arg in pos_args) {
951 // Type is undefined (was error 246)
952 if (arg.Type == null)
955 if (arg.Type.IsArray) {
956 Report.Error (3016, Location, "Arrays as attribute arguments are not CLS-compliant");
962 if (Arguments.Count < 2)
965 ArrayList named_args = (ArrayList) Arguments [1];
966 foreach (DictionaryEntry de in named_args) {
967 Argument arg = (Argument) de.Value;
969 // Type is undefined (was error 246)
970 if (arg.Type == null)
973 if (arg.Type.IsArray) {
974 Report.Error (3016, Location, "Arrays as attribute arguments are not CLS-compliant");
981 public object GetValue (EmitContext ec, Constant c, Type target)
983 if (Convert.ImplicitConversionExists (ec, c, target))
984 return c.GetValue ();
986 Convert.Error_CannotImplicitConversion (Location, c.Type, target);
990 public MethodBuilder DefinePInvokeMethod (EmitContext ec, TypeBuilder builder, string name,
991 MethodAttributes flags, Type ret_type, Type [] param_types)
994 // We extract from the attribute the information we need
997 if (Arguments == null) {
998 Console.WriteLine ("Internal error : this is not supposed to happen !");
1002 ResolveType (ec, true);
1006 ArrayList named_args = new ArrayList ();
1008 ArrayList pos_args = (ArrayList) Arguments [0];
1009 if (Arguments.Count > 1)
1010 named_args = (ArrayList) Arguments [1];
1013 string dll_name = null;
1015 Argument tmp = (Argument) pos_args [0];
1017 if (!tmp.Resolve (ec, Location))
1020 if (tmp.Expr is Constant)
1021 dll_name = (string) ((Constant) tmp.Expr).GetValue ();
1023 Error_AttributeArgumentNotValid (Location);
1027 // Now we process the named arguments
1028 CallingConvention cc = CallingConvention.Winapi;
1029 CharSet charset = CharSet.Ansi;
1030 bool preserve_sig = true;
1032 bool exact_spelling = false;
1034 bool set_last_err = false;
1035 string entry_point = null;
1037 for (int i = 0; i < named_args.Count; i++) {
1039 DictionaryEntry de = (DictionaryEntry) named_args [i];
1041 string member_name = (string) de.Key;
1042 Argument a = (Argument) de.Value;
1044 if (!a.Resolve (ec, Location))
1047 Expression member = Expression.MemberLookup (
1048 ec, Type, member_name,
1049 MemberTypes.Field | MemberTypes.Property,
1050 BindingFlags.Public | BindingFlags.Instance,
1053 if (member == null || !(member is FieldExpr)) {
1054 Error_InvalidNamedArgument (member_name);
1058 if (member is FieldExpr) {
1059 FieldExpr fe = (FieldExpr) member;
1060 FieldInfo fi = fe.FieldInfo;
1062 if (fi.IsInitOnly) {
1063 Error_InvalidNamedArgument (member_name);
1067 if (a.Expr is Constant) {
1068 Constant c = (Constant) a.Expr;
1071 if (member_name == "CallingConvention"){
1072 object val = GetValue (ec, c, typeof (CallingConvention));
1075 cc = (CallingConvention) val;
1076 } else if (member_name == "CharSet"){
1077 charset = (CharSet) c.GetValue ();
1078 } else if (member_name == "EntryPoint")
1079 entry_point = (string) c.GetValue ();
1080 else if (member_name == "SetLastError")
1081 set_last_err = (bool) c.GetValue ();
1083 else if (member_name == "ExactSpelling")
1084 exact_spelling = (bool) c.GetValue ();
1086 else if (member_name == "PreserveSig")
1087 preserve_sig = (bool) c.GetValue ();
1088 } catch (InvalidCastException){
1089 Error_InvalidNamedArgument (member_name);
1090 Error_AttributeArgumentNotValid (Location);
1093 Error_AttributeArgumentNotValid (Location);
1100 if (entry_point == null)
1103 charset = (CharSet)((int)charset | 0x40);
1105 MethodBuilder mb = builder.DefinePInvokeMethod (
1106 name, dll_name, entry_point, flags | MethodAttributes.HideBySig,
1107 CallingConventions.Standard,
1114 mb.SetImplementationFlags (MethodImplAttributes.PreserveSig);
1119 private Expression GetValue ()
1121 if ((Arguments == null) || (Arguments.Count < 1))
1123 ArrayList al = (ArrayList) Arguments [0];
1124 if ((al == null) || (al.Count < 1))
1126 Argument arg = (Argument) al [0];
1127 if ((arg == null) || (arg.Expr == null))
1132 public string GetString ()
1134 Expression e = GetValue ();
1135 if (e is StringLiteral)
1136 return (e as StringLiteral).Value;
1140 public bool GetBoolean ()
1142 Expression e = GetValue ();
1143 if (e is BoolLiteral)
1144 return (e as BoolLiteral).Value;
1151 /// For global attributes (assembly, module) we need special handling.
1152 /// Attributes can be located in the several files
1154 public class GlobalAttribute: Attribute
1156 public readonly NamespaceEntry ns;
1158 public GlobalAttribute (TypeContainer container, string target, string name, ArrayList args, Location loc):
1159 base (target, name, args, loc)
1161 ns = container.NamespaceEntry;
1164 protected override Type CheckAttributeType (EmitContext ec, bool complain)
1166 NamespaceEntry old = ec.DeclSpace.NamespaceEntry;
1167 if (old == null || old.NS == null || old.NS == Namespace.Root)
1168 ec.DeclSpace.NamespaceEntry = ns;
1169 return base.CheckAttributeType (ec, complain);
1173 public class Attributes {
1174 public ArrayList Attrs;
1176 public Attributes (Attribute a)
1178 Attrs = new ArrayList ();
1182 public Attributes (ArrayList attrs)
1187 public void AddAttributes (ArrayList attrs)
1189 Attrs.AddRange (attrs);
1193 /// Checks whether attribute target is valid for the current element
1195 public void CheckTargets (Attributable member)
1197 string[] valid_targets = member.ValidAttributeTargets;
1198 foreach (Attribute a in Attrs) {
1199 if (a.ExplicitTarget == null || a.ExplicitTarget == valid_targets [0]) {
1200 a.Target = member.AttributeTargets;
1204 // TODO: we can skip the first item
1205 if (((IList) valid_targets).Contains (a.ExplicitTarget)) {
1206 switch (a.ExplicitTarget) {
1207 case "return": a.Target = AttributeTargets.ReturnValue; continue;
1208 case "param": a.Target = AttributeTargets.Parameter; continue;
1209 case "field": a.Target = AttributeTargets.Field; continue;
1210 case "method": a.Target = AttributeTargets.Method; continue;
1211 case "property": a.Target = AttributeTargets.Property; continue;
1213 throw new InternalErrorException ("Unknown explicit target: " + a.ExplicitTarget);
1216 StringBuilder sb = new StringBuilder ();
1217 foreach (string s in valid_targets) {
1221 sb.Remove (sb.Length - 2, 2);
1222 Report.Error (657, a.Location, "'{0}' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are '{1}'", a.Target, sb.ToString ());
1226 private Attribute Search (Type t, EmitContext ec, bool complain)
1228 foreach (Attribute a in Attrs) {
1229 if (a.ResolveType (ec, complain) == t)
1235 public Attribute Search (Type t, EmitContext ec)
1237 return Search (t, ec, true);
1241 /// Returns all attributes of type 't'. Use it when attribute is AllowMultiple = true
1243 public Attribute[] SearchMulti (Type t, EmitContext ec)
1245 ArrayList ar = null;
1247 foreach (Attribute a in Attrs) {
1248 if (a.ResolveType (ec, false) == t) {
1250 ar = new ArrayList ();
1255 return ar == null ? null : ar.ToArray (typeof (Attribute)) as Attribute[];
1258 public void Emit (EmitContext ec, Attributable ias)
1260 ListDictionary ld = new ListDictionary ();
1262 foreach (Attribute a in Attrs)
1263 a.Emit (ec, ias, ld);
1266 public bool Contains (Type t, EmitContext ec)
1268 return Search (t, ec) != null;
1271 public Attribute GetClsCompliantAttribute (EmitContext ec)
1273 return Search (TypeManager.cls_compliant_attribute_type, ec, false);
1277 /// Pulls the IndexerName attribute from an Indexer if it exists.
1279 public Attribute GetIndexerNameAttribute (EmitContext ec)
1281 Attribute a = Search (TypeManager.indexer_name_type, ec, false);
1285 // Remove the attribute from the list because it is not emitted
1293 /// Helper class for attribute verification routine.
1295 sealed class AttributeTester
1297 static PtrHashtable analyzed_types = new PtrHashtable ();
1298 static PtrHashtable analyzed_types_obsolete = new PtrHashtable ();
1299 static PtrHashtable analyzed_member_obsolete = new PtrHashtable ();
1300 static PtrHashtable analyzed_method_excluded = new PtrHashtable ();
1302 private AttributeTester ()
1307 /// Returns true if parameters of two compared methods are CLS-Compliant.
1308 /// It tests differing only in ref or out, or in array rank.
1310 public static bool AreOverloadedMethodParamsClsCompliant (Type[] types_a, Type[] types_b)
1312 if (types_a == null || types_b == null)
1315 if (types_a.Length != types_b.Length)
1318 for (int i = 0; i < types_b.Length; ++i) {
1319 Type aType = types_a [i];
1320 Type bType = types_b [i];
1322 if (aType.IsArray && bType.IsArray && aType.GetArrayRank () != bType.GetArrayRank () && aType.GetElementType () == bType.GetElementType ()) {
1326 Type aBaseType = aType;
1327 bool is_either_ref_or_out = false;
1329 if (aType.IsByRef || aType.IsPointer) {
1330 aBaseType = aType.GetElementType ();
1331 is_either_ref_or_out = true;
1334 Type bBaseType = bType;
1335 if (bType.IsByRef || bType.IsPointer)
1337 bBaseType = bType.GetElementType ();
1338 is_either_ref_or_out = !is_either_ref_or_out;
1341 if (aBaseType != bBaseType)
1344 if (is_either_ref_or_out)
1351 /// Goes through all parameters and test if they are CLS-Compliant.
1353 public static bool AreParametersCompliant (Parameter[] fixedParameters, Location loc)
1355 if (fixedParameters == null)
1358 foreach (Parameter arg in fixedParameters) {
1359 if (!AttributeTester.IsClsCompliant (arg.ParameterType)) {
1360 Report.Error (3001, loc, "Argument type '{0}' is not CLS-compliant", arg.GetSignatureForError ());
1369 /// This method tests the CLS compliance of external types. It doesn't test type visibility.
1371 public static bool IsClsCompliant (Type type)
1376 object type_compliance = analyzed_types[type];
1377 if (type_compliance != null)
1378 return type_compliance == TRUE;
1380 if (type.IsPointer) {
1381 analyzed_types.Add (type, null);
1386 if (type.IsArray || type.IsByRef) {
1387 result = IsClsCompliant (TypeManager.GetElementType (type));
1389 result = AnalyzeTypeCompliance (type);
1391 analyzed_types.Add (type, result ? TRUE : FALSE);
1395 static object TRUE = new object ();
1396 static object FALSE = new object ();
1398 public static void VerifyModulesClsCompliance ()
1400 Module[] modules = TypeManager.Modules;
1401 if (modules == null)
1404 // The first module is generated assembly
1405 for (int i = 1; i < modules.Length; ++i) {
1406 Module module = modules [i];
1407 if (!IsClsCompliant (module)) {
1408 Report.Error (3013, "Added modules must be marked with the CLSCompliant attribute to match the assembly", module.Name);
1415 /// Tests container name for CLS-Compliant name (differing only in case)
1417 public static void VerifyTopLevelNameClsCompliance ()
1419 Hashtable locase_table = new Hashtable ();
1421 // Convert imported type names to lower case and ignore not cls compliant
1422 foreach (DictionaryEntry de in TypeManager.all_imported_types) {
1423 Type t = (Type)de.Value;
1424 if (!AttributeTester.IsClsCompliant (t))
1427 locase_table.Add (((string)de.Key).ToLower (System.Globalization.CultureInfo.InvariantCulture), t);
1430 foreach (DictionaryEntry de in RootContext.Tree.Decls) {
1431 DeclSpace decl = (DeclSpace)de.Value;
1432 if (!decl.IsClsCompliaceRequired (decl))
1435 string lcase = decl.Name.ToLower (System.Globalization.CultureInfo.InvariantCulture);
1436 if (!locase_table.Contains (lcase)) {
1437 locase_table.Add (lcase, decl);
1441 object conflict = locase_table [lcase];
1442 if (conflict is Type)
1443 Report.SymbolRelatedToPreviousError ((Type)conflict);
1445 Report.SymbolRelatedToPreviousError ((MemberCore)conflict);
1447 Report.Error (3005, decl.Location, "Identifier '{0}' differing only in case is not CLS-compliant", decl.GetSignatureForError ());
1451 static bool IsClsCompliant (ICustomAttributeProvider attribute_provider)
1453 object[] CompliantAttribute = attribute_provider.GetCustomAttributes (TypeManager.cls_compliant_attribute_type, false);
1454 if (CompliantAttribute.Length == 0)
1457 return ((CLSCompliantAttribute)CompliantAttribute[0]).IsCompliant;
1460 static bool AnalyzeTypeCompliance (Type type)
1462 DeclSpace ds = TypeManager.LookupDeclSpace (type);
1464 return ds.IsClsCompliaceRequired (ds.Parent);
1467 object[] CompliantAttribute = type.GetCustomAttributes (TypeManager.cls_compliant_attribute_type, false);
1468 if (CompliantAttribute.Length == 0)
1469 return IsClsCompliant (type.Assembly);
1471 return ((CLSCompliantAttribute)CompliantAttribute[0]).IsCompliant;
1475 /// Returns instance of ObsoleteAttribute when type is obsolete
1477 public static ObsoleteAttribute GetObsoleteAttribute (Type type)
1479 object type_obsolete = analyzed_types_obsolete [type];
1480 if (type_obsolete == FALSE)
1483 if (type_obsolete != null)
1484 return (ObsoleteAttribute)type_obsolete;
1486 ObsoleteAttribute result = null;
1487 if (type.IsByRef || type.IsArray || type.IsPointer) {
1488 result = GetObsoleteAttribute (TypeManager.GetElementType (type));
1490 DeclSpace type_ds = TypeManager.LookupDeclSpace (type);
1492 // Type is external, we can get attribute directly
1493 if (type_ds == null) {
1494 object[] attribute = type.GetCustomAttributes (TypeManager.obsolete_attribute_type, false);
1495 if (attribute.Length == 1)
1496 result = (ObsoleteAttribute)attribute [0];
1498 result = type_ds.GetObsoleteAttribute (type_ds);
1502 analyzed_types_obsolete.Add (type, result == null ? FALSE : result);
1507 /// Returns instance of ObsoleteAttribute when method is obsolete
1509 public static ObsoleteAttribute GetMethodObsoleteAttribute (MethodBase mb)
1511 IMethodData mc = TypeManager.GetMethod (mb);
1513 return mc.GetObsoleteAttribute ();
1515 // compiler generated methods are not registered by AddMethod
1516 if (mb.DeclaringType is TypeBuilder)
1519 return GetMemberObsoleteAttribute (mb);
1523 /// Returns instance of ObsoleteAttribute when member is obsolete
1525 public static ObsoleteAttribute GetMemberObsoleteAttribute (MemberInfo mi)
1527 object type_obsolete = analyzed_member_obsolete [mi];
1528 if (type_obsolete == FALSE)
1531 if (type_obsolete != null)
1532 return (ObsoleteAttribute)type_obsolete;
1534 ObsoleteAttribute oa = System.Attribute.GetCustomAttribute (mi, TypeManager.obsolete_attribute_type, false) as ObsoleteAttribute;
1535 analyzed_member_obsolete.Add (mi, oa == null ? FALSE : oa);
1540 /// Common method for Obsolete error/warning reporting.
1542 public static void Report_ObsoleteMessage (ObsoleteAttribute oa, string member, Location loc)
1545 Report.Error (619, loc, "'{0}' is obsolete: '{1}'", member, oa.Message);
1549 if (oa.Message == null) {
1550 Report.Warning (612, loc, "'{0}' is obsolete", member);
1553 if (RootContext.WarningLevel >= 2)
1554 Report.Warning (618, loc, "'{0}' is obsolete: '{1}'", member, oa.Message);
1557 public static bool IsConditionalMethodExcluded (MethodBase mb)
1559 object excluded = analyzed_method_excluded [mb];
1560 if (excluded != null)
1561 return excluded == TRUE ? true : false;
1563 ConditionalAttribute[] attrs = mb.GetCustomAttributes (TypeManager.conditional_attribute_type, true) as ConditionalAttribute[];
1564 if (attrs.Length == 0) {
1565 analyzed_method_excluded.Add (mb, FALSE);
1569 foreach (ConditionalAttribute a in attrs) {
1570 if (RootContext.AllDefines.Contains (a.ConditionString)) {
1571 analyzed_method_excluded.Add (mb, FALSE);
1575 analyzed_method_excluded.Add (mb, TRUE);