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 ?)");
195 resolve_error = true;
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 virtual CustomAttributeBuilder Resolve (EmitContext ec)
274 resolve_error = true;
279 Type = CheckAttributeType (ec);
281 if (oldType == null && Type == null)
283 if (oldType != null && oldType != Type){
284 Report.Error (-27, Location,
285 "Attribute {0} resolved to different types at different times: {1} vs. {2}",
286 Name, oldType, Type);
290 if (Type.IsAbstract) {
291 Report.Error (653, Location, "Cannot apply attribute class '{0}' because it is abstract", Name);
295 bool MethodImplAttr = false;
296 bool MarshalAsAttr = false;
297 bool GuidAttr = false;
298 bool usage_attr = false;
300 bool DoCompares = true;
303 // If we are a certain special attribute, we
304 // set the information accordingly
307 if (Type == TypeManager.attribute_usage_type)
309 else if (Type == TypeManager.methodimpl_attr_type)
310 MethodImplAttr = true;
311 else if (Type == TypeManager.marshal_as_attr_type)
312 MarshalAsAttr = true;
313 else if (Type == TypeManager.guid_attr_type)
318 // Now we extract the positional and named arguments
320 ArrayList pos_args = new ArrayList ();
321 ArrayList named_args = new ArrayList ();
322 int pos_arg_count = 0;
324 if (Arguments != null) {
325 pos_args = (ArrayList) Arguments [0];
326 if (pos_args != null)
327 pos_arg_count = pos_args.Count;
328 if (Arguments.Count > 1)
329 named_args = (ArrayList) Arguments [1];
332 pos_values = new object [pos_arg_count];
335 // First process positional arguments
339 for (i = 0; i < pos_arg_count; i++) {
340 Argument a = (Argument) pos_args [i];
343 if (!a.Resolve (ec, Location))
349 if (!GetAttributeArgumentExpression (e, Location, a.Type, out val))
352 pos_values [i] = val;
357 Report.Error (591, Location, "Invalid value for argument to 'System.AttributeUsage' attribute");
360 usage_attribute = new AttributeUsageAttribute ((AttributeTargets)val);
361 } else if (MethodImplAttr) {
362 this.ImplOptions = (MethodImplOptions) val;
363 } else if (GuidAttr){
365 // we will later check the validity of the type
368 if (!ValidateGuid ((string) val))
372 } else if (MarshalAsAttr)
374 (System.Runtime.InteropServices.UnmanagedType) val;
379 // Now process named arguments
382 ArrayList field_infos = null;
383 ArrayList prop_infos = null;
384 ArrayList field_values = null;
385 ArrayList prop_values = null;
387 if (named_args.Count > 0) {
388 field_infos = new ArrayList ();
389 prop_infos = new ArrayList ();
390 field_values = new ArrayList ();
391 prop_values = new ArrayList ();
394 Hashtable seen_names = new Hashtable();
396 for (i = 0; i < named_args.Count; i++) {
397 DictionaryEntry de = (DictionaryEntry) named_args [i];
398 string member_name = (string) de.Key;
399 Argument a = (Argument) de.Value;
402 if (seen_names.Contains(member_name)) {
403 Report.Error(643, Location, "'" + member_name + "' duplicate named attribute argument");
406 seen_names.Add(member_name, 1);
408 if (!a.Resolve (ec, Location))
411 Expression member = Expression.MemberLookup (
412 ec, Type, member_name,
413 MemberTypes.Field | MemberTypes.Property,
414 BindingFlags.Public | BindingFlags.Instance,
417 if (member == null) {
418 member = Expression.MemberLookup (ec, Type, member_name,
419 MemberTypes.Field | MemberTypes.Property, BindingFlags.NonPublic | BindingFlags.Instance,
422 if (member != null) {
423 Report.Error (122, Location, "'{0}' is inaccessible due to its protection level", GetFullMemberName (member_name));
429 Report.Error (117, Location, "Attribute `{0}' does not contain a definition for `{1}'",
434 if (!(member is PropertyExpr || member is FieldExpr)) {
435 Error_InvalidNamedArgument (member_name);
440 if (member is PropertyExpr) {
441 PropertyExpr pe = (PropertyExpr) member;
442 PropertyInfo pi = pe.PropertyInfo;
444 if (!pi.CanWrite || !pi.CanRead) {
445 Report.SymbolRelatedToPreviousError (pi);
446 Error_InvalidNamedArgument (member_name);
451 if (!GetAttributeArgumentExpression (e, Location, pi.PropertyType, out value))
454 if (usage_attribute != null) {
455 if (member_name == "AllowMultiple")
456 usage_attribute.AllowMultiple = (bool) value;
457 if (member_name == "Inherited")
458 usage_attribute.Inherited = (bool) value;
461 prop_values.Add (value);
464 } else if (member is FieldExpr) {
465 FieldExpr fe = (FieldExpr) member;
466 FieldInfo fi = fe.FieldInfo;
469 Error_InvalidNamedArgument (member_name);
474 if (!GetAttributeArgumentExpression (e, Location, fi.FieldType, out value))
477 field_values.Add (value);
478 field_infos.Add (fi);
482 Expression mg = Expression.MemberLookup (
483 ec, Type, ".ctor", MemberTypes.Constructor,
484 BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly,
488 Error_AttributeConstructorMismatch ();
492 MethodBase constructor = Invocation.OverloadResolve (
493 ec, (MethodGroupExpr) mg, pos_args, false, Location);
495 if (constructor == null) {
500 // Now we perform some checks on the positional args as they
501 // cannot be null for a constructor which expects a parameter
505 ParameterData pd = Invocation.GetParameterData (constructor);
507 int last_real_param = pd.Count;
509 // When the params is not filled we need to put one
510 if (last_real_param > pos_arg_count) {
511 object [] new_pos_values = new object [pos_arg_count + 1];
512 pos_values.CopyTo (new_pos_values, 0);
513 new_pos_values [pos_arg_count] = new object [] {} ;
514 pos_values = new_pos_values;
519 for (int j = 0; j < pos_arg_count; ++j) {
520 Argument a = (Argument) pos_args [j];
522 if (a.Expr is NullLiteral && pd.ParameterType (j) == TypeManager.object_type) {
523 Error_AttributeArgumentNotValid (Location);
527 if (j < last_real_param)
530 if (j == last_real_param) {
531 object [] array = new object [pos_arg_count - last_real_param];
532 array [0] = pos_values [j];
533 pos_values [j] = array;
537 object [] params_array = (object []) pos_values [last_real_param];
538 params_array [j - last_real_param] = pos_values [j];
541 // Adjust the size of the pos_values if it had params
542 if (last_real_param != pos_arg_count) {
543 object [] new_pos_values = new object [last_real_param + 1];
544 Array.Copy (pos_values, new_pos_values, last_real_param + 1);
545 pos_values = new_pos_values;
549 if (named_args.Count > 0) {
550 prop_info_arr = new PropertyInfo [prop_infos.Count];
551 field_info_arr = new FieldInfo [field_infos.Count];
552 field_values_arr = new object [field_values.Count];
553 prop_values_arr = new object [prop_values.Count];
555 field_infos.CopyTo (field_info_arr, 0);
556 field_values.CopyTo (field_values_arr, 0);
558 prop_values.CopyTo (prop_values_arr, 0);
559 prop_infos.CopyTo (prop_info_arr, 0);
561 cb = new CustomAttributeBuilder (
562 (ConstructorInfo) constructor, pos_values,
563 prop_info_arr, prop_values_arr,
564 field_info_arr, field_values_arr);
567 cb = new CustomAttributeBuilder (
568 (ConstructorInfo) constructor, pos_values);
569 } catch (Exception e) {
572 // using System.ComponentModel;
573 // [DefaultValue (CollectionChangeAction.Add)]
574 // class X { static void Main () {} }
576 Error_AttributeArgumentNotValid (Location);
580 resolve_error = false;
585 /// Get a string containing a list of valid targets for the attribute 'attr'
587 public string GetValidTargets ()
589 StringBuilder sb = new StringBuilder ();
590 AttributeTargets targets = GetAttributeUsage ().ValidOn;
592 if ((targets & AttributeTargets.Assembly) != 0)
593 sb.Append ("'assembly' ");
595 if ((targets & AttributeTargets.Class) != 0)
596 sb.Append ("'class' ");
598 if ((targets & AttributeTargets.Constructor) != 0)
599 sb.Append ("'constructor' ");
601 if ((targets & AttributeTargets.Delegate) != 0)
602 sb.Append ("'delegate' ");
604 if ((targets & AttributeTargets.Enum) != 0)
605 sb.Append ("'enum' ");
607 if ((targets & AttributeTargets.Event) != 0)
608 sb.Append ("'event' ");
610 if ((targets & AttributeTargets.Field) != 0)
611 sb.Append ("'field' ");
613 if ((targets & AttributeTargets.Interface) != 0)
614 sb.Append ("'interface' ");
616 if ((targets & AttributeTargets.Method) != 0)
617 sb.Append ("'method' ");
619 if ((targets & AttributeTargets.Module) != 0)
620 sb.Append ("'module' ");
622 if ((targets & AttributeTargets.Parameter) != 0)
623 sb.Append ("'parameter' ");
625 if ((targets & AttributeTargets.Property) != 0)
626 sb.Append ("'property' ");
628 if ((targets & AttributeTargets.ReturnValue) != 0)
629 sb.Append ("'return' ");
631 if ((targets & AttributeTargets.Struct) != 0)
632 sb.Append ("'struct' ");
634 return sb.ToString ();
639 /// Returns AttributeUsage attribute for this type
641 public AttributeUsageAttribute GetAttributeUsage ()
643 AttributeUsageAttribute ua = usage_attr_cache [Type] as AttributeUsageAttribute;
647 Class attr_class = TypeManager.LookupClass (Type);
649 if (attr_class == null) {
650 object[] usage_attr = Type.GetCustomAttributes (TypeManager.attribute_usage_type, true);
651 ua = (AttributeUsageAttribute)usage_attr [0];
652 usage_attr_cache.Add (Type, ua);
656 return attr_class.AttributeUsage;
660 /// Returns custom name of indexer
662 public string GetIndexerAttributeValue (EmitContext ec)
664 if (pos_values == null)
665 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
666 // 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 (EmitContext ec)
677 if (pos_values == null)
678 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
679 // But because a lot of attribute class code must be rewritten will be better to wait...
682 // Some error occurred
683 if (pos_values [0] == null)
686 return (string)pos_values [0];
690 /// Creates the instance of ObsoleteAttribute from this attribute instance
692 public ObsoleteAttribute GetObsoleteAttribute (EmitContext ec)
694 if (pos_values == null)
695 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
696 // But because a lot of attribute class code must be rewritten will be better to wait...
699 // Some error occurred
700 if (pos_values == null)
703 if (pos_values.Length == 0)
704 return new ObsoleteAttribute ();
706 if (pos_values.Length == 1)
707 return new ObsoleteAttribute ((string)pos_values [0]);
709 return new ObsoleteAttribute ((string)pos_values [0], (bool)pos_values [1]);
713 /// Returns value of CLSCompliantAttribute contructor parameter but because the method can be called
714 /// before ApplyAttribute. We need to resolve the arguments.
715 /// This situation occurs when class deps is differs from Emit order.
717 public bool GetClsCompliantAttributeValue (EmitContext ec)
719 if (pos_values == null)
720 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
721 // But because a lot of attribute class code must be rewritten will be better to wait...
724 // Some error occurred
725 if (pos_values [0] == null)
728 return (bool)pos_values [0];
732 /// Tests permitted SecurityAction for assembly or other types
734 public bool CheckSecurityActionValidity (bool for_assembly)
736 SecurityAction action = GetSecurityActionValue ();
738 if ((action == SecurityAction.RequestMinimum || action == SecurityAction.RequestOptional || action == SecurityAction.RequestRefuse) && for_assembly)
742 if (action < SecurityAction.Demand || action > SecurityAction.InheritanceDemand) {
743 Error_AttributeEmitError ("SecurityAction is out of range");
747 if ((action != SecurityAction.RequestMinimum && action != SecurityAction.RequestOptional && action != SecurityAction.RequestRefuse) && !for_assembly)
751 Error_AttributeEmitError (String.Concat ("SecurityAction '", action, "' is not valid for this declaration"));
755 System.Security.Permissions.SecurityAction GetSecurityActionValue ()
757 return (SecurityAction)pos_values [0];
761 /// Creates instance of SecurityAttribute class and add result of CreatePermission method to permission table.
763 /// <returns></returns>
764 public void ExtractSecurityPermissionSet (ListDictionary permissions)
766 if (TypeManager.LookupDeclSpace (Type) != null && RootContext.StdLib) {
767 Error_AttributeEmitError ("security custom attributes can not be referenced from defining assembly");
771 SecurityAttribute sa;
772 // For all assemblies except corlib we can avoid all hacks
773 if (RootContext.StdLib) {
774 sa = (SecurityAttribute) Activator.CreateInstance (Type, pos_values);
776 if (prop_info_arr != null) {
777 for (int i = 0; i < prop_info_arr.Length; ++i) {
778 PropertyInfo pi = prop_info_arr [i];
779 pi.SetValue (sa, prop_values_arr [i], null);
783 Type temp_type = Type.GetType (Type.FullName);
784 // HACK: All mscorlib attributes have same ctor syntax
785 sa = (SecurityAttribute) Activator.CreateInstance (temp_type, new object[] { GetSecurityActionValue () } );
787 // All types are from newly created corlib but for invocation with old we need to convert them
788 if (prop_info_arr != null) {
789 for (int i = 0; i < prop_info_arr.Length; ++i) {
790 PropertyInfo emited_pi = prop_info_arr [i];
791 PropertyInfo pi = temp_type.GetProperty (emited_pi.Name, emited_pi.PropertyType);
793 object old_instance = pi.PropertyType.IsEnum ?
794 System.Enum.ToObject (pi.PropertyType, prop_values_arr [i]) :
797 pi.SetValue (sa, old_instance, null);
802 IPermission perm = sa.CreatePermission ();
803 SecurityAction action;
805 // IS is correct because for corlib we are using an instance from old corlib
806 if (perm is System.Security.CodeAccessPermission) {
807 action = GetSecurityActionValue ();
809 switch (GetSecurityActionValue ()) {
810 case SecurityAction.Demand:
811 action = (SecurityAction)13;
813 case SecurityAction.LinkDemand:
814 action = (SecurityAction)14;
816 case SecurityAction.InheritanceDemand:
817 action = (SecurityAction)15;
820 Error_AttributeEmitError ("Invalid SecurityAction for non-Code Access Security permission");
825 PermissionSet ps = (PermissionSet)permissions [action];
827 ps = new PermissionSet (PermissionState.None);
828 permissions.Add (action, ps);
830 ps.AddPermission (sa.CreatePermission ());
833 object GetValue (object value)
835 if (value is EnumConstant)
836 return ((EnumConstant) value).GetValue ();
841 public object GetPositionalValue (int i)
843 return (pos_values == null) ? null : pos_values[i];
846 object GetFieldValue (string name)
849 if (field_info_arr == null)
852 foreach (FieldInfo fi in field_info_arr) {
854 return GetValue (field_values_arr [i]);
860 public UnmanagedMarshal GetMarshal (Attributable attr)
862 object value = GetFieldValue ("SizeParamIndex");
863 if (value != null && UnmanagedType != UnmanagedType.LPArray) {
864 Error_AttributeEmitError ("SizeParamIndex field is not valid for the specified unmanaged type");
868 object o = GetFieldValue ("ArraySubType");
869 UnmanagedType array_sub_type = o == null ? UnmanagedType.I4 : (UnmanagedType) o;
871 switch (UnmanagedType) {
872 case UnmanagedType.CustomMarshaler:
873 MethodInfo define_custom = typeof (UnmanagedMarshal).GetMethod ("DefineCustom",
874 BindingFlags.Static | BindingFlags.Public);
875 if (define_custom == null) {
876 Report.RuntimeMissingSupport (Location, "set marshal info");
880 object [] args = new object [4];
881 args [0] = GetFieldValue ("MarshalTypeRef");
882 args [1] = GetFieldValue ("MarshalCookie");
883 args [2] = GetFieldValue ("MarshalType");
884 args [3] = Guid.Empty;
885 return (UnmanagedMarshal) define_custom.Invoke (null, args);
887 case UnmanagedType.LPArray:
888 return UnmanagedMarshal.DefineLPArray (array_sub_type);
890 case UnmanagedType.SafeArray:
891 return UnmanagedMarshal.DefineSafeArray (array_sub_type);
893 case UnmanagedType.ByValArray:
894 FieldMember fm = attr as FieldMember;
896 Error_AttributeEmitError ("Specified unmanaged type is only valid on fields");
899 return UnmanagedMarshal.DefineByValArray ((int) GetFieldValue ("SizeConst"));
901 case UnmanagedType.ByValTStr:
902 return UnmanagedMarshal.DefineByValTStr ((int) GetFieldValue ("SizeConst"));
905 return UnmanagedMarshal.DefineUnmanagedMarshal (UnmanagedType);
909 public bool IsInternalCall
911 get { return ImplOptions == MethodImplOptions.InternalCall; }
915 /// Emit attribute for Attributable symbol
917 public void Emit (EmitContext ec, Attributable ias, ListDictionary emitted_attr)
919 CustomAttributeBuilder cb = Resolve (ec);
923 AttributeUsageAttribute usage_attr = GetAttributeUsage ();
924 if ((usage_attr.ValidOn & Target) == 0) {
925 Report.Error (592, Location, "Attribute '{0}' is not valid on this declaration type. It is valid on {1} declarations only.", Name, GetValidTargets ());
929 ias.ApplyAttributeBuilder (this, cb);
931 if (!usage_attr.AllowMultiple) {
932 ArrayList emitted_targets = (ArrayList)emitted_attr [Type];
933 if (emitted_targets == null) {
934 emitted_targets = new ArrayList ();
935 emitted_attr.Add (Type, emitted_targets);
936 } else if (emitted_targets.Contains (Target)) {
937 Report.Error (579, Location, "Duplicate '" + Name + "' attribute");
940 emitted_targets.Add (Target);
943 if (!RootContext.VerifyClsCompliance)
946 // Here we are testing attribute arguments for array usage (error 3016)
947 if (ias.IsClsCompliaceRequired (ec.DeclSpace)) {
948 if (Arguments == null)
951 ArrayList pos_args = (ArrayList) Arguments [0];
952 if (pos_args != null) {
953 foreach (Argument arg in pos_args) {
954 // Type is undefined (was error 246)
955 if (arg.Type == null)
958 if (arg.Type.IsArray) {
959 Report.Error (3016, Location, "Arrays as attribute arguments are not CLS-compliant");
965 if (Arguments.Count < 2)
968 ArrayList named_args = (ArrayList) Arguments [1];
969 foreach (DictionaryEntry de in named_args) {
970 Argument arg = (Argument) de.Value;
972 // Type is undefined (was error 246)
973 if (arg.Type == null)
976 if (arg.Type.IsArray) {
977 Report.Error (3016, Location, "Arrays as attribute arguments are not CLS-compliant");
984 public object GetValue (EmitContext ec, Constant c, Type target)
986 if (Convert.ImplicitConversionExists (ec, c, target))
987 return c.GetValue ();
989 Convert.Error_CannotImplicitConversion (Location, c.Type, target);
993 public MethodBuilder DefinePInvokeMethod (EmitContext ec, TypeBuilder builder, string name,
994 MethodAttributes flags, Type ret_type, Type [] param_types)
997 // We extract from the attribute the information we need
1000 if (Arguments == null) {
1001 Console.WriteLine ("Internal error : this is not supposed to happen !");
1009 ArrayList named_args = new ArrayList ();
1011 ArrayList pos_args = (ArrayList) Arguments [0];
1012 if (Arguments.Count > 1)
1013 named_args = (ArrayList) Arguments [1];
1016 string dll_name = null;
1018 Argument tmp = (Argument) pos_args [0];
1020 if (!tmp.Resolve (ec, Location))
1023 if (tmp.Expr is Constant)
1024 dll_name = (string) ((Constant) tmp.Expr).GetValue ();
1026 Error_AttributeArgumentNotValid (Location);
1030 // Now we process the named arguments
1031 CallingConvention cc = CallingConvention.Winapi;
1032 CharSet charset = CharSet.Ansi;
1033 bool preserve_sig = true;
1035 bool exact_spelling = false;
1037 bool set_last_err = false;
1038 string entry_point = null;
1040 for (int i = 0; i < named_args.Count; i++) {
1042 DictionaryEntry de = (DictionaryEntry) named_args [i];
1044 string member_name = (string) de.Key;
1045 Argument a = (Argument) de.Value;
1047 if (!a.Resolve (ec, Location))
1050 Expression member = Expression.MemberLookup (
1051 ec, Type, member_name,
1052 MemberTypes.Field | MemberTypes.Property,
1053 BindingFlags.Public | BindingFlags.Instance,
1056 if (member == null || !(member is FieldExpr)) {
1057 Error_InvalidNamedArgument (member_name);
1061 if (member is FieldExpr) {
1062 FieldExpr fe = (FieldExpr) member;
1063 FieldInfo fi = fe.FieldInfo;
1065 if (fi.IsInitOnly) {
1066 Error_InvalidNamedArgument (member_name);
1070 if (a.Expr is Constant) {
1071 Constant c = (Constant) a.Expr;
1074 if (member_name == "CallingConvention"){
1075 object val = GetValue (ec, c, typeof (CallingConvention));
1078 cc = (CallingConvention) val;
1079 } else if (member_name == "CharSet"){
1080 charset = (CharSet) c.GetValue ();
1081 } else if (member_name == "EntryPoint")
1082 entry_point = (string) c.GetValue ();
1083 else if (member_name == "SetLastError")
1084 set_last_err = (bool) c.GetValue ();
1086 else if (member_name == "ExactSpelling")
1087 exact_spelling = (bool) c.GetValue ();
1089 else if (member_name == "PreserveSig")
1090 preserve_sig = (bool) c.GetValue ();
1091 } catch (InvalidCastException){
1092 Error_InvalidNamedArgument (member_name);
1093 Error_AttributeArgumentNotValid (Location);
1096 Error_AttributeArgumentNotValid (Location);
1103 if (entry_point == null)
1106 charset = (CharSet)((int)charset | 0x40);
1108 MethodBuilder mb = builder.DefinePInvokeMethod (
1109 name, dll_name, entry_point, flags | MethodAttributes.HideBySig,
1110 CallingConventions.Standard,
1117 mb.SetImplementationFlags (MethodImplAttributes.PreserveSig);
1122 private Expression GetValue ()
1124 if ((Arguments == null) || (Arguments.Count < 1))
1126 ArrayList al = (ArrayList) Arguments [0];
1127 if ((al == null) || (al.Count < 1))
1129 Argument arg = (Argument) al [0];
1130 if ((arg == null) || (arg.Expr == null))
1135 public string GetString ()
1137 Expression e = GetValue ();
1138 if (e is StringLiteral)
1139 return (e as StringLiteral).Value;
1143 public bool GetBoolean ()
1145 Expression e = GetValue ();
1146 if (e is BoolLiteral)
1147 return (e as BoolLiteral).Value;
1154 /// For global attributes (assembly, module) we need special handling.
1155 /// Attributes can be located in the several files
1157 public class GlobalAttribute: Attribute
1159 public readonly NamespaceEntry ns;
1161 public GlobalAttribute (TypeContainer container, string target, string name, ArrayList args, Location loc):
1162 base (target, name, args, loc)
1164 ns = container.NamespaceEntry;
1167 protected override Type CheckAttributeType (EmitContext ec)
1169 // RootContext.Tree.Types has a single NamespaceEntry which gets overwritten
1170 // each time a new file is parsed. However, we need to use the NamespaceEntry
1171 // in effect where the attribute was used. Since code elsewhere cannot assume
1172 // that the NamespaceEntry is right, just overwrite it.
1174 // Precondition: RootContext.Tree.Types == null || RootContext.Tree.Types == ns.
1175 // The second case happens when we are recursively invoked from inside Emit.
1177 NamespaceEntry old = null;
1178 if (ec.DeclSpace == RootContext.Tree.Types) {
1179 old = ec.DeclSpace.NamespaceEntry;
1180 ec.DeclSpace.NamespaceEntry = ns;
1181 if (old != null && old != ns)
1182 throw new InternalErrorException (Location + " non-null NamespaceEntry " + old);
1185 Type retval = base.CheckAttributeType (ec);
1187 if (ec.DeclSpace == RootContext.Tree.Types)
1188 ec.DeclSpace.NamespaceEntry = old;
1193 public override CustomAttributeBuilder Resolve (EmitContext ec)
1195 if (ec.DeclSpace == RootContext.Tree.Types) {
1196 NamespaceEntry old = ec.DeclSpace.NamespaceEntry;
1197 ec.DeclSpace.NamespaceEntry = ns;
1199 throw new InternalErrorException (Location + " non-null NamespaceEntry " + old);
1202 CustomAttributeBuilder retval = base.Resolve (ec);
1204 if (ec.DeclSpace == RootContext.Tree.Types)
1205 ec.DeclSpace.NamespaceEntry = null;
1211 public class Attributes {
1212 public ArrayList Attrs;
1214 public Attributes (Attribute a)
1216 Attrs = new ArrayList ();
1220 public Attributes (ArrayList attrs)
1225 public void AddAttributes (ArrayList attrs)
1227 Attrs.AddRange (attrs);
1231 /// Checks whether attribute target is valid for the current element
1233 public bool CheckTargets (Attributable member)
1235 string[] valid_targets = member.ValidAttributeTargets;
1236 foreach (Attribute a in Attrs) {
1237 if (a.ExplicitTarget == null || a.ExplicitTarget == valid_targets [0]) {
1238 a.Target = member.AttributeTargets;
1242 // TODO: we can skip the first item
1243 if (((IList) valid_targets).Contains (a.ExplicitTarget)) {
1244 switch (a.ExplicitTarget) {
1245 case "return": a.Target = AttributeTargets.ReturnValue; continue;
1246 case "param": a.Target = AttributeTargets.Parameter; continue;
1247 case "field": a.Target = AttributeTargets.Field; continue;
1248 case "method": a.Target = AttributeTargets.Method; continue;
1249 case "property": a.Target = AttributeTargets.Property; continue;
1251 throw new InternalErrorException ("Unknown explicit target: " + a.ExplicitTarget);
1254 StringBuilder sb = new StringBuilder ();
1255 foreach (string s in valid_targets) {
1259 sb.Remove (sb.Length - 2, 2);
1260 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 ());
1266 public Attribute Search (Type t, EmitContext ec)
1268 foreach (Attribute a in Attrs) {
1269 if (a.ResolveType (ec) == t)
1276 /// Returns all attributes of type 't'. Use it when attribute is AllowMultiple = true
1278 public Attribute[] SearchMulti (Type t, EmitContext ec)
1280 ArrayList ar = null;
1282 foreach (Attribute a in Attrs) {
1283 if (a.ResolveType (ec) == t) {
1285 ar = new ArrayList ();
1290 return ar == null ? null : ar.ToArray (typeof (Attribute)) as Attribute[];
1293 public void Emit (EmitContext ec, Attributable ias)
1295 if (!CheckTargets (ias))
1298 ListDictionary ld = new ListDictionary ();
1300 foreach (Attribute a in Attrs)
1301 a.Emit (ec, ias, ld);
1304 public bool Contains (Type t, EmitContext ec)
1306 return Search (t, ec) != null;
1311 /// Helper class for attribute verification routine.
1313 sealed class AttributeTester
1315 static PtrHashtable analyzed_types = new PtrHashtable ();
1316 static PtrHashtable analyzed_types_obsolete = new PtrHashtable ();
1317 static PtrHashtable analyzed_member_obsolete = new PtrHashtable ();
1318 static PtrHashtable analyzed_method_excluded = new PtrHashtable ();
1320 private AttributeTester ()
1325 /// Returns true if parameters of two compared methods are CLS-Compliant.
1326 /// It tests differing only in ref or out, or in array rank.
1328 public static bool AreOverloadedMethodParamsClsCompliant (Type[] types_a, Type[] types_b)
1330 if (types_a == null || types_b == null)
1333 if (types_a.Length != types_b.Length)
1336 for (int i = 0; i < types_b.Length; ++i) {
1337 Type aType = types_a [i];
1338 Type bType = types_b [i];
1340 if (aType.IsArray && bType.IsArray && aType.GetArrayRank () != bType.GetArrayRank () && aType.GetElementType () == bType.GetElementType ()) {
1344 Type aBaseType = aType;
1345 bool is_either_ref_or_out = false;
1347 if (aType.IsByRef || aType.IsPointer) {
1348 aBaseType = aType.GetElementType ();
1349 is_either_ref_or_out = true;
1352 Type bBaseType = bType;
1353 if (bType.IsByRef || bType.IsPointer)
1355 bBaseType = bType.GetElementType ();
1356 is_either_ref_or_out = !is_either_ref_or_out;
1359 if (aBaseType != bBaseType)
1362 if (is_either_ref_or_out)
1369 /// Goes through all parameters and test if they are CLS-Compliant.
1371 public static bool AreParametersCompliant (Parameter[] fixedParameters, Location loc)
1373 if (fixedParameters == null)
1376 foreach (Parameter arg in fixedParameters) {
1377 if (!AttributeTester.IsClsCompliant (arg.ParameterType)) {
1378 Report.Error (3001, loc, "Argument type '{0}' is not CLS-compliant", arg.GetSignatureForError ());
1387 /// This method tests the CLS compliance of external types. It doesn't test type visibility.
1389 public static bool IsClsCompliant (Type type)
1394 object type_compliance = analyzed_types[type];
1395 if (type_compliance != null)
1396 return type_compliance == TRUE;
1398 if (type.IsPointer) {
1399 analyzed_types.Add (type, null);
1404 if (type.IsArray || type.IsByRef) {
1405 result = IsClsCompliant (TypeManager.GetElementType (type));
1407 result = AnalyzeTypeCompliance (type);
1409 analyzed_types.Add (type, result ? TRUE : FALSE);
1413 static object TRUE = new object ();
1414 static object FALSE = new object ();
1416 public static void VerifyModulesClsCompliance ()
1418 Module[] modules = TypeManager.Modules;
1419 if (modules == null)
1422 // The first module is generated assembly
1423 for (int i = 1; i < modules.Length; ++i) {
1424 Module module = modules [i];
1425 if (!IsClsCompliant (module)) {
1426 Report.Error (3013, "Added modules must be marked with the CLSCompliant attribute to match the assembly", module.Name);
1433 /// Tests container name for CLS-Compliant name (differing only in case)
1435 public static void VerifyTopLevelNameClsCompliance ()
1437 Hashtable locase_table = new Hashtable ();
1439 // Convert imported type names to lower case and ignore not cls compliant
1440 foreach (DictionaryEntry de in TypeManager.all_imported_types) {
1441 Type t = (Type)de.Value;
1442 if (!AttributeTester.IsClsCompliant (t))
1445 locase_table.Add (((string)de.Key).ToLower (System.Globalization.CultureInfo.InvariantCulture), t);
1448 foreach (DictionaryEntry de in RootContext.Tree.Decls) {
1449 DeclSpace decl = (DeclSpace)de.Value;
1450 if (!decl.IsClsCompliaceRequired (decl))
1453 string lcase = decl.Name.ToLower (System.Globalization.CultureInfo.InvariantCulture);
1454 if (!locase_table.Contains (lcase)) {
1455 locase_table.Add (lcase, decl);
1459 object conflict = locase_table [lcase];
1460 if (conflict is Type)
1461 Report.SymbolRelatedToPreviousError ((Type)conflict);
1463 Report.SymbolRelatedToPreviousError ((MemberCore)conflict);
1465 Report.Error (3005, decl.Location, "Identifier '{0}' differing only in case is not CLS-compliant", decl.GetSignatureForError ());
1469 static bool IsClsCompliant (ICustomAttributeProvider attribute_provider)
1471 object[] CompliantAttribute = attribute_provider.GetCustomAttributes (TypeManager.cls_compliant_attribute_type, false);
1472 if (CompliantAttribute.Length == 0)
1475 return ((CLSCompliantAttribute)CompliantAttribute[0]).IsCompliant;
1478 static bool AnalyzeTypeCompliance (Type type)
1480 DeclSpace ds = TypeManager.LookupDeclSpace (type);
1482 return ds.IsClsCompliaceRequired (ds.Parent);
1485 object[] CompliantAttribute = type.GetCustomAttributes (TypeManager.cls_compliant_attribute_type, false);
1486 if (CompliantAttribute.Length == 0)
1487 return IsClsCompliant (type.Assembly);
1489 return ((CLSCompliantAttribute)CompliantAttribute[0]).IsCompliant;
1493 /// Returns instance of ObsoleteAttribute when type is obsolete
1495 public static ObsoleteAttribute GetObsoleteAttribute (Type type)
1497 object type_obsolete = analyzed_types_obsolete [type];
1498 if (type_obsolete == FALSE)
1501 if (type_obsolete != null)
1502 return (ObsoleteAttribute)type_obsolete;
1504 ObsoleteAttribute result = null;
1505 if (type.IsByRef || type.IsArray || type.IsPointer) {
1506 result = GetObsoleteAttribute (TypeManager.GetElementType (type));
1508 DeclSpace type_ds = TypeManager.LookupDeclSpace (type);
1510 // Type is external, we can get attribute directly
1511 if (type_ds == null) {
1512 object[] attribute = type.GetCustomAttributes (TypeManager.obsolete_attribute_type, false);
1513 if (attribute.Length == 1)
1514 result = (ObsoleteAttribute)attribute [0];
1516 result = type_ds.GetObsoleteAttribute (type_ds);
1520 analyzed_types_obsolete.Add (type, result == null ? FALSE : result);
1525 /// Returns instance of ObsoleteAttribute when method is obsolete
1527 public static ObsoleteAttribute GetMethodObsoleteAttribute (MethodBase mb)
1529 IMethodData mc = TypeManager.GetMethod (mb);
1531 return mc.GetObsoleteAttribute ();
1533 // compiler generated methods are not registered by AddMethod
1534 if (mb.DeclaringType is TypeBuilder)
1537 return GetMemberObsoleteAttribute (mb);
1541 /// Returns instance of ObsoleteAttribute when member is obsolete
1543 public static ObsoleteAttribute GetMemberObsoleteAttribute (MemberInfo mi)
1545 object type_obsolete = analyzed_member_obsolete [mi];
1546 if (type_obsolete == FALSE)
1549 if (type_obsolete != null)
1550 return (ObsoleteAttribute)type_obsolete;
1552 ObsoleteAttribute oa = System.Attribute.GetCustomAttribute (mi, TypeManager.obsolete_attribute_type, false) as ObsoleteAttribute;
1553 analyzed_member_obsolete.Add (mi, oa == null ? FALSE : oa);
1558 /// Common method for Obsolete error/warning reporting.
1560 public static void Report_ObsoleteMessage (ObsoleteAttribute oa, string member, Location loc)
1563 Report.Error (619, loc, "'{0}' is obsolete: '{1}'", member, oa.Message);
1567 if (oa.Message == null) {
1568 Report.Warning (612, loc, "'{0}' is obsolete", member);
1571 if (RootContext.WarningLevel >= 2)
1572 Report.Warning (618, loc, "'{0}' is obsolete: '{1}'", member, oa.Message);
1575 public static bool IsConditionalMethodExcluded (MethodBase mb)
1577 object excluded = analyzed_method_excluded [mb];
1578 if (excluded != null)
1579 return excluded == TRUE ? true : false;
1581 ConditionalAttribute[] attrs = mb.GetCustomAttributes (TypeManager.conditional_attribute_type, true) as ConditionalAttribute[];
1582 if (attrs.Length == 0) {
1583 analyzed_method_excluded.Add (mb, FALSE);
1587 foreach (ConditionalAttribute a in attrs) {
1588 if (RootContext.AllDefines.Contains (a.ConditionString)) {
1589 analyzed_method_excluded.Add (mb, FALSE);
1593 analyzed_method_excluded.Add (mb, TRUE);