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 protected 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);
132 static void Error_TypeParameterInAttribute (Location loc)
135 -202, loc, "Can not use a type parameter in an attribute");
139 /// This is rather hack. We report many emit attribute error with same error to be compatible with
140 /// csc. But because csc has to report them this way because error came from ilasm we needn't.
142 public void Error_AttributeEmitError (string inner)
144 Report.Error (647, Location, "Error emitting '{0}' attribute because '{1}'", Name, inner);
147 public void Error_InvalidSecurityParent ()
149 Error_AttributeEmitError ("it is attached to invalid parent");
152 void Error_AttributeConstructorMismatch ()
154 Report.Error (-6, Location,
155 "Could not find a constructor for this argument list.");
159 /// Tries to resolve the type of the attribute. Flags an error if it can't, and complain is true.
161 protected virtual Type CheckAttributeType (EmitContext ec)
163 string NameAttribute = Name + "Attribute";
164 FullNamedExpression n1 = ec.ResolvingTypeTree
165 ? ec.DeclSpace.FindType (Location, Name)
166 : ec.DeclSpace.LookupType (Name, true, Location);
168 // FIXME: Shouldn't do this for quoted attributes: [@A]
169 FullNamedExpression n2 = ec.ResolvingTypeTree
170 ? ec.DeclSpace.FindType (Location, NameAttribute)
171 : ec.DeclSpace.LookupType (NameAttribute, true, Location);
173 TypeExpr e1 = n1 == null ? null : n1 as TypeExpr;
174 TypeExpr e2 = n2 == null ? null : n2 as TypeExpr;
176 Type t1 = e1 == null ? null : e1.ResolveType (ec);
177 Type t2 = e2 == null ? null : e2.ResolveType (ec);
179 String err0616 = null;
180 if (t1 != null && ! t1.IsSubclassOf (TypeManager.attribute_type)) {
182 err0616 = "'" + Name + "': is not an attribute class";
184 if (t2 != null && ! t2.IsSubclassOf (TypeManager.attribute_type)) {
186 err0616 = (err0616 != null)
187 ? "Neither '" + Name + "' nor '" + NameAttribute +"' is an attribute class"
188 : "'" + Name + "Attribute': is not an attribute class";
191 if (t1 != null && t2 != null) {
192 Report.Error(1614, Location, "'" + Name + "': is ambiguous; "
193 + " use either '@" + Name + "' or '" + NameAttribute + "'");
200 if (err0616 != null) {
201 Report.Error (616, Location, err0616);
205 Report.Error (246, Location,
206 "Could not find attribute '" + Name
207 + "' (are you missing a using directive or an assembly reference ?)");
209 resolve_error = true;
213 public Type ResolveType (EmitContext ec)
216 Type = CheckAttributeType (ec);
221 /// Validates the guid string
223 bool ValidateGuid (string guid)
229 Report.Error (647, Location, "Format of GUID is invalid: " + guid);
234 string GetFullMemberName (string member)
236 return Type.FullName + '.' + member;
240 // Given an expression, if the expression is a valid attribute-argument-expression
241 // returns an object that can be used to encode it, or null on failure.
243 public static bool GetAttributeArgumentExpression (Expression e, Location loc, Type arg_type, out object result)
245 if (e is EnumConstant) {
246 if (RootContext.StdLib)
247 result = ((EnumConstant)e).GetValueAsEnumType ();
249 result = ((EnumConstant)e).GetValue ();
254 Constant constant = e as Constant;
255 if (constant != null) {
256 if (e.Type != arg_type) {
257 constant = Const.ChangeType (loc, constant, arg_type);
258 if (constant == null) {
260 Error_AttributeArgumentNotValid (loc);
264 result = constant.GetValue ();
266 } else if (e is TypeOf) {
267 result = ((TypeOf) e).TypeArg;
269 } else if (e is ArrayCreation){
270 result = ((ArrayCreation) e).EncodeAsAttribute ();
273 } else if (e is EmptyCast) {
274 Expression child = ((EmptyCast)e).Child;
275 return GetAttributeArgumentExpression (child, loc, child.Type, out result);
279 Error_AttributeArgumentNotValid (loc);
283 public virtual CustomAttributeBuilder Resolve (EmitContext ec)
288 resolve_error = true;
293 Type = CheckAttributeType (ec);
295 if (oldType == null && Type == null)
297 if (oldType != null && oldType != Type){
298 Report.Error (-27, Location,
299 "Attribute {0} resolved to different types at different times: {1} vs. {2}",
300 Name, oldType, Type);
304 if (Type.IsAbstract) {
305 Report.Error (653, Location, "Cannot apply attribute class '{0}' because it is abstract", Name);
309 bool MethodImplAttr = false;
310 bool MarshalAsAttr = false;
311 bool GuidAttr = false;
312 bool usage_attr = false;
314 bool DoCompares = true;
317 // If we are a certain special attribute, we
318 // set the information accordingly
321 if (Type == TypeManager.attribute_usage_type)
323 else if (Type == TypeManager.methodimpl_attr_type)
324 MethodImplAttr = true;
325 else if (Type == TypeManager.marshal_as_attr_type)
326 MarshalAsAttr = true;
327 else if (Type == TypeManager.guid_attr_type)
332 // Now we extract the positional and named arguments
334 ArrayList pos_args = new ArrayList ();
335 ArrayList named_args = new ArrayList ();
336 int pos_arg_count = 0;
338 if (Arguments != null) {
339 pos_args = (ArrayList) Arguments [0];
340 if (pos_args != null)
341 pos_arg_count = pos_args.Count;
342 if (Arguments.Count > 1)
343 named_args = (ArrayList) Arguments [1];
346 pos_values = new object [pos_arg_count];
349 // First process positional arguments
353 for (i = 0; i < pos_arg_count; i++) {
354 Argument a = (Argument) pos_args [i];
357 if (!a.Resolve (ec, Location))
363 if (!GetAttributeArgumentExpression (e, Location, a.Type, out val))
366 pos_values [i] = val;
371 Report.Error (591, Location, "Invalid value for argument to 'System.AttributeUsage' attribute");
374 usage_attribute = new AttributeUsageAttribute ((AttributeTargets)val);
375 } else if (MethodImplAttr) {
376 this.ImplOptions = (MethodImplOptions) val;
377 } else if (GuidAttr){
379 // we will later check the validity of the type
382 if (!ValidateGuid ((string) val))
386 } else if (MarshalAsAttr)
388 (System.Runtime.InteropServices.UnmanagedType) val;
393 // Now process named arguments
396 ArrayList field_infos = null;
397 ArrayList prop_infos = null;
398 ArrayList field_values = null;
399 ArrayList prop_values = null;
401 if (named_args.Count > 0) {
402 field_infos = new ArrayList ();
403 prop_infos = new ArrayList ();
404 field_values = new ArrayList ();
405 prop_values = new ArrayList ();
408 Hashtable seen_names = new Hashtable();
410 for (i = 0; i < named_args.Count; i++) {
411 DictionaryEntry de = (DictionaryEntry) named_args [i];
412 string member_name = (string) de.Key;
413 Argument a = (Argument) de.Value;
416 if (seen_names.Contains(member_name)) {
417 Report.Error(643, Location, "'" + member_name + "' duplicate named attribute argument");
420 seen_names.Add(member_name, 1);
422 if (!a.Resolve (ec, Location))
425 Expression member = Expression.MemberLookup (
426 ec, Type, member_name,
427 MemberTypes.Field | MemberTypes.Property,
428 BindingFlags.Public | BindingFlags.Instance,
431 if (member == null) {
432 member = Expression.MemberLookup (ec, Type, member_name,
433 MemberTypes.Field | MemberTypes.Property, BindingFlags.NonPublic | BindingFlags.Instance,
436 if (member != null) {
437 Report.Error (122, Location, "'{0}' is inaccessible due to its protection level", GetFullMemberName (member_name));
443 Report.Error (117, Location, "Attribute `{0}' does not contain a definition for `{1}'",
448 if (!(member is PropertyExpr || member is FieldExpr)) {
449 Error_InvalidNamedArgument (member_name);
454 if (e is TypeParameterExpr){
455 Error_TypeParameterInAttribute (Location);
459 if (member is PropertyExpr) {
460 PropertyExpr pe = (PropertyExpr) member;
461 PropertyInfo pi = pe.PropertyInfo;
463 if (!pi.CanWrite || !pi.CanRead) {
464 Report.SymbolRelatedToPreviousError (pi);
465 Error_InvalidNamedArgument (member_name);
470 if (!GetAttributeArgumentExpression (e, Location, pi.PropertyType, out value))
473 if (usage_attribute != null) {
474 if (member_name == "AllowMultiple")
475 usage_attribute.AllowMultiple = (bool) value;
476 if (member_name == "Inherited")
477 usage_attribute.Inherited = (bool) value;
480 prop_values.Add (value);
483 } else if (member is FieldExpr) {
484 FieldExpr fe = (FieldExpr) member;
485 FieldInfo fi = fe.FieldInfo;
488 Error_InvalidNamedArgument (member_name);
493 if (!GetAttributeArgumentExpression (e, Location, fi.FieldType, out value))
496 field_values.Add (value);
498 field_infos.Add (fi);
502 Expression mg = Expression.MemberLookup (
503 ec, Type, ".ctor", MemberTypes.Constructor,
504 BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly,
508 Error_AttributeConstructorMismatch ();
512 MethodBase constructor = Invocation.OverloadResolve (
513 ec, (MethodGroupExpr) mg, pos_args, false, Location);
515 if (constructor == null) {
520 // Now we perform some checks on the positional args as they
521 // cannot be null for a constructor which expects a parameter
525 ParameterData pd = Invocation.GetParameterData (constructor);
527 int last_real_param = pd.Count;
529 // When the params is not filled we need to put one
530 if (last_real_param > pos_arg_count) {
531 object [] new_pos_values = new object [pos_arg_count + 1];
532 pos_values.CopyTo (new_pos_values, 0);
533 new_pos_values [pos_arg_count] = new object [] {} ;
534 pos_values = new_pos_values;
539 for (int j = 0; j < pos_arg_count; ++j) {
540 Argument a = (Argument) pos_args [j];
542 if (a.Expr is NullLiteral && pd.ParameterType (j) == TypeManager.object_type) {
543 Error_AttributeArgumentNotValid (Location);
547 if (j < last_real_param)
550 if (j == last_real_param) {
551 object [] array = new object [pos_arg_count - last_real_param];
552 array [0] = pos_values [j];
553 pos_values [j] = array;
557 object [] params_array = (object []) pos_values [last_real_param];
558 params_array [j - last_real_param] = pos_values [j];
561 // Adjust the size of the pos_values if it had params
562 if (last_real_param != pos_arg_count) {
563 object [] new_pos_values = new object [last_real_param + 1];
564 Array.Copy (pos_values, new_pos_values, last_real_param + 1);
565 pos_values = new_pos_values;
569 if (named_args.Count > 0) {
570 prop_info_arr = new PropertyInfo [prop_infos.Count];
571 field_info_arr = new FieldInfo [field_infos.Count];
572 field_values_arr = new object [field_values.Count];
573 prop_values_arr = new object [prop_values.Count];
575 field_infos.CopyTo (field_info_arr, 0);
576 field_values.CopyTo (field_values_arr, 0);
578 prop_values.CopyTo (prop_values_arr, 0);
579 prop_infos.CopyTo (prop_info_arr, 0);
581 cb = new CustomAttributeBuilder (
582 (ConstructorInfo) constructor, pos_values,
583 prop_info_arr, prop_values_arr,
584 field_info_arr, field_values_arr);
587 cb = new CustomAttributeBuilder (
588 (ConstructorInfo) constructor, pos_values);
589 } catch (Exception e) {
592 // using System.ComponentModel;
593 // [DefaultValue (CollectionChangeAction.Add)]
594 // class X { static void Main () {} }
596 Error_AttributeArgumentNotValid (Location);
600 resolve_error = false;
605 /// Get a string containing a list of valid targets for the attribute 'attr'
607 public string GetValidTargets ()
609 StringBuilder sb = new StringBuilder ();
610 AttributeTargets targets = GetAttributeUsage ().ValidOn;
612 if ((targets & AttributeTargets.Assembly) != 0)
613 sb.Append ("'assembly' ");
615 if ((targets & AttributeTargets.Class) != 0)
616 sb.Append ("'class' ");
618 if ((targets & AttributeTargets.Constructor) != 0)
619 sb.Append ("'constructor' ");
621 if ((targets & AttributeTargets.Delegate) != 0)
622 sb.Append ("'delegate' ");
624 if ((targets & AttributeTargets.Enum) != 0)
625 sb.Append ("'enum' ");
627 if ((targets & AttributeTargets.Event) != 0)
628 sb.Append ("'event' ");
630 if ((targets & AttributeTargets.Field) != 0)
631 sb.Append ("'field' ");
633 if ((targets & AttributeTargets.Interface) != 0)
634 sb.Append ("'interface' ");
636 if ((targets & AttributeTargets.Method) != 0)
637 sb.Append ("'method' ");
639 if ((targets & AttributeTargets.Module) != 0)
640 sb.Append ("'module' ");
642 if ((targets & AttributeTargets.Parameter) != 0)
643 sb.Append ("'parameter' ");
645 if ((targets & AttributeTargets.Property) != 0)
646 sb.Append ("'property' ");
648 if ((targets & AttributeTargets.ReturnValue) != 0)
649 sb.Append ("'return' ");
651 if ((targets & AttributeTargets.Struct) != 0)
652 sb.Append ("'struct' ");
654 return sb.ToString ();
659 /// Returns AttributeUsage attribute for this type
661 public AttributeUsageAttribute GetAttributeUsage ()
663 AttributeUsageAttribute ua = usage_attr_cache [Type] as AttributeUsageAttribute;
667 Class attr_class = TypeManager.LookupClass (Type);
669 if (attr_class == null) {
670 object[] usage_attr = Type.GetCustomAttributes (TypeManager.attribute_usage_type, true);
671 ua = (AttributeUsageAttribute)usage_attr [0];
672 usage_attr_cache.Add (Type, ua);
676 return attr_class.AttributeUsage;
680 /// Returns custom name of indexer
682 public string GetIndexerAttributeValue (EmitContext ec)
684 if (pos_values == null)
685 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
686 // But because a lot of attribute class code must be rewritten will be better to wait...
689 return pos_values [0] as string;
693 /// Returns condition of ConditionalAttribute
695 public string GetConditionalAttributeValue (EmitContext ec)
697 if (pos_values == null)
698 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
699 // But because a lot of attribute class code must be rewritten will be better to wait...
702 // Some error occurred
703 if (pos_values [0] == null)
706 return (string)pos_values [0];
710 /// Creates the instance of ObsoleteAttribute from this attribute instance
712 public ObsoleteAttribute GetObsoleteAttribute (EmitContext ec)
714 if (pos_values == null)
715 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
716 // But because a lot of attribute class code must be rewritten will be better to wait...
719 // Some error occurred
720 if (pos_values == null)
723 if (pos_values.Length == 0)
724 return new ObsoleteAttribute ();
726 if (pos_values.Length == 1)
727 return new ObsoleteAttribute ((string)pos_values [0]);
729 return new ObsoleteAttribute ((string)pos_values [0], (bool)pos_values [1]);
733 /// Returns value of CLSCompliantAttribute contructor parameter but because the method can be called
734 /// before ApplyAttribute. We need to resolve the arguments.
735 /// This situation occurs when class deps is differs from Emit order.
737 public bool GetClsCompliantAttributeValue (EmitContext ec)
739 if (pos_values == null)
740 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
741 // But because a lot of attribute class code must be rewritten will be better to wait...
744 // Some error occurred
745 if (pos_values [0] == null)
748 return (bool)pos_values [0];
752 /// Tests permitted SecurityAction for assembly or other types
754 public bool CheckSecurityActionValidity (bool for_assembly)
756 SecurityAction action = GetSecurityActionValue ();
758 if ((action == SecurityAction.RequestMinimum || action == SecurityAction.RequestOptional || action == SecurityAction.RequestRefuse) && for_assembly)
762 if (action < SecurityAction.Demand || action > SecurityAction.InheritanceDemand) {
763 Error_AttributeEmitError ("SecurityAction is out of range");
767 if ((action != SecurityAction.RequestMinimum && action != SecurityAction.RequestOptional && action != SecurityAction.RequestRefuse) && !for_assembly)
771 Error_AttributeEmitError (String.Concat ("SecurityAction '", action, "' is not valid for this declaration"));
775 System.Security.Permissions.SecurityAction GetSecurityActionValue ()
777 return (SecurityAction)pos_values [0];
781 /// Creates instance of SecurityAttribute class and add result of CreatePermission method to permission table.
783 /// <returns></returns>
784 public void ExtractSecurityPermissionSet (ListDictionary permissions)
786 if (TypeManager.LookupDeclSpace (Type) != null && RootContext.StdLib) {
787 Error_AttributeEmitError ("security custom attributes can not be referenced from defining assembly");
791 SecurityAttribute sa;
792 // For all assemblies except corlib we can avoid all hacks
793 if (RootContext.StdLib) {
794 sa = (SecurityAttribute) Activator.CreateInstance (Type, pos_values);
796 if (prop_info_arr != null) {
797 for (int i = 0; i < prop_info_arr.Length; ++i) {
798 PropertyInfo pi = prop_info_arr [i];
799 pi.SetValue (sa, prop_values_arr [i], null);
803 Type temp_type = Type.GetType (Type.FullName);
804 // HACK: All mscorlib attributes have same ctor syntax
805 sa = (SecurityAttribute) Activator.CreateInstance (temp_type, new object[] { GetSecurityActionValue () } );
807 // All types are from newly created corlib but for invocation with old we need to convert them
808 if (prop_info_arr != null) {
809 for (int i = 0; i < prop_info_arr.Length; ++i) {
810 PropertyInfo emited_pi = prop_info_arr [i];
811 PropertyInfo pi = temp_type.GetProperty (emited_pi.Name, emited_pi.PropertyType);
813 object old_instance = pi.PropertyType.IsEnum ?
814 System.Enum.ToObject (pi.PropertyType, prop_values_arr [i]) :
817 pi.SetValue (sa, old_instance, null);
824 perm = sa.CreatePermission ();
826 catch (Exception e) {
827 Error_AttributeEmitError (String.Format ("{0} was thrown during attribute processing: {1}", e.GetType (), e.Message));
830 SecurityAction action = GetSecurityActionValue ();
832 // IS is correct because for corlib we are using an instance from old corlib
833 if (!(perm is System.Security.CodeAccessPermission)) {
835 case SecurityAction.Demand:
836 action = (SecurityAction)13;
838 case SecurityAction.LinkDemand:
839 action = (SecurityAction)14;
841 case SecurityAction.InheritanceDemand:
842 action = (SecurityAction)15;
847 PermissionSet ps = (PermissionSet)permissions [action];
849 if (sa is PermissionSetAttribute)
850 ps = new PermissionSet (sa.Unrestricted ? PermissionState.Unrestricted : PermissionState.None);
852 ps = new PermissionSet (PermissionState.None);
854 permissions.Add (action, ps);
855 } else if (!ps.IsUnrestricted () && sa.Unrestricted) {
856 ps = ps.Union (new PermissionSet (PermissionState.Unrestricted));
857 permissions [action] = ps;
859 ps.AddPermission (perm);
862 object GetValue (object value)
864 if (value is EnumConstant)
865 return ((EnumConstant) value).GetValue ();
870 public object GetPositionalValue (int i)
872 return (pos_values == null) ? null : pos_values[i];
875 object GetFieldValue (string name)
878 if (field_info_arr == null)
881 foreach (FieldInfo fi in field_info_arr) {
883 return GetValue (field_values_arr [i]);
889 public UnmanagedMarshal GetMarshal (Attributable attr)
891 object value = GetFieldValue ("SizeParamIndex");
892 if (value != null && UnmanagedType != UnmanagedType.LPArray) {
893 Error_AttributeEmitError ("SizeParamIndex field is not valid for the specified unmanaged type");
897 object o = GetFieldValue ("ArraySubType");
898 UnmanagedType array_sub_type = o == null ? UnmanagedType.I4 : (UnmanagedType) o;
900 switch (UnmanagedType) {
901 case UnmanagedType.CustomMarshaler:
902 MethodInfo define_custom = typeof (UnmanagedMarshal).GetMethod ("DefineCustom",
903 BindingFlags.Static | BindingFlags.Public);
904 if (define_custom == null) {
905 Report.RuntimeMissingSupport (Location, "set marshal info");
909 object [] args = new object [4];
910 args [0] = GetFieldValue ("MarshalTypeRef");
911 args [1] = GetFieldValue ("MarshalCookie");
912 args [2] = GetFieldValue ("MarshalType");
913 args [3] = Guid.Empty;
914 return (UnmanagedMarshal) define_custom.Invoke (null, args);
916 case UnmanagedType.LPArray:
917 return UnmanagedMarshal.DefineLPArray (array_sub_type);
919 case UnmanagedType.SafeArray:
920 return UnmanagedMarshal.DefineSafeArray (array_sub_type);
922 case UnmanagedType.ByValArray:
923 FieldMember fm = attr as FieldMember;
925 Error_AttributeEmitError ("Specified unmanaged type is only valid on fields");
928 return UnmanagedMarshal.DefineByValArray ((int) GetFieldValue ("SizeConst"));
930 case UnmanagedType.ByValTStr:
931 return UnmanagedMarshal.DefineByValTStr ((int) GetFieldValue ("SizeConst"));
934 return UnmanagedMarshal.DefineUnmanagedMarshal (UnmanagedType);
938 public bool IsInternalCall
940 get { return ImplOptions == MethodImplOptions.InternalCall; }
944 /// Emit attribute for Attributable symbol
946 public void Emit (EmitContext ec, Attributable ias, ListDictionary emitted_attr)
948 CustomAttributeBuilder cb = Resolve (ec);
952 AttributeUsageAttribute usage_attr = GetAttributeUsage ();
953 if ((usage_attr.ValidOn & Target) == 0) {
954 Report.Error (592, Location, "Attribute '{0}' is not valid on this declaration type. It is valid on {1} declarations only.", Name, GetValidTargets ());
958 ias.ApplyAttributeBuilder (this, cb);
960 if (!usage_attr.AllowMultiple) {
961 ArrayList emitted_targets = (ArrayList)emitted_attr [Type];
962 if (emitted_targets == null) {
963 emitted_targets = new ArrayList ();
964 emitted_attr.Add (Type, emitted_targets);
965 } else if (emitted_targets.Contains (Target)) {
966 Report.Error (579, Location, "Duplicate '" + Name + "' attribute");
969 emitted_targets.Add (Target);
972 if (!RootContext.VerifyClsCompliance)
975 // Here we are testing attribute arguments for array usage (error 3016)
976 if (ias.IsClsCompliaceRequired (ec.DeclSpace)) {
977 if (Arguments == null)
980 ArrayList pos_args = (ArrayList) Arguments [0];
981 if (pos_args != null) {
982 foreach (Argument arg in pos_args) {
983 // Type is undefined (was error 246)
984 if (arg.Type == null)
987 if (arg.Type.IsArray) {
988 Report.Error (3016, Location, "Arrays as attribute arguments are not CLS-compliant");
994 if (Arguments.Count < 2)
997 ArrayList named_args = (ArrayList) Arguments [1];
998 foreach (DictionaryEntry de in named_args) {
999 Argument arg = (Argument) de.Value;
1001 // Type is undefined (was error 246)
1002 if (arg.Type == null)
1005 if (arg.Type.IsArray) {
1006 Report.Error (3016, Location, "Arrays as attribute arguments are not CLS-compliant");
1013 public object GetValue (EmitContext ec, Constant c, Type target)
1015 if (Convert.ImplicitConversionExists (ec, c, target))
1016 return c.GetValue ();
1018 Convert.Error_CannotImplicitConversion (Location, c.Type, target);
1022 public MethodBuilder DefinePInvokeMethod (EmitContext ec, TypeBuilder builder, string name,
1023 MethodAttributes flags, Type ret_type, Type [] param_types)
1026 // We extract from the attribute the information we need
1029 if (Arguments == null) {
1030 Console.WriteLine ("Internal error : this is not supposed to happen !");
1038 ArrayList named_args = new ArrayList ();
1040 ArrayList pos_args = (ArrayList) Arguments [0];
1041 if (Arguments.Count > 1)
1042 named_args = (ArrayList) Arguments [1];
1045 string dll_name = null;
1047 Argument tmp = (Argument) pos_args [0];
1049 if (!tmp.Resolve (ec, Location))
1052 if (tmp.Expr is Constant)
1053 dll_name = (string) ((Constant) tmp.Expr).GetValue ();
1055 Error_AttributeArgumentNotValid (Location);
1058 if (dll_name == null || dll_name == ""){
1059 Error_AttributeArgumentNotValid (": DllImport requires a non-empty string", Location);
1063 // Now we process the named arguments
1064 CallingConvention cc = CallingConvention.Winapi;
1065 CharSet charset = CharSet.Ansi;
1066 bool preserve_sig = true;
1068 bool exact_spelling = false;
1070 bool set_last_err = false;
1071 string entry_point = null;
1073 for (int i = 0; i < named_args.Count; i++) {
1075 DictionaryEntry de = (DictionaryEntry) named_args [i];
1077 string member_name = (string) de.Key;
1078 Argument a = (Argument) de.Value;
1080 if (!a.Resolve (ec, Location))
1083 Expression member = Expression.MemberLookup (
1084 ec, Type, member_name,
1085 MemberTypes.Field | MemberTypes.Property,
1086 BindingFlags.Public | BindingFlags.Instance,
1089 if (member == null || !(member is FieldExpr)) {
1090 Error_InvalidNamedArgument (member_name);
1094 if (member is FieldExpr) {
1095 FieldExpr fe = (FieldExpr) member;
1096 FieldInfo fi = fe.FieldInfo;
1098 if (fi.IsInitOnly) {
1099 Error_InvalidNamedArgument (member_name);
1103 if (a.Expr is Constant) {
1104 Constant c = (Constant) a.Expr;
1107 if (member_name == "CallingConvention"){
1108 object val = GetValue (ec, c, typeof (CallingConvention));
1111 cc = (CallingConvention) val;
1112 } else if (member_name == "CharSet"){
1113 charset = (CharSet) c.GetValue ();
1114 } else if (member_name == "EntryPoint")
1115 entry_point = (string) c.GetValue ();
1116 else if (member_name == "SetLastError")
1117 set_last_err = (bool) c.GetValue ();
1119 else if (member_name == "ExactSpelling")
1120 exact_spelling = (bool) c.GetValue ();
1122 else if (member_name == "PreserveSig")
1123 preserve_sig = (bool) c.GetValue ();
1124 } catch (InvalidCastException){
1125 Error_InvalidNamedArgument (member_name);
1126 Error_AttributeArgumentNotValid (Location);
1129 Error_AttributeArgumentNotValid (Location);
1136 if (entry_point == null)
1139 charset = (CharSet)((int)charset | 0x40);
1141 MethodBuilder mb = builder.DefinePInvokeMethod (
1142 name, dll_name, entry_point, flags | MethodAttributes.HideBySig,
1143 CallingConventions.Standard,
1150 mb.SetImplementationFlags (MethodImplAttributes.PreserveSig);
1155 private Expression GetValue ()
1157 if ((Arguments == null) || (Arguments.Count < 1))
1159 ArrayList al = (ArrayList) Arguments [0];
1160 if ((al == null) || (al.Count < 1))
1162 Argument arg = (Argument) al [0];
1163 if ((arg == null) || (arg.Expr == null))
1168 public string GetString ()
1170 Expression e = GetValue ();
1171 if (e is StringLiteral)
1172 return (e as StringLiteral).Value;
1176 public bool GetBoolean ()
1178 Expression e = GetValue ();
1179 if (e is BoolLiteral)
1180 return (e as BoolLiteral).Value;
1184 public bool IsAssemblyAttribute {
1186 return ExplicitTarget == "assembly";
1190 public bool IsModuleAttribute {
1192 return ExplicitTarget == "module";
1199 /// For global attributes (assembly, module) we need special handling.
1200 /// Attributes can be located in the several files
1202 public class GlobalAttribute: Attribute
1204 public readonly NamespaceEntry ns;
1206 public GlobalAttribute (TypeContainer container, string target, string name, ArrayList args, Location loc):
1207 base (target, name, args, loc)
1209 ns = container.NamespaceEntry;
1212 protected override Type CheckAttributeType (EmitContext ec)
1214 // RootContext.Tree.Types has a single NamespaceEntry which gets overwritten
1215 // each time a new file is parsed. However, we need to use the NamespaceEntry
1216 // in effect where the attribute was used. Since code elsewhere cannot assume
1217 // that the NamespaceEntry is right, just overwrite it.
1219 // Precondition: RootContext.Tree.Types == null || RootContext.Tree.Types == ns.
1220 // The second case happens when we are recursively invoked from inside Emit.
1222 NamespaceEntry old = null;
1223 if (ec.DeclSpace == RootContext.Tree.Types) {
1224 old = ec.DeclSpace.NamespaceEntry;
1225 ec.DeclSpace.NamespaceEntry = ns;
1226 if (old != null && old != ns)
1227 throw new InternalErrorException (Location + " non-null NamespaceEntry " + old);
1230 Type retval = base.CheckAttributeType (ec);
1232 if (ec.DeclSpace == RootContext.Tree.Types)
1233 ec.DeclSpace.NamespaceEntry = old;
1238 public override CustomAttributeBuilder Resolve (EmitContext ec)
1240 if (ec.DeclSpace == RootContext.Tree.Types) {
1241 NamespaceEntry old = ec.DeclSpace.NamespaceEntry;
1242 ec.DeclSpace.NamespaceEntry = ns;
1244 throw new InternalErrorException (Location + " non-null NamespaceEntry " + old);
1247 CustomAttributeBuilder retval = base.Resolve (ec);
1249 if (ec.DeclSpace == RootContext.Tree.Types)
1250 ec.DeclSpace.NamespaceEntry = null;
1256 public class Attributes {
1257 public ArrayList Attrs;
1259 public Attributes (Attribute a)
1261 Attrs = new ArrayList ();
1265 public Attributes (ArrayList attrs)
1270 public void AddAttributes (ArrayList attrs)
1272 Attrs.AddRange (attrs);
1275 public void AddAttribute (Attribute attr)
1281 /// Checks whether attribute target is valid for the current element
1283 public bool CheckTargets (Attributable member)
1285 string[] valid_targets = member.ValidAttributeTargets;
1286 foreach (Attribute a in Attrs) {
1287 if (a.ExplicitTarget == null || a.ExplicitTarget == valid_targets [0]) {
1288 a.Target = member.AttributeTargets;
1292 // TODO: we can skip the first item
1293 if (((IList) valid_targets).Contains (a.ExplicitTarget)) {
1294 switch (a.ExplicitTarget) {
1295 case "return": a.Target = AttributeTargets.ReturnValue; continue;
1296 case "param": a.Target = AttributeTargets.Parameter; continue;
1297 case "field": a.Target = AttributeTargets.Field; continue;
1298 case "method": a.Target = AttributeTargets.Method; continue;
1299 case "property": a.Target = AttributeTargets.Property; continue;
1301 throw new InternalErrorException ("Unknown explicit target: " + a.ExplicitTarget);
1304 StringBuilder sb = new StringBuilder ();
1305 foreach (string s in valid_targets) {
1309 sb.Remove (sb.Length - 2, 2);
1310 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 ());
1316 public Attribute Search (Type t, EmitContext ec)
1318 foreach (Attribute a in Attrs) {
1319 if (a.ResolveType (ec) == t)
1326 /// Returns all attributes of type 't'. Use it when attribute is AllowMultiple = true
1328 public Attribute[] SearchMulti (Type t, EmitContext ec)
1330 ArrayList ar = null;
1332 foreach (Attribute a in Attrs) {
1333 if (a.ResolveType (ec) == t) {
1335 ar = new ArrayList ();
1340 return ar == null ? null : ar.ToArray (typeof (Attribute)) as Attribute[];
1343 public void Emit (EmitContext ec, Attributable ias)
1345 if (!CheckTargets (ias))
1348 ListDictionary ld = new ListDictionary ();
1350 foreach (Attribute a in Attrs)
1351 a.Emit (ec, ias, ld);
1354 public bool Contains (Type t, EmitContext ec)
1356 return Search (t, ec) != null;
1361 /// Helper class for attribute verification routine.
1363 sealed class AttributeTester
1365 static PtrHashtable analyzed_types = new PtrHashtable ();
1366 static PtrHashtable analyzed_types_obsolete = new PtrHashtable ();
1367 static PtrHashtable analyzed_member_obsolete = new PtrHashtable ();
1368 static PtrHashtable analyzed_method_excluded = new PtrHashtable ();
1370 private AttributeTester ()
1375 /// Returns true if parameters of two compared methods are CLS-Compliant.
1376 /// It tests differing only in ref or out, or in array rank.
1378 public static bool AreOverloadedMethodParamsClsCompliant (Type[] types_a, Type[] types_b)
1380 if (types_a == null || types_b == null)
1383 if (types_a.Length != types_b.Length)
1386 for (int i = 0; i < types_b.Length; ++i) {
1387 Type aType = types_a [i];
1388 Type bType = types_b [i];
1390 if (aType.IsArray && bType.IsArray && aType.GetArrayRank () != bType.GetArrayRank () && aType.GetElementType () == bType.GetElementType ()) {
1394 Type aBaseType = aType;
1395 bool is_either_ref_or_out = false;
1397 if (aType.IsByRef || aType.IsPointer) {
1398 aBaseType = aType.GetElementType ();
1399 is_either_ref_or_out = true;
1402 Type bBaseType = bType;
1403 if (bType.IsByRef || bType.IsPointer)
1405 bBaseType = bType.GetElementType ();
1406 is_either_ref_or_out = !is_either_ref_or_out;
1409 if (aBaseType != bBaseType)
1412 if (is_either_ref_or_out)
1419 /// Goes through all parameters and test if they are CLS-Compliant.
1421 public static bool AreParametersCompliant (Parameter[] fixedParameters, Location loc)
1423 if (fixedParameters == null)
1426 foreach (Parameter arg in fixedParameters) {
1427 if (!AttributeTester.IsClsCompliant (arg.ParameterType)) {
1428 Report.Error (3001, loc, "Argument type '{0}' is not CLS-compliant", arg.GetSignatureForError ());
1437 /// This method tests the CLS compliance of external types. It doesn't test type visibility.
1439 public static bool IsClsCompliant (Type type)
1444 object type_compliance = analyzed_types[type];
1445 if (type_compliance != null)
1446 return type_compliance == TRUE;
1448 if (type.IsPointer) {
1449 analyzed_types.Add (type, null);
1454 if (type.IsArray || type.IsByRef) {
1455 result = IsClsCompliant (TypeManager.GetElementType (type));
1457 result = AnalyzeTypeCompliance (type);
1459 analyzed_types.Add (type, result ? TRUE : FALSE);
1463 static object TRUE = new object ();
1464 static object FALSE = new object ();
1466 public static void VerifyModulesClsCompliance ()
1468 Module[] modules = TypeManager.Modules;
1469 if (modules == null)
1472 // The first module is generated assembly
1473 for (int i = 1; i < modules.Length; ++i) {
1474 Module module = modules [i];
1475 if (!IsClsCompliant (module)) {
1476 Report.Error (3013, "Added modules must be marked with the CLSCompliant attribute to match the assembly", module.Name);
1483 /// Tests container name for CLS-Compliant name (differing only in case)
1485 public static void VerifyTopLevelNameClsCompliance ()
1487 Hashtable locase_table = new Hashtable ();
1489 // Convert imported type names to lower case and ignore not cls compliant
1490 foreach (DictionaryEntry de in TypeManager.all_imported_types) {
1491 Type t = (Type)de.Value;
1492 if (!AttributeTester.IsClsCompliant (t))
1495 locase_table.Add (((string)de.Key).ToLower (System.Globalization.CultureInfo.InvariantCulture), t);
1498 foreach (DictionaryEntry de in RootContext.Tree.Decls) {
1499 DeclSpace decl = (DeclSpace)de.Value;
1500 if (!decl.IsClsCompliaceRequired (decl))
1503 string lcase = decl.Name.ToLower (System.Globalization.CultureInfo.InvariantCulture);
1504 if (!locase_table.Contains (lcase)) {
1505 locase_table.Add (lcase, decl);
1509 object conflict = locase_table [lcase];
1510 if (conflict is Type)
1511 Report.SymbolRelatedToPreviousError ((Type)conflict);
1513 Report.SymbolRelatedToPreviousError ((MemberCore)conflict);
1515 Report.Error (3005, decl.Location, "Identifier '{0}' differing only in case is not CLS-compliant", decl.GetSignatureForError ());
1519 static bool IsClsCompliant (ICustomAttributeProvider attribute_provider)
1521 object[] CompliantAttribute = attribute_provider.GetCustomAttributes (TypeManager.cls_compliant_attribute_type, false);
1522 if (CompliantAttribute.Length == 0)
1525 return ((CLSCompliantAttribute)CompliantAttribute[0]).IsCompliant;
1528 static bool AnalyzeTypeCompliance (Type type)
1530 DeclSpace ds = TypeManager.LookupDeclSpace (type);
1532 return ds.IsClsCompliaceRequired (ds.Parent);
1535 if (type.IsGenericParameter || type.IsGenericInstance)
1538 object[] CompliantAttribute = type.GetCustomAttributes (TypeManager.cls_compliant_attribute_type, false);
1539 if (CompliantAttribute.Length == 0)
1540 return IsClsCompliant (type.Assembly);
1542 return ((CLSCompliantAttribute)CompliantAttribute[0]).IsCompliant;
1546 /// Returns instance of ObsoleteAttribute when type is obsolete
1548 public static ObsoleteAttribute GetObsoleteAttribute (Type type)
1550 object type_obsolete = analyzed_types_obsolete [type];
1551 if (type_obsolete == FALSE)
1554 if (type_obsolete != null)
1555 return (ObsoleteAttribute)type_obsolete;
1557 ObsoleteAttribute result = null;
1558 if (type.IsByRef || type.IsArray || type.IsPointer) {
1559 result = GetObsoleteAttribute (TypeManager.GetElementType (type));
1560 } else if (type.IsGenericParameter || type.IsGenericInstance)
1563 DeclSpace type_ds = TypeManager.LookupDeclSpace (type);
1565 // Type is external, we can get attribute directly
1566 if (type_ds == null) {
1567 object[] attribute = type.GetCustomAttributes (TypeManager.obsolete_attribute_type, false);
1568 if (attribute.Length == 1)
1569 result = (ObsoleteAttribute)attribute [0];
1571 result = type_ds.GetObsoleteAttribute (type_ds);
1575 analyzed_types_obsolete.Add (type, result == null ? FALSE : result);
1580 /// Returns instance of ObsoleteAttribute when method is obsolete
1582 public static ObsoleteAttribute GetMethodObsoleteAttribute (MethodBase mb)
1584 IMethodData mc = TypeManager.GetMethod (mb);
1586 return mc.GetObsoleteAttribute ();
1588 // compiler generated methods are not registered by AddMethod
1589 if (mb.DeclaringType is TypeBuilder)
1592 PropertyInfo pi = PropertyExpr.AccessorTable [mb] as PropertyInfo;
1594 return GetMemberObsoleteAttribute (pi);
1596 return GetMemberObsoleteAttribute (mb);
1600 /// Returns instance of ObsoleteAttribute when member is obsolete
1602 public static ObsoleteAttribute GetMemberObsoleteAttribute (MemberInfo mi)
1604 object type_obsolete = analyzed_member_obsolete [mi];
1605 if (type_obsolete == FALSE)
1608 if (type_obsolete != null)
1609 return (ObsoleteAttribute)type_obsolete;
1611 if ((mi.DeclaringType is TypeBuilder) || mi.DeclaringType.IsGenericInstance)
1614 ObsoleteAttribute oa = System.Attribute.GetCustomAttribute (mi, TypeManager.obsolete_attribute_type, false) as ObsoleteAttribute;
1615 analyzed_member_obsolete.Add (mi, oa == null ? FALSE : oa);
1620 /// Common method for Obsolete error/warning reporting.
1622 public static void Report_ObsoleteMessage (ObsoleteAttribute oa, string member, Location loc)
1625 Report.Error (619, loc, "'{0}' is obsolete: '{1}'", member, oa.Message);
1629 if (oa.Message == null) {
1630 Report.Warning (612, loc, "'{0}' is obsolete", member);
1633 if (RootContext.WarningLevel >= 2)
1634 Report.Warning (618, loc, "'{0}' is obsolete: '{1}'", member, oa.Message);
1637 public static bool IsConditionalMethodExcluded (MethodBase mb)
1639 object excluded = analyzed_method_excluded [mb];
1640 if (excluded != null)
1641 return excluded == TRUE ? true : false;
1643 if (mb.Mono_IsInflatedMethod)
1646 ConditionalAttribute[] attrs = mb.GetCustomAttributes (TypeManager.conditional_attribute_type, true) as ConditionalAttribute[];
1647 if (attrs.Length == 0) {
1648 analyzed_method_excluded.Add (mb, FALSE);
1652 foreach (ConditionalAttribute a in attrs) {
1653 if (RootContext.AllDefines.Contains (a.ConditionString)) {
1654 analyzed_method_excluded.Add (mb, FALSE);
1658 analyzed_method_excluded.Add (mb, TRUE);