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 (string extra, Location loc)
122 Report.Error (182, loc,
123 "An attribute argument must be a constant expression, typeof " +
124 "expression or array creation expression" + extra);
127 static void Error_AttributeArgumentNotValid (Location loc)
129 Error_AttributeArgumentNotValid ("", loc);
134 /// This is rather hack. We report many emit attribute error with same error to be compatible with
135 /// csc. But because csc has to report them this way because error came from ilasm we needn't.
137 public void Error_AttributeEmitError (string inner)
139 Report.Error (647, Location, "Error emitting '{0}' attribute because '{1}'", Name, inner);
142 public void Error_InvalidSecurityParent ()
144 Error_AttributeEmitError ("it is attached to invalid parent");
147 void Error_AttributeConstructorMismatch ()
149 Report.Error (-6, Location,
150 "Could not find a constructor for this argument list.");
154 /// Tries to resolve the type of the attribute. Flags an error if it can't, and complain is true.
156 protected virtual Type CheckAttributeType (EmitContext ec)
158 string NameAttribute = Name + "Attribute";
160 Type t1 = ec.ResolvingTypeTree
161 ? ec.DeclSpace.FindType (Location, Name)
162 : RootContext.LookupType (ec.DeclSpace, Name, true, Location);
164 // FIXME: Shouldn't do this for quoted attributes: [@A]
165 Type t2 = ec.ResolvingTypeTree
166 ? ec.DeclSpace.FindType (Location, NameAttribute)
167 : RootContext.LookupType (ec.DeclSpace, NameAttribute, true, Location);
169 String err0616 = null;
171 if (t1 != null && ! t1.IsSubclassOf (TypeManager.attribute_type)) {
173 err0616 = "'" + Name + "': is not an attribute class";
175 if (t2 != null && ! t2.IsSubclassOf (TypeManager.attribute_type)) {
177 err0616 = (err0616 != null)
178 ? "Neither '" + Name + "' nor '" + NameAttribute +"' is an attribute class"
179 : "'" + Name + "Attribute': is not an attribute class";
182 if (t1 != null && t2 != null) {
183 Report.Error(1614, Location, "'" + Name + "': is ambiguous; "
184 + " use either '@" + Name + "' or '" + NameAttribute + "'");
192 if (err0616 != null) {
193 Report.Error (616, Location, err0616);
197 Report.Error (246, Location,
198 "Could not find attribute '" + Name
199 + "' (are you missing a using directive or an assembly reference ?)");
201 resolve_error = true;
205 public Type ResolveType (EmitContext ec)
208 Type = CheckAttributeType (ec);
213 /// Validates the guid string
215 bool ValidateGuid (string guid)
221 Report.Error (647, Location, "Format of GUID is invalid: " + guid);
226 string GetFullMemberName (string member)
228 return Type.FullName + '.' + member;
232 // Given an expression, if the expression is a valid attribute-argument-expression
233 // returns an object that can be used to encode it, or null on failure.
235 public static bool GetAttributeArgumentExpression (Expression e, Location loc, Type arg_type, out object result)
237 if (e is EnumConstant) {
238 if (RootContext.StdLib)
239 result = ((EnumConstant)e).GetValueAsEnumType ();
241 result = ((EnumConstant)e).GetValue ();
246 Constant constant = e as Constant;
247 if (constant != null) {
248 if (e.Type != arg_type) {
249 constant = Const.ChangeType (loc, constant, arg_type);
250 if (constant == null) {
252 Error_AttributeArgumentNotValid (loc);
256 result = constant.GetValue ();
258 } else if (e is TypeOf) {
259 result = ((TypeOf) e).TypeArg;
261 } else if (e is ArrayCreation){
262 result = ((ArrayCreation) e).EncodeAsAttribute ();
265 } else if (e is EmptyCast) {
266 Expression child = ((EmptyCast)e).Child;
267 return GetAttributeArgumentExpression (child, loc, child.Type, out result);
271 Error_AttributeArgumentNotValid (loc);
275 public virtual CustomAttributeBuilder Resolve (EmitContext ec)
280 resolve_error = true;
285 Type = CheckAttributeType (ec);
287 if (oldType == null && Type == null)
289 if (oldType != null && oldType != Type){
290 Report.Error (-27, Location,
291 "Attribute {0} resolved to different types at different times: {1} vs. {2}",
292 Name, oldType, Type);
296 if (Type.IsAbstract) {
297 Report.Error (653, Location, "Cannot apply attribute class '{0}' because it is abstract", Name);
301 bool MethodImplAttr = false;
302 bool MarshalAsAttr = false;
303 bool GuidAttr = false;
304 bool usage_attr = false;
306 bool DoCompares = true;
309 // If we are a certain special attribute, we
310 // set the information accordingly
313 if (Type == TypeManager.attribute_usage_type)
315 else if (Type == TypeManager.methodimpl_attr_type)
316 MethodImplAttr = true;
317 else if (Type == TypeManager.marshal_as_attr_type)
318 MarshalAsAttr = true;
319 else if (Type == TypeManager.guid_attr_type)
324 // Now we extract the positional and named arguments
326 ArrayList pos_args = new ArrayList ();
327 ArrayList named_args = new ArrayList ();
328 int pos_arg_count = 0;
330 if (Arguments != null) {
331 pos_args = (ArrayList) Arguments [0];
332 if (pos_args != null)
333 pos_arg_count = pos_args.Count;
334 if (Arguments.Count > 1)
335 named_args = (ArrayList) Arguments [1];
338 pos_values = new object [pos_arg_count];
341 // First process positional arguments
345 for (i = 0; i < pos_arg_count; i++) {
346 Argument a = (Argument) pos_args [i];
349 if (!a.Resolve (ec, Location))
355 if (!GetAttributeArgumentExpression (e, Location, a.Type, out val))
358 pos_values [i] = val;
363 Report.Error (591, Location, "Invalid value for argument to 'System.AttributeUsage' attribute");
366 usage_attribute = new AttributeUsageAttribute ((AttributeTargets)val);
367 } else if (MethodImplAttr) {
368 this.ImplOptions = (MethodImplOptions) val;
369 } else if (GuidAttr){
371 // we will later check the validity of the type
374 if (!ValidateGuid ((string) val))
378 } else if (MarshalAsAttr)
380 (System.Runtime.InteropServices.UnmanagedType) val;
385 // Now process named arguments
388 ArrayList field_infos = null;
389 ArrayList prop_infos = null;
390 ArrayList field_values = null;
391 ArrayList prop_values = null;
393 if (named_args.Count > 0) {
394 field_infos = new ArrayList ();
395 prop_infos = new ArrayList ();
396 field_values = new ArrayList ();
397 prop_values = new ArrayList ();
400 Hashtable seen_names = new Hashtable();
402 for (i = 0; i < named_args.Count; i++) {
403 DictionaryEntry de = (DictionaryEntry) named_args [i];
404 string member_name = (string) de.Key;
405 Argument a = (Argument) de.Value;
408 if (seen_names.Contains(member_name)) {
409 Report.Error(643, Location, "'" + member_name + "' duplicate named attribute argument");
412 seen_names.Add(member_name, 1);
414 if (!a.Resolve (ec, Location))
417 Expression member = Expression.MemberLookup (
418 ec, Type, member_name,
419 MemberTypes.Field | MemberTypes.Property,
420 BindingFlags.Public | BindingFlags.Instance,
423 if (member == null) {
424 member = Expression.MemberLookup (ec, Type, member_name,
425 MemberTypes.Field | MemberTypes.Property, BindingFlags.NonPublic | BindingFlags.Instance,
428 if (member != null) {
429 Report.Error (122, Location, "'{0}' is inaccessible due to its protection level", GetFullMemberName (member_name));
435 Report.Error (117, Location, "Attribute `{0}' does not contain a definition for `{1}'",
440 if (!(member is PropertyExpr || member is FieldExpr)) {
441 Error_InvalidNamedArgument (member_name);
446 if (member is PropertyExpr) {
447 PropertyExpr pe = (PropertyExpr) member;
448 PropertyInfo pi = pe.PropertyInfo;
450 if (!pi.CanWrite || !pi.CanRead) {
451 Report.SymbolRelatedToPreviousError (pi);
452 Error_InvalidNamedArgument (member_name);
457 if (!GetAttributeArgumentExpression (e, Location, pi.PropertyType, out value))
460 if (usage_attribute != null) {
461 if (member_name == "AllowMultiple")
462 usage_attribute.AllowMultiple = (bool) value;
463 if (member_name == "Inherited")
464 usage_attribute.Inherited = (bool) value;
467 prop_values.Add (value);
470 } else if (member is FieldExpr) {
471 FieldExpr fe = (FieldExpr) member;
472 FieldInfo fi = fe.FieldInfo;
475 Error_InvalidNamedArgument (member_name);
480 if (!GetAttributeArgumentExpression (e, Location, fi.FieldType, out value))
483 field_values.Add (value);
484 field_infos.Add (fi);
488 Expression mg = Expression.MemberLookup (
489 ec, Type, ".ctor", MemberTypes.Constructor,
490 BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly,
494 Error_AttributeConstructorMismatch ();
498 MethodBase constructor = Invocation.OverloadResolve (
499 ec, (MethodGroupExpr) mg, pos_args, false, Location);
501 if (constructor == null) {
506 // Now we perform some checks on the positional args as they
507 // cannot be null for a constructor which expects a parameter
511 ParameterData pd = Invocation.GetParameterData (constructor);
513 int last_real_param = pd.Count;
515 // When the params is not filled we need to put one
516 if (last_real_param > pos_arg_count) {
517 object [] new_pos_values = new object [pos_arg_count + 1];
518 pos_values.CopyTo (new_pos_values, 0);
519 new_pos_values [pos_arg_count] = new object [] {} ;
520 pos_values = new_pos_values;
525 for (int j = 0; j < pos_arg_count; ++j) {
526 Argument a = (Argument) pos_args [j];
528 if (a.Expr is NullLiteral && pd.ParameterType (j) == TypeManager.object_type) {
529 Error_AttributeArgumentNotValid (Location);
533 if (j < last_real_param)
536 if (j == last_real_param) {
537 object [] array = new object [pos_arg_count - last_real_param];
538 array [0] = pos_values [j];
539 pos_values [j] = array;
543 object [] params_array = (object []) pos_values [last_real_param];
544 params_array [j - last_real_param] = pos_values [j];
547 // Adjust the size of the pos_values if it had params
548 if (last_real_param != pos_arg_count) {
549 object [] new_pos_values = new object [last_real_param + 1];
550 Array.Copy (pos_values, new_pos_values, last_real_param + 1);
551 pos_values = new_pos_values;
555 if (named_args.Count > 0) {
556 prop_info_arr = new PropertyInfo [prop_infos.Count];
557 field_info_arr = new FieldInfo [field_infos.Count];
558 field_values_arr = new object [field_values.Count];
559 prop_values_arr = new object [prop_values.Count];
561 field_infos.CopyTo (field_info_arr, 0);
562 field_values.CopyTo (field_values_arr, 0);
564 prop_values.CopyTo (prop_values_arr, 0);
565 prop_infos.CopyTo (prop_info_arr, 0);
567 cb = new CustomAttributeBuilder (
568 (ConstructorInfo) constructor, pos_values,
569 prop_info_arr, prop_values_arr,
570 field_info_arr, field_values_arr);
573 cb = new CustomAttributeBuilder (
574 (ConstructorInfo) constructor, pos_values);
575 } catch (Exception e) {
578 // using System.ComponentModel;
579 // [DefaultValue (CollectionChangeAction.Add)]
580 // class X { static void Main () {} }
582 Error_AttributeArgumentNotValid (Location);
586 resolve_error = false;
591 /// Get a string containing a list of valid targets for the attribute 'attr'
593 public string GetValidTargets ()
595 StringBuilder sb = new StringBuilder ();
596 AttributeTargets targets = GetAttributeUsage ().ValidOn;
598 if ((targets & AttributeTargets.Assembly) != 0)
599 sb.Append ("'assembly' ");
601 if ((targets & AttributeTargets.Class) != 0)
602 sb.Append ("'class' ");
604 if ((targets & AttributeTargets.Constructor) != 0)
605 sb.Append ("'constructor' ");
607 if ((targets & AttributeTargets.Delegate) != 0)
608 sb.Append ("'delegate' ");
610 if ((targets & AttributeTargets.Enum) != 0)
611 sb.Append ("'enum' ");
613 if ((targets & AttributeTargets.Event) != 0)
614 sb.Append ("'event' ");
616 if ((targets & AttributeTargets.Field) != 0)
617 sb.Append ("'field' ");
619 if ((targets & AttributeTargets.Interface) != 0)
620 sb.Append ("'interface' ");
622 if ((targets & AttributeTargets.Method) != 0)
623 sb.Append ("'method' ");
625 if ((targets & AttributeTargets.Module) != 0)
626 sb.Append ("'module' ");
628 if ((targets & AttributeTargets.Parameter) != 0)
629 sb.Append ("'parameter' ");
631 if ((targets & AttributeTargets.Property) != 0)
632 sb.Append ("'property' ");
634 if ((targets & AttributeTargets.ReturnValue) != 0)
635 sb.Append ("'return' ");
637 if ((targets & AttributeTargets.Struct) != 0)
638 sb.Append ("'struct' ");
640 return sb.ToString ();
645 /// Returns AttributeUsage attribute for this type
647 public AttributeUsageAttribute GetAttributeUsage ()
649 AttributeUsageAttribute ua = usage_attr_cache [Type] as AttributeUsageAttribute;
653 Class attr_class = TypeManager.LookupClass (Type);
655 if (attr_class == null) {
656 object[] usage_attr = Type.GetCustomAttributes (TypeManager.attribute_usage_type, true);
657 ua = (AttributeUsageAttribute)usage_attr [0];
658 usage_attr_cache.Add (Type, ua);
662 return attr_class.AttributeUsage;
666 /// Returns custom name of indexer
668 public string GetIndexerAttributeValue (EmitContext ec)
670 if (pos_values == null)
671 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
672 // But because a lot of attribute class code must be rewritten will be better to wait...
675 return pos_values [0] as string;
679 /// Returns condition of ConditionalAttribute
681 public string GetConditionalAttributeValue (EmitContext ec)
683 if (pos_values == null)
684 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
685 // But because a lot of attribute class code must be rewritten will be better to wait...
688 // Some error occurred
689 if (pos_values [0] == null)
692 return (string)pos_values [0];
696 /// Creates the instance of ObsoleteAttribute from this attribute instance
698 public ObsoleteAttribute GetObsoleteAttribute (EmitContext ec)
700 if (pos_values == null)
701 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
702 // 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 (EmitContext ec)
725 if (pos_values == null)
726 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
727 // But because a lot of attribute class code must be rewritten will be better to wait...
730 // Some error occurred
731 if (pos_values [0] == null)
734 return (bool)pos_values [0];
738 /// Tests permitted SecurityAction for assembly or other types
740 public bool CheckSecurityActionValidity (bool for_assembly)
742 SecurityAction action = GetSecurityActionValue ();
744 if ((action == SecurityAction.RequestMinimum || action == SecurityAction.RequestOptional || action == SecurityAction.RequestRefuse) && for_assembly)
748 if (action < SecurityAction.Demand || action > SecurityAction.InheritanceDemand) {
749 Error_AttributeEmitError ("SecurityAction is out of range");
753 if ((action != SecurityAction.RequestMinimum && action != SecurityAction.RequestOptional && action != SecurityAction.RequestRefuse) && !for_assembly)
757 Error_AttributeEmitError (String.Concat ("SecurityAction '", action, "' is not valid for this declaration"));
761 System.Security.Permissions.SecurityAction GetSecurityActionValue ()
763 return (SecurityAction)pos_values [0];
767 /// Creates instance of SecurityAttribute class and add result of CreatePermission method to permission table.
769 /// <returns></returns>
770 public void ExtractSecurityPermissionSet (ListDictionary permissions)
772 if (TypeManager.LookupDeclSpace (Type) != null && RootContext.StdLib) {
773 Error_AttributeEmitError ("security custom attributes can not be referenced from defining assembly");
777 SecurityAttribute sa;
778 // For all assemblies except corlib we can avoid all hacks
779 if (RootContext.StdLib) {
780 sa = (SecurityAttribute) Activator.CreateInstance (Type, pos_values);
782 if (prop_info_arr != null) {
783 for (int i = 0; i < prop_info_arr.Length; ++i) {
784 PropertyInfo pi = prop_info_arr [i];
785 pi.SetValue (sa, prop_values_arr [i], null);
789 Type temp_type = Type.GetType (Type.FullName);
790 // HACK: All mscorlib attributes have same ctor syntax
791 sa = (SecurityAttribute) Activator.CreateInstance (temp_type, new object[] { GetSecurityActionValue () } );
793 // All types are from newly created corlib but for invocation with old we need to convert them
794 if (prop_info_arr != null) {
795 for (int i = 0; i < prop_info_arr.Length; ++i) {
796 PropertyInfo emited_pi = prop_info_arr [i];
797 PropertyInfo pi = temp_type.GetProperty (emited_pi.Name, emited_pi.PropertyType);
799 object old_instance = pi.PropertyType.IsEnum ?
800 System.Enum.ToObject (pi.PropertyType, prop_values_arr [i]) :
803 pi.SetValue (sa, old_instance, null);
808 IPermission perm = sa.CreatePermission ();
809 SecurityAction action;
811 // IS is correct because for corlib we are using an instance from old corlib
812 if (perm is System.Security.CodeAccessPermission) {
813 action = GetSecurityActionValue ();
815 switch (GetSecurityActionValue ()) {
816 case SecurityAction.Demand:
817 action = (SecurityAction)13;
819 case SecurityAction.LinkDemand:
820 action = (SecurityAction)14;
822 case SecurityAction.InheritanceDemand:
823 action = (SecurityAction)15;
826 Error_AttributeEmitError ("Invalid SecurityAction for non-Code Access Security permission");
831 PermissionSet ps = (PermissionSet)permissions [action];
833 ps = new PermissionSet (PermissionState.None);
834 permissions.Add (action, ps);
836 ps.AddPermission (sa.CreatePermission ());
839 object GetValue (object value)
841 if (value is EnumConstant)
842 return ((EnumConstant) value).GetValue ();
847 public object GetPositionalValue (int i)
849 return (pos_values == null) ? null : pos_values[i];
852 object GetFieldValue (string name)
855 if (field_info_arr == null)
858 foreach (FieldInfo fi in field_info_arr) {
860 return GetValue (field_values_arr [i]);
866 public UnmanagedMarshal GetMarshal (Attributable attr)
868 object value = GetFieldValue ("SizeParamIndex");
869 if (value != null && UnmanagedType != UnmanagedType.LPArray) {
870 Error_AttributeEmitError ("SizeParamIndex field is not valid for the specified unmanaged type");
874 object o = GetFieldValue ("ArraySubType");
875 UnmanagedType array_sub_type = o == null ? UnmanagedType.I4 : (UnmanagedType) o;
877 switch (UnmanagedType) {
878 case UnmanagedType.CustomMarshaler:
879 MethodInfo define_custom = typeof (UnmanagedMarshal).GetMethod ("DefineCustom",
880 BindingFlags.Static | BindingFlags.Public);
881 if (define_custom == null) {
882 Report.RuntimeMissingSupport (Location, "set marshal info");
886 object [] args = new object [4];
887 args [0] = GetFieldValue ("MarshalTypeRef");
888 args [1] = GetFieldValue ("MarshalCookie");
889 args [2] = GetFieldValue ("MarshalType");
890 args [3] = Guid.Empty;
891 return (UnmanagedMarshal) define_custom.Invoke (null, args);
893 case UnmanagedType.LPArray:
894 return UnmanagedMarshal.DefineLPArray (array_sub_type);
896 case UnmanagedType.SafeArray:
897 return UnmanagedMarshal.DefineSafeArray (array_sub_type);
899 case UnmanagedType.ByValArray:
900 FieldMember fm = attr as FieldMember;
902 Error_AttributeEmitError ("Specified unmanaged type is only valid on fields");
905 return UnmanagedMarshal.DefineByValArray ((int) GetFieldValue ("SizeConst"));
907 case UnmanagedType.ByValTStr:
908 return UnmanagedMarshal.DefineByValTStr ((int) GetFieldValue ("SizeConst"));
911 return UnmanagedMarshal.DefineUnmanagedMarshal (UnmanagedType);
915 public bool IsInternalCall
917 get { return ImplOptions == MethodImplOptions.InternalCall; }
921 /// Emit attribute for Attributable symbol
923 public void Emit (EmitContext ec, Attributable ias, ListDictionary emitted_attr)
925 CustomAttributeBuilder cb = Resolve (ec);
929 AttributeUsageAttribute usage_attr = GetAttributeUsage ();
930 if ((usage_attr.ValidOn & Target) == 0) {
931 Report.Error (592, Location, "Attribute '{0}' is not valid on this declaration type. It is valid on {1} declarations only.", Name, GetValidTargets ());
935 ias.ApplyAttributeBuilder (this, cb);
937 if (!usage_attr.AllowMultiple) {
938 ArrayList emitted_targets = (ArrayList)emitted_attr [Type];
939 if (emitted_targets == null) {
940 emitted_targets = new ArrayList ();
941 emitted_attr.Add (Type, emitted_targets);
942 } else if (emitted_targets.Contains (Target)) {
943 Report.Error (579, Location, "Duplicate '" + Name + "' attribute");
946 emitted_targets.Add (Target);
949 if (!RootContext.VerifyClsCompliance)
952 // Here we are testing attribute arguments for array usage (error 3016)
953 if (ias.IsClsCompliaceRequired (ec.DeclSpace)) {
954 if (Arguments == null)
957 ArrayList pos_args = (ArrayList) Arguments [0];
958 if (pos_args != null) {
959 foreach (Argument arg in pos_args) {
960 // Type is undefined (was error 246)
961 if (arg.Type == null)
964 if (arg.Type.IsArray) {
965 Report.Error (3016, Location, "Arrays as attribute arguments are not CLS-compliant");
971 if (Arguments.Count < 2)
974 ArrayList named_args = (ArrayList) Arguments [1];
975 foreach (DictionaryEntry de in named_args) {
976 Argument arg = (Argument) de.Value;
978 // Type is undefined (was error 246)
979 if (arg.Type == null)
982 if (arg.Type.IsArray) {
983 Report.Error (3016, Location, "Arrays as attribute arguments are not CLS-compliant");
990 public object GetValue (EmitContext ec, Constant c, Type target)
992 if (Convert.ImplicitConversionExists (ec, c, target))
993 return c.GetValue ();
995 Convert.Error_CannotImplicitConversion (Location, c.Type, target);
999 public MethodBuilder DefinePInvokeMethod (EmitContext ec, TypeBuilder builder, string name,
1000 MethodAttributes flags, Type ret_type, Type [] param_types)
1003 // We extract from the attribute the information we need
1006 if (Arguments == null) {
1007 Console.WriteLine ("Internal error : this is not supposed to happen !");
1015 ArrayList named_args = new ArrayList ();
1017 ArrayList pos_args = (ArrayList) Arguments [0];
1018 if (Arguments.Count > 1)
1019 named_args = (ArrayList) Arguments [1];
1022 string dll_name = null;
1024 Argument tmp = (Argument) pos_args [0];
1026 if (!tmp.Resolve (ec, Location))
1029 if (tmp.Expr is Constant)
1030 dll_name = (string) ((Constant) tmp.Expr).GetValue ();
1032 Error_AttributeArgumentNotValid (Location);
1035 if (dll_name == null || dll_name == ""){
1036 Error_AttributeArgumentNotValid (": DllImport requires a non-empty string", Location);
1040 // Now we process the named arguments
1041 CallingConvention cc = CallingConvention.Winapi;
1042 CharSet charset = CharSet.Ansi;
1043 bool preserve_sig = true;
1045 bool exact_spelling = false;
1047 bool set_last_err = false;
1048 string entry_point = null;
1050 for (int i = 0; i < named_args.Count; i++) {
1052 DictionaryEntry de = (DictionaryEntry) named_args [i];
1054 string member_name = (string) de.Key;
1055 Argument a = (Argument) de.Value;
1057 if (!a.Resolve (ec, Location))
1060 Expression member = Expression.MemberLookup (
1061 ec, Type, member_name,
1062 MemberTypes.Field | MemberTypes.Property,
1063 BindingFlags.Public | BindingFlags.Instance,
1066 if (member == null || !(member is FieldExpr)) {
1067 Error_InvalidNamedArgument (member_name);
1071 if (member is FieldExpr) {
1072 FieldExpr fe = (FieldExpr) member;
1073 FieldInfo fi = fe.FieldInfo;
1075 if (fi.IsInitOnly) {
1076 Error_InvalidNamedArgument (member_name);
1080 if (a.Expr is Constant) {
1081 Constant c = (Constant) a.Expr;
1084 if (member_name == "CallingConvention"){
1085 object val = GetValue (ec, c, typeof (CallingConvention));
1088 cc = (CallingConvention) val;
1089 } else if (member_name == "CharSet"){
1090 charset = (CharSet) c.GetValue ();
1091 } else if (member_name == "EntryPoint")
1092 entry_point = (string) c.GetValue ();
1093 else if (member_name == "SetLastError")
1094 set_last_err = (bool) c.GetValue ();
1096 else if (member_name == "ExactSpelling")
1097 exact_spelling = (bool) c.GetValue ();
1099 else if (member_name == "PreserveSig")
1100 preserve_sig = (bool) c.GetValue ();
1101 } catch (InvalidCastException){
1102 Error_InvalidNamedArgument (member_name);
1103 Error_AttributeArgumentNotValid (Location);
1106 Error_AttributeArgumentNotValid (Location);
1113 if (entry_point == null)
1116 charset = (CharSet)((int)charset | 0x40);
1118 MethodBuilder mb = builder.DefinePInvokeMethod (
1119 name, dll_name, entry_point, flags | MethodAttributes.HideBySig,
1120 CallingConventions.Standard,
1127 mb.SetImplementationFlags (MethodImplAttributes.PreserveSig);
1132 private Expression GetValue ()
1134 if ((Arguments == null) || (Arguments.Count < 1))
1136 ArrayList al = (ArrayList) Arguments [0];
1137 if ((al == null) || (al.Count < 1))
1139 Argument arg = (Argument) al [0];
1140 if ((arg == null) || (arg.Expr == null))
1145 public string GetString ()
1147 Expression e = GetValue ();
1148 if (e is StringLiteral)
1149 return (e as StringLiteral).Value;
1153 public bool GetBoolean ()
1155 Expression e = GetValue ();
1156 if (e is BoolLiteral)
1157 return (e as BoolLiteral).Value;
1164 /// For global attributes (assembly, module) we need special handling.
1165 /// Attributes can be located in the several files
1167 public class GlobalAttribute: Attribute
1169 public readonly NamespaceEntry ns;
1171 public GlobalAttribute (TypeContainer container, string target, string name, ArrayList args, Location loc):
1172 base (target, name, args, loc)
1174 ns = container.NamespaceEntry;
1177 protected override Type CheckAttributeType (EmitContext ec)
1179 // RootContext.Tree.Types has a single NamespaceEntry which gets overwritten
1180 // each time a new file is parsed. However, we need to use the NamespaceEntry
1181 // in effect where the attribute was used. Since code elsewhere cannot assume
1182 // that the NamespaceEntry is right, just overwrite it.
1184 // Precondition: RootContext.Tree.Types == null || RootContext.Tree.Types == ns.
1185 // The second case happens when we are recursively invoked from inside Emit.
1187 NamespaceEntry old = null;
1188 if (ec.DeclSpace == RootContext.Tree.Types) {
1189 old = ec.DeclSpace.NamespaceEntry;
1190 ec.DeclSpace.NamespaceEntry = ns;
1191 if (old != null && old != ns)
1192 throw new InternalErrorException (Location + " non-null NamespaceEntry " + old);
1195 Type retval = base.CheckAttributeType (ec);
1197 if (ec.DeclSpace == RootContext.Tree.Types)
1198 ec.DeclSpace.NamespaceEntry = old;
1203 public override CustomAttributeBuilder Resolve (EmitContext ec)
1205 if (ec.DeclSpace == RootContext.Tree.Types) {
1206 NamespaceEntry old = ec.DeclSpace.NamespaceEntry;
1207 ec.DeclSpace.NamespaceEntry = ns;
1209 throw new InternalErrorException (Location + " non-null NamespaceEntry " + old);
1212 CustomAttributeBuilder retval = base.Resolve (ec);
1214 if (ec.DeclSpace == RootContext.Tree.Types)
1215 ec.DeclSpace.NamespaceEntry = null;
1221 public class Attributes {
1222 public ArrayList Attrs;
1224 public Attributes (Attribute a)
1226 Attrs = new ArrayList ();
1230 public Attributes (ArrayList attrs)
1235 public void AddAttributes (ArrayList attrs)
1237 Attrs.AddRange (attrs);
1241 /// Checks whether attribute target is valid for the current element
1243 public bool CheckTargets (Attributable member)
1245 string[] valid_targets = member.ValidAttributeTargets;
1246 foreach (Attribute a in Attrs) {
1247 if (a.ExplicitTarget == null || a.ExplicitTarget == valid_targets [0]) {
1248 a.Target = member.AttributeTargets;
1252 // TODO: we can skip the first item
1253 if (((IList) valid_targets).Contains (a.ExplicitTarget)) {
1254 switch (a.ExplicitTarget) {
1255 case "return": a.Target = AttributeTargets.ReturnValue; continue;
1256 case "param": a.Target = AttributeTargets.Parameter; continue;
1257 case "field": a.Target = AttributeTargets.Field; continue;
1258 case "method": a.Target = AttributeTargets.Method; continue;
1259 case "property": a.Target = AttributeTargets.Property; continue;
1261 throw new InternalErrorException ("Unknown explicit target: " + a.ExplicitTarget);
1264 StringBuilder sb = new StringBuilder ();
1265 foreach (string s in valid_targets) {
1269 sb.Remove (sb.Length - 2, 2);
1270 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 ());
1276 public Attribute Search (Type t, EmitContext ec)
1278 foreach (Attribute a in Attrs) {
1279 if (a.ResolveType (ec) == t)
1286 /// Returns all attributes of type 't'. Use it when attribute is AllowMultiple = true
1288 public Attribute[] SearchMulti (Type t, EmitContext ec)
1290 ArrayList ar = null;
1292 foreach (Attribute a in Attrs) {
1293 if (a.ResolveType (ec) == t) {
1295 ar = new ArrayList ();
1300 return ar == null ? null : ar.ToArray (typeof (Attribute)) as Attribute[];
1303 public void Emit (EmitContext ec, Attributable ias)
1305 if (!CheckTargets (ias))
1308 ListDictionary ld = new ListDictionary ();
1310 foreach (Attribute a in Attrs)
1311 a.Emit (ec, ias, ld);
1314 public bool Contains (Type t, EmitContext ec)
1316 return Search (t, ec) != null;
1321 /// Helper class for attribute verification routine.
1323 sealed class AttributeTester
1325 static PtrHashtable analyzed_types = new PtrHashtable ();
1326 static PtrHashtable analyzed_types_obsolete = new PtrHashtable ();
1327 static PtrHashtable analyzed_member_obsolete = new PtrHashtable ();
1328 static PtrHashtable analyzed_method_excluded = new PtrHashtable ();
1330 private AttributeTester ()
1335 /// Returns true if parameters of two compared methods are CLS-Compliant.
1336 /// It tests differing only in ref or out, or in array rank.
1338 public static bool AreOverloadedMethodParamsClsCompliant (Type[] types_a, Type[] types_b)
1340 if (types_a == null || types_b == null)
1343 if (types_a.Length != types_b.Length)
1346 for (int i = 0; i < types_b.Length; ++i) {
1347 Type aType = types_a [i];
1348 Type bType = types_b [i];
1350 if (aType.IsArray && bType.IsArray && aType.GetArrayRank () != bType.GetArrayRank () && aType.GetElementType () == bType.GetElementType ()) {
1354 Type aBaseType = aType;
1355 bool is_either_ref_or_out = false;
1357 if (aType.IsByRef || aType.IsPointer) {
1358 aBaseType = aType.GetElementType ();
1359 is_either_ref_or_out = true;
1362 Type bBaseType = bType;
1363 if (bType.IsByRef || bType.IsPointer)
1365 bBaseType = bType.GetElementType ();
1366 is_either_ref_or_out = !is_either_ref_or_out;
1369 if (aBaseType != bBaseType)
1372 if (is_either_ref_or_out)
1379 /// Goes through all parameters and test if they are CLS-Compliant.
1381 public static bool AreParametersCompliant (Parameter[] fixedParameters, Location loc)
1383 if (fixedParameters == null)
1386 foreach (Parameter arg in fixedParameters) {
1387 if (!AttributeTester.IsClsCompliant (arg.ParameterType)) {
1388 Report.Error (3001, loc, "Argument type '{0}' is not CLS-compliant", arg.GetSignatureForError ());
1397 /// This method tests the CLS compliance of external types. It doesn't test type visibility.
1399 public static bool IsClsCompliant (Type type)
1404 object type_compliance = analyzed_types[type];
1405 if (type_compliance != null)
1406 return type_compliance == TRUE;
1408 if (type.IsPointer) {
1409 analyzed_types.Add (type, null);
1414 if (type.IsArray || type.IsByRef) {
1415 result = IsClsCompliant (TypeManager.GetElementType (type));
1417 result = AnalyzeTypeCompliance (type);
1419 analyzed_types.Add (type, result ? TRUE : FALSE);
1423 static object TRUE = new object ();
1424 static object FALSE = new object ();
1426 public static void VerifyModulesClsCompliance ()
1428 Module[] modules = TypeManager.Modules;
1429 if (modules == null)
1432 // The first module is generated assembly
1433 for (int i = 1; i < modules.Length; ++i) {
1434 Module module = modules [i];
1435 if (!IsClsCompliant (module)) {
1436 Report.Error (3013, "Added modules must be marked with the CLSCompliant attribute to match the assembly", module.Name);
1443 /// Tests container name for CLS-Compliant name (differing only in case)
1445 public static void VerifyTopLevelNameClsCompliance ()
1447 Hashtable locase_table = new Hashtable ();
1449 // Convert imported type names to lower case and ignore not cls compliant
1450 foreach (DictionaryEntry de in TypeManager.all_imported_types) {
1451 Type t = (Type)de.Value;
1452 if (!AttributeTester.IsClsCompliant (t))
1455 locase_table.Add (((string)de.Key).ToLower (System.Globalization.CultureInfo.InvariantCulture), t);
1458 foreach (DictionaryEntry de in RootContext.Tree.Decls) {
1459 DeclSpace decl = (DeclSpace)de.Value;
1460 if (!decl.IsClsCompliaceRequired (decl))
1463 string lcase = decl.Name.ToLower (System.Globalization.CultureInfo.InvariantCulture);
1464 if (!locase_table.Contains (lcase)) {
1465 locase_table.Add (lcase, decl);
1469 object conflict = locase_table [lcase];
1470 if (conflict is Type)
1471 Report.SymbolRelatedToPreviousError ((Type)conflict);
1473 Report.SymbolRelatedToPreviousError ((MemberCore)conflict);
1475 Report.Error (3005, decl.Location, "Identifier '{0}' differing only in case is not CLS-compliant", decl.GetSignatureForError ());
1479 static bool IsClsCompliant (ICustomAttributeProvider attribute_provider)
1481 object[] CompliantAttribute = attribute_provider.GetCustomAttributes (TypeManager.cls_compliant_attribute_type, false);
1482 if (CompliantAttribute.Length == 0)
1485 return ((CLSCompliantAttribute)CompliantAttribute[0]).IsCompliant;
1488 static bool AnalyzeTypeCompliance (Type type)
1490 DeclSpace ds = TypeManager.LookupDeclSpace (type);
1492 return ds.IsClsCompliaceRequired (ds.Parent);
1495 object[] CompliantAttribute = type.GetCustomAttributes (TypeManager.cls_compliant_attribute_type, false);
1496 if (CompliantAttribute.Length == 0)
1497 return IsClsCompliant (type.Assembly);
1499 return ((CLSCompliantAttribute)CompliantAttribute[0]).IsCompliant;
1503 /// Returns instance of ObsoleteAttribute when type is obsolete
1505 public static ObsoleteAttribute GetObsoleteAttribute (Type type)
1507 object type_obsolete = analyzed_types_obsolete [type];
1508 if (type_obsolete == FALSE)
1511 if (type_obsolete != null)
1512 return (ObsoleteAttribute)type_obsolete;
1514 ObsoleteAttribute result = null;
1515 if (type.IsByRef || type.IsArray || type.IsPointer) {
1516 result = GetObsoleteAttribute (TypeManager.GetElementType (type));
1518 DeclSpace type_ds = TypeManager.LookupDeclSpace (type);
1520 // Type is external, we can get attribute directly
1521 if (type_ds == null) {
1522 object[] attribute = type.GetCustomAttributes (TypeManager.obsolete_attribute_type, false);
1523 if (attribute.Length == 1)
1524 result = (ObsoleteAttribute)attribute [0];
1526 result = type_ds.GetObsoleteAttribute (type_ds);
1530 analyzed_types_obsolete.Add (type, result == null ? FALSE : result);
1535 /// Returns instance of ObsoleteAttribute when method is obsolete
1537 public static ObsoleteAttribute GetMethodObsoleteAttribute (MethodBase mb)
1539 IMethodData mc = TypeManager.GetMethod (mb);
1541 return mc.GetObsoleteAttribute ();
1543 // compiler generated methods are not registered by AddMethod
1544 if (mb.DeclaringType is TypeBuilder)
1547 return GetMemberObsoleteAttribute (mb);
1551 /// Returns instance of ObsoleteAttribute when member is obsolete
1553 public static ObsoleteAttribute GetMemberObsoleteAttribute (MemberInfo mi)
1555 object type_obsolete = analyzed_member_obsolete [mi];
1556 if (type_obsolete == FALSE)
1559 if (type_obsolete != null)
1560 return (ObsoleteAttribute)type_obsolete;
1562 ObsoleteAttribute oa = System.Attribute.GetCustomAttribute (mi, TypeManager.obsolete_attribute_type, false) as ObsoleteAttribute;
1563 analyzed_member_obsolete.Add (mi, oa == null ? FALSE : oa);
1568 /// Common method for Obsolete error/warning reporting.
1570 public static void Report_ObsoleteMessage (ObsoleteAttribute oa, string member, Location loc)
1573 Report.Error (619, loc, "'{0}' is obsolete: '{1}'", member, oa.Message);
1577 if (oa.Message == null) {
1578 Report.Warning (612, loc, "'{0}' is obsolete", member);
1581 if (RootContext.WarningLevel >= 2)
1582 Report.Warning (618, loc, "'{0}' is obsolete: '{1}'", member, oa.Message);
1585 public static bool IsConditionalMethodExcluded (MethodBase mb)
1587 object excluded = analyzed_method_excluded [mb];
1588 if (excluded != null)
1589 return excluded == TRUE ? true : false;
1591 ConditionalAttribute[] attrs = mb.GetCustomAttributes (TypeManager.conditional_attribute_type, true) as ConditionalAttribute[];
1592 if (attrs.Length == 0) {
1593 analyzed_method_excluded.Add (mb, FALSE);
1597 foreach (ConditionalAttribute a in attrs) {
1598 if (RootContext.AllDefines.Contains (a.ConditionString)) {
1599 analyzed_method_excluded.Add (mb, FALSE);
1603 analyzed_method_excluded.Add (mb, TRUE);