2 // attribute.cs: Attribute Handler
4 // Author: Ravi Pratap (ravi@ximian.com)
5 // Marek Safar (marek.safar@seznam.cz)
7 // Licensed under the terms of the GNU GPL
9 // (C) 2001 Ximian, Inc (http://www.ximian.com)
14 using System.Diagnostics;
15 using System.Collections;
16 using System.Collections.Specialized;
17 using System.Reflection;
18 using System.Reflection.Emit;
19 using System.Runtime.InteropServices;
20 using System.Runtime.CompilerServices;
21 using System.Security;
22 using System.Security.Permissions;
25 namespace Mono.CSharp {
28 /// Base class for objects that can have Attributes applied to them.
30 public abstract class Attributable {
32 /// Attributes for this type
34 Attributes attributes;
36 public Attributable(Attributes attrs)
39 if (attributes != null)
40 attributes.CheckTargets (this);
43 public Attributes OptAttributes
50 if (attributes != null)
51 attributes.CheckTargets (this);
56 /// Use member-specific procedure to apply attribute @a in @cb to the entity being built in @builder
58 public abstract void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb);
61 /// Returns one AttributeTarget for this element.
63 public abstract AttributeTargets AttributeTargets { get; }
65 public abstract bool IsClsCompliaceRequired (DeclSpace ds);
68 /// Gets list of valid attribute targets for explicit target declaration.
69 /// The first array item is default target. Don't break this rule.
71 public abstract string[] ValidAttributeTargets { get; }
74 public class Attribute {
75 public readonly string ExplicitTarget;
76 public AttributeTargets Target;
78 public readonly string Name;
79 public readonly ArrayList Arguments;
81 public readonly Location Location;
85 // Is non-null if type is AttributeUsageAttribute
86 AttributeUsageAttribute usage_attribute;
88 public AttributeUsageAttribute UsageAttribute {
90 return usage_attribute;
94 MethodImplOptions ImplOptions;
95 UnmanagedType UnmanagedType;
96 CustomAttributeBuilder cb;
98 // non-null if named args present after Resolve () is called
99 PropertyInfo [] prop_info_arr;
100 FieldInfo [] field_info_arr;
101 object [] field_values_arr;
102 object [] prop_values_arr;
103 object [] pos_values;
105 static PtrHashtable usage_attr_cache = new PtrHashtable ();
107 public Attribute (string target, string name, ArrayList args, Location loc)
112 ExplicitTarget = target;
115 void Error_InvalidNamedArgument (string name)
117 Report.Error (617, Location, "'" + name + "' is not a valid named attribute " +
118 "argument. Named attribute arguments must be fields which are not " +
119 "readonly, static or const, or read-write properties which are not static.");
122 static void Error_AttributeArgumentNotValid (Location loc)
124 Report.Error (182, loc,
125 "An attribute argument must be a constant expression, typeof " +
126 "expression or array creation expression");
129 static void Error_TypeParameterInAttribute (Location loc)
132 -202, loc, "Can not use a type parameter in an attribute");
136 /// This is rather hack. We report many emit attribute error with same error to be compatible with
137 /// csc. But because csc has to report them this way because error came from ilasm we needn't.
139 public void Error_AttributeEmitError (string inner)
141 Report.Error (647, Location, "Error emitting '{0}' attribute because '{1}'", Name, inner);
144 public void Error_InvalidSecurityParent ()
146 Error_AttributeEmitError ("it is attached to invalid parent");
149 void Error_AttributeConstructorMismatch ()
151 Report.Error (-6, Location,
152 "Could not find a constructor for this argument list.");
156 /// Tries to resolve the type of the attribute. Flags an error if it can't, and complain is true.
158 protected virtual Type CheckAttributeType (EmitContext ec, bool complain)
160 TypeExpr t1 = RootContext.LookupType (ec.DeclSpace, Name, true, Location);
161 // FIXME: Shouldn't do this for quoted attributes: [@A]
162 TypeExpr t2 = RootContext.LookupType (ec.DeclSpace, Name + "Attribute", true, Location);
164 String err0616 = null;
165 if (t1 != null && ! t1.IsAttribute) {
167 err0616 = "'" + Name + "': is not an attribute class";
169 if (t2 != null && ! t2.IsAttribute) {
171 err0616 = (err0616 != null)
172 ? "Neither '" + Name + "' nor '" + Name + "Attribute' 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 '" + Name + "Attribute'");
182 return t1.ResolveType (ec);
184 return t2.ResolveType (ec);
185 if (err0616 != null) {
186 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 ?)");
197 public Type ResolveType (EmitContext ec, bool complain)
200 Type = CheckAttributeType (ec, complain);
205 /// Validates the guid string
207 bool ValidateGuid (string guid)
213 Report.Error (647, Location, "Format of GUID is invalid: " + guid);
218 string GetFullMemberName (string member)
220 return Type.FullName + '.' + member;
224 // Given an expression, if the expression is a valid attribute-argument-expression
225 // returns an object that can be used to encode it, or null on failure.
227 public static bool GetAttributeArgumentExpression (Expression e, Location loc, Type arg_type, out object result)
229 if (e is EnumConstant) {
230 if (RootContext.StdLib)
231 result = ((EnumConstant)e).GetValueAsEnumType ();
233 result = ((EnumConstant)e).GetValue ();
238 Constant constant = e as Constant;
239 if (constant != null) {
240 if (e.Type != arg_type) {
241 constant = Const.ChangeType (loc, constant, arg_type);
242 if (constant == null) {
244 Error_AttributeArgumentNotValid (loc);
248 result = constant.GetValue ();
250 } else if (e is TypeOf) {
251 result = ((TypeOf) e).TypeArg;
253 } else if (e is ArrayCreation){
254 result = ((ArrayCreation) e).EncodeAsAttribute ();
257 } else if (e is EmptyCast) {
258 Expression child = ((EmptyCast)e).Child;
259 return GetAttributeArgumentExpression (child, loc, child.Type, out result);
263 Error_AttributeArgumentNotValid (loc);
267 public CustomAttributeBuilder Resolve (EmitContext ec)
272 Type = CheckAttributeType (ec, true);
274 if (oldType == null && Type == null)
276 if (oldType != null && oldType != Type){
277 Report.Error (-27, Location,
278 "Attribute {0} resolved to different types at different times: {1} vs. {2}",
279 Name, oldType, Type);
283 if (Type.IsAbstract) {
284 Report.Error (653, Location, "Cannot apply attribute class '{0}' because it is abstract", Name);
288 bool MethodImplAttr = false;
289 bool MarshalAsAttr = false;
290 bool GuidAttr = false;
291 bool usage_attr = false;
293 bool DoCompares = true;
296 // If we are a certain special attribute, we
297 // set the information accordingly
300 if (Type == TypeManager.attribute_usage_type)
302 else if (Type == TypeManager.methodimpl_attr_type)
303 MethodImplAttr = true;
304 else if (Type == TypeManager.marshal_as_attr_type)
305 MarshalAsAttr = true;
306 else if (Type == TypeManager.guid_attr_type)
311 // Now we extract the positional and named arguments
313 ArrayList pos_args = new ArrayList ();
314 ArrayList named_args = new ArrayList ();
315 int pos_arg_count = 0;
317 if (Arguments != null) {
318 pos_args = (ArrayList) Arguments [0];
319 if (pos_args != null)
320 pos_arg_count = pos_args.Count;
321 if (Arguments.Count > 1)
322 named_args = (ArrayList) Arguments [1];
325 pos_values = new object [pos_arg_count];
328 // First process positional arguments
332 for (i = 0; i < pos_arg_count; i++) {
333 Argument a = (Argument) pos_args [i];
336 if (!a.Resolve (ec, Location))
342 if (!GetAttributeArgumentExpression (e, Location, a.Type, out val))
345 pos_values [i] = val;
349 usage_attribute = new AttributeUsageAttribute ((AttributeTargets)val);
350 } else if (MethodImplAttr) {
351 this.ImplOptions = (MethodImplOptions) val;
352 } else if (GuidAttr){
354 // we will later check the validity of the type
357 if (!ValidateGuid ((string) val))
361 } else if (MarshalAsAttr)
363 (System.Runtime.InteropServices.UnmanagedType) val;
368 // Now process named arguments
371 ArrayList field_infos = null;
372 ArrayList prop_infos = null;
373 ArrayList field_values = null;
374 ArrayList prop_values = null;
376 if (named_args.Count > 0) {
377 field_infos = new ArrayList ();
378 prop_infos = new ArrayList ();
379 field_values = new ArrayList ();
380 prop_values = new ArrayList ();
383 Hashtable seen_names = new Hashtable();
385 for (i = 0; i < named_args.Count; i++) {
386 DictionaryEntry de = (DictionaryEntry) named_args [i];
387 string member_name = (string) de.Key;
388 Argument a = (Argument) de.Value;
391 if (seen_names.Contains(member_name)) {
392 Report.Error(643, Location, "'" + member_name + "' duplicate named attribute argument");
395 seen_names.Add(member_name, 1);
397 if (!a.Resolve (ec, Location))
400 Expression member = Expression.MemberLookup (
401 ec, Type, member_name,
402 MemberTypes.Field | MemberTypes.Property,
403 BindingFlags.Public | BindingFlags.Instance,
406 if (member == null) {
407 member = Expression.MemberLookup (ec, Type, member_name,
408 MemberTypes.Field | MemberTypes.Property, BindingFlags.NonPublic | BindingFlags.Instance,
411 if (member != null) {
412 Report.Error (122, Location, "'{0}' is inaccessible due to its protection level", GetFullMemberName (member_name));
417 if (member == null || !(member is PropertyExpr || member is FieldExpr)) {
418 Error_InvalidNamedArgument (member_name);
423 if (e is TypeParameterExpr){
424 Error_TypeParameterInAttribute (Location);
428 if (member is PropertyExpr) {
429 PropertyExpr pe = (PropertyExpr) member;
430 PropertyInfo pi = pe.PropertyInfo;
432 if (!pi.CanWrite || !pi.CanRead) {
433 Report.SymbolRelatedToPreviousError (pi);
434 Error_InvalidNamedArgument (member_name);
439 if (!GetAttributeArgumentExpression (e, Location, pi.PropertyType, out value))
442 if (usage_attribute != null) {
443 if (member_name == "AllowMultiple")
444 usage_attribute.AllowMultiple = (bool) value;
445 if (member_name == "Inherited")
446 usage_attribute.Inherited = (bool) value;
449 prop_values.Add (value);
452 } else if (member is FieldExpr) {
453 FieldExpr fe = (FieldExpr) member;
454 FieldInfo fi = fe.FieldInfo;
457 Error_InvalidNamedArgument (member_name);
462 if (!GetAttributeArgumentExpression (e, Location, fi.FieldType, out value))
465 field_values.Add (value);
467 field_infos.Add (fi);
471 Expression mg = Expression.MemberLookup (
472 ec, Type, ".ctor", MemberTypes.Constructor,
473 BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly,
477 Error_AttributeConstructorMismatch ();
481 MethodBase constructor = Invocation.OverloadResolve (
482 ec, (MethodGroupExpr) mg, pos_args, false, Location);
484 if (constructor == null) {
489 // Now we perform some checks on the positional args as they
490 // cannot be null for a constructor which expects a parameter
494 ParameterData pd = Invocation.GetParameterData (constructor);
496 int group_in_params_array = Int32.MaxValue;
498 if (pc > 0 && pd.ParameterModifier (pc-1) == Parameter.Modifier.PARAMS)
499 group_in_params_array = pc-1;
501 for (int j = 0; j < pos_arg_count; ++j) {
502 Argument a = (Argument) pos_args [j];
504 if (a.Expr is NullLiteral && pd.ParameterType (j) == TypeManager.object_type) {
505 Error_AttributeArgumentNotValid (Location);
509 if (j < group_in_params_array)
512 if (j == group_in_params_array){
513 object v = pos_values [j];
514 int count = pos_arg_count - j;
516 object [] array = new object [count];
517 pos_values [j] = array;
520 object [] array = (object []) pos_values [group_in_params_array];
522 array [j - group_in_params_array] = pos_values [j];
527 // Adjust the size of the pos_values if it had params
529 if (group_in_params_array != Int32.MaxValue){
530 int argc = group_in_params_array+1;
531 object [] new_pos_values = new object [argc];
533 for (int p = 0; p < argc; p++)
534 new_pos_values [p] = pos_values [p];
535 pos_values = new_pos_values;
539 if (named_args.Count > 0) {
540 prop_info_arr = new PropertyInfo [prop_infos.Count];
541 field_info_arr = new FieldInfo [field_infos.Count];
542 field_values_arr = new object [field_values.Count];
543 prop_values_arr = new object [prop_values.Count];
545 field_infos.CopyTo (field_info_arr, 0);
546 field_values.CopyTo (field_values_arr, 0);
548 prop_values.CopyTo (prop_values_arr, 0);
549 prop_infos.CopyTo (prop_info_arr, 0);
551 cb = new CustomAttributeBuilder (
552 (ConstructorInfo) constructor, pos_values,
553 prop_info_arr, prop_values_arr,
554 field_info_arr, field_values_arr);
557 cb = new CustomAttributeBuilder (
558 (ConstructorInfo) constructor, pos_values);
559 } catch (NullReferenceException) {
561 // Don't know what to do here
564 -101, Location, "NullReferenceException while trying to create attribute." +
565 "Something's wrong!");
566 } catch (Exception e) {
569 // using System.ComponentModel;
570 // [DefaultValue (CollectionChangeAction.Add)]
571 // class X { static void Main () {} }
574 -23, Location, "The compiler can not encode this attribute in .NET due to a bug in the .NET runtime. Try the Mono runtime. The exception was: " + e.Message);
581 /// Get a string containing a list of valid targets for the attribute 'attr'
583 public string GetValidTargets ()
585 StringBuilder sb = new StringBuilder ();
586 AttributeTargets targets = GetAttributeUsage ().ValidOn;
588 if ((targets & AttributeTargets.Assembly) != 0)
589 sb.Append ("'assembly' ");
591 if ((targets & AttributeTargets.Class) != 0)
592 sb.Append ("'class' ");
594 if ((targets & AttributeTargets.Constructor) != 0)
595 sb.Append ("'constructor' ");
597 if ((targets & AttributeTargets.Delegate) != 0)
598 sb.Append ("'delegate' ");
600 if ((targets & AttributeTargets.Enum) != 0)
601 sb.Append ("'enum' ");
603 if ((targets & AttributeTargets.Event) != 0)
604 sb.Append ("'event' ");
606 if ((targets & AttributeTargets.Field) != 0)
607 sb.Append ("'field' ");
609 if ((targets & AttributeTargets.Interface) != 0)
610 sb.Append ("'interface' ");
612 if ((targets & AttributeTargets.Method) != 0)
613 sb.Append ("'method' ");
615 if ((targets & AttributeTargets.Module) != 0)
616 sb.Append ("'module' ");
618 if ((targets & AttributeTargets.Parameter) != 0)
619 sb.Append ("'parameter' ");
621 if ((targets & AttributeTargets.Property) != 0)
622 sb.Append ("'property' ");
624 if ((targets & AttributeTargets.ReturnValue) != 0)
625 sb.Append ("'return' ");
627 if ((targets & AttributeTargets.Struct) != 0)
628 sb.Append ("'struct' ");
630 return sb.ToString ();
635 /// Returns AttributeUsage attribute for this type
637 public AttributeUsageAttribute GetAttributeUsage ()
639 AttributeUsageAttribute ua = usage_attr_cache [Type] as AttributeUsageAttribute;
643 Class attr_class = TypeManager.LookupClass (Type);
645 if (attr_class == null) {
646 object[] usage_attr = Type.GetCustomAttributes (TypeManager.attribute_usage_type, true);
647 ua = (AttributeUsageAttribute)usage_attr [0];
648 usage_attr_cache.Add (Type, ua);
652 return attr_class.AttributeUsage;
656 /// Returns custom name of indexer
658 public string GetIndexerAttributeValue (EmitContext ec)
660 if (pos_values == null) {
661 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
662 // But because a lot of attribute class code must be rewritten will be better to wait...
666 return pos_values [0] as string;
670 /// Returns condition of ConditionalAttribute
672 public string GetConditionalAttributeValue (DeclSpace ds)
674 if (pos_values == null) {
675 EmitContext ec = new EmitContext (ds, ds, Location, null, null, 0, false);
677 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
678 // 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 (DeclSpace ds)
694 if (pos_values == null) {
695 EmitContext ec = new EmitContext (ds, ds, Location, null, null, 0, false);
697 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
698 // But because a lot of attribute class code must be rewritten will be better to wait...
702 // Some error occurred
703 if (pos_values == null)
706 if (pos_values.Length == 0)
707 return new ObsoleteAttribute ();
709 if (pos_values.Length == 1)
710 return new ObsoleteAttribute ((string)pos_values [0]);
712 return new ObsoleteAttribute ((string)pos_values [0], (bool)pos_values [1]);
716 /// Returns value of CLSCompliantAttribute contructor parameter but because the method can be called
717 /// before ApplyAttribute. We need to resolve the arguments.
718 /// This situation occurs when class deps is differs from Emit order.
720 public bool GetClsCompliantAttributeValue (DeclSpace ds)
722 if (pos_values == null) {
723 EmitContext ec = new EmitContext (ds, ds, Location, null, null, 0, false);
725 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
726 // 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 !");
1011 ResolveType (ec, true);
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);
1036 // Now we process the named arguments
1037 CallingConvention cc = CallingConvention.Winapi;
1038 CharSet charset = CharSet.Ansi;
1039 bool preserve_sig = true;
1041 bool exact_spelling = false;
1043 bool set_last_err = false;
1044 string entry_point = null;
1046 for (int i = 0; i < named_args.Count; i++) {
1048 DictionaryEntry de = (DictionaryEntry) named_args [i];
1050 string member_name = (string) de.Key;
1051 Argument a = (Argument) de.Value;
1053 if (!a.Resolve (ec, Location))
1056 Expression member = Expression.MemberLookup (
1057 ec, Type, member_name,
1058 MemberTypes.Field | MemberTypes.Property,
1059 BindingFlags.Public | BindingFlags.Instance,
1062 if (member == null || !(member is FieldExpr)) {
1063 Error_InvalidNamedArgument (member_name);
1067 if (member is FieldExpr) {
1068 FieldExpr fe = (FieldExpr) member;
1069 FieldInfo fi = fe.FieldInfo;
1071 if (fi.IsInitOnly) {
1072 Error_InvalidNamedArgument (member_name);
1076 if (a.Expr is Constant) {
1077 Constant c = (Constant) a.Expr;
1080 if (member_name == "CallingConvention"){
1081 object val = GetValue (ec, c, typeof (CallingConvention));
1084 cc = (CallingConvention) val;
1085 } else if (member_name == "CharSet"){
1086 charset = (CharSet) c.GetValue ();
1087 } else if (member_name == "EntryPoint")
1088 entry_point = (string) c.GetValue ();
1089 else if (member_name == "SetLastError")
1090 set_last_err = (bool) c.GetValue ();
1092 else if (member_name == "ExactSpelling")
1093 exact_spelling = (bool) c.GetValue ();
1095 else if (member_name == "PreserveSig")
1096 preserve_sig = (bool) c.GetValue ();
1097 } catch (InvalidCastException){
1098 Error_InvalidNamedArgument (member_name);
1099 Error_AttributeArgumentNotValid (Location);
1102 Error_AttributeArgumentNotValid (Location);
1109 if (entry_point == null)
1112 charset = (CharSet)((int)charset | 0x40);
1114 MethodBuilder mb = builder.DefinePInvokeMethod (
1115 name, dll_name, entry_point, flags | MethodAttributes.HideBySig,
1116 CallingConventions.Standard,
1123 mb.SetImplementationFlags (MethodImplAttributes.PreserveSig);
1128 private Expression GetValue ()
1130 if ((Arguments == null) || (Arguments.Count < 1))
1132 ArrayList al = (ArrayList) Arguments [0];
1133 if ((al == null) || (al.Count < 1))
1135 Argument arg = (Argument) al [0];
1136 if ((arg == null) || (arg.Expr == null))
1141 public string GetString ()
1143 Expression e = GetValue ();
1144 if (e is StringLiteral)
1145 return (e as StringLiteral).Value;
1149 public bool GetBoolean ()
1151 Expression e = GetValue ();
1152 if (e is BoolLiteral)
1153 return (e as BoolLiteral).Value;
1160 /// For global attributes (assembly, module) we need special handling.
1161 /// Attributes can be located in the several files
1163 public class GlobalAttribute: Attribute
1165 public readonly NamespaceEntry ns;
1167 public GlobalAttribute (TypeContainer container, string target, string name, ArrayList args, Location loc):
1168 base (target, name, args, loc)
1170 ns = container.NamespaceEntry;
1173 protected override Type CheckAttributeType (EmitContext ec, bool complain)
1175 NamespaceEntry old = ec.DeclSpace.NamespaceEntry;
1176 if (old == null || old.NS == null || old.NS == Namespace.Root)
1177 ec.DeclSpace.NamespaceEntry = ns;
1178 return base.CheckAttributeType (ec, complain);
1182 public class Attributes {
1183 public ArrayList Attrs;
1185 public Attributes (Attribute a)
1187 Attrs = new ArrayList ();
1191 public Attributes (ArrayList attrs)
1196 public void AddAttributes (ArrayList attrs)
1198 Attrs.AddRange (attrs);
1202 /// Checks whether attribute target is valid for the current element
1204 public void CheckTargets (Attributable member)
1206 string[] valid_targets = member.ValidAttributeTargets;
1207 foreach (Attribute a in Attrs) {
1208 if (a.ExplicitTarget == null || a.ExplicitTarget == valid_targets [0]) {
1209 a.Target = member.AttributeTargets;
1213 // TODO: we can skip the first item
1214 if (((IList) valid_targets).Contains (a.ExplicitTarget)) {
1215 switch (a.ExplicitTarget) {
1216 case "return": a.Target = AttributeTargets.ReturnValue; continue;
1217 case "param": a.Target = AttributeTargets.Parameter; continue;
1218 case "field": a.Target = AttributeTargets.Field; continue;
1219 case "method": a.Target = AttributeTargets.Method; continue;
1220 case "property": a.Target = AttributeTargets.Property; continue;
1222 throw new InternalErrorException ("Unknown explicit target: " + a.ExplicitTarget);
1225 StringBuilder sb = new StringBuilder ();
1226 foreach (string s in valid_targets) {
1230 sb.Remove (sb.Length - 2, 2);
1231 Report.Error (657, a.Location, "'{0}' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are '{1}'", a.Target, sb.ToString ());
1235 private Attribute Search (Type t, EmitContext ec, bool complain)
1237 foreach (Attribute a in Attrs) {
1238 if (a.ResolveType (ec, complain) == t)
1244 public Attribute Search (Type t, EmitContext ec)
1246 return Search (t, ec, true);
1250 /// Returns all attributes of type 't'. Use it when attribute is AllowMultiple = true
1252 public Attribute[] SearchMulti (Type t, EmitContext ec)
1254 ArrayList ar = null;
1256 foreach (Attribute a in Attrs) {
1257 if (a.ResolveType (ec, false) == t) {
1259 ar = new ArrayList ();
1264 return ar == null ? null : ar.ToArray (typeof (Attribute)) as Attribute[];
1267 public void Emit (EmitContext ec, Attributable ias)
1269 ListDictionary ld = new ListDictionary ();
1271 foreach (Attribute a in Attrs)
1272 a.Emit (ec, ias, ld);
1275 public bool Contains (Type t, EmitContext ec)
1277 return Search (t, ec) != null;
1280 public Attribute GetClsCompliantAttribute (EmitContext ec)
1282 return Search (TypeManager.cls_compliant_attribute_type, ec, false);
1286 /// Pulls the IndexerName attribute from an Indexer if it exists.
1288 public Attribute GetIndexerNameAttribute (EmitContext ec)
1290 Attribute a = Search (TypeManager.indexer_name_type, ec, false);
1294 // Remove the attribute from the list because it is not emitted
1302 /// Helper class for attribute verification routine.
1304 sealed class AttributeTester
1306 static PtrHashtable analyzed_types = new PtrHashtable ();
1307 static PtrHashtable analyzed_types_obsolete = new PtrHashtable ();
1308 static PtrHashtable analyzed_member_obsolete = new PtrHashtable ();
1309 static PtrHashtable analyzed_method_excluded = new PtrHashtable ();
1311 private AttributeTester ()
1316 /// Returns true if parameters of two compared methods are CLS-Compliant.
1317 /// It tests differing only in ref or out, or in array rank.
1319 public static bool AreOverloadedMethodParamsClsCompliant (Type[] types_a, Type[] types_b)
1321 if (types_a == null || types_b == null)
1324 if (types_a.Length != types_b.Length)
1327 for (int i = 0; i < types_b.Length; ++i) {
1328 Type aType = types_a [i];
1329 Type bType = types_b [i];
1331 if (aType.IsArray && bType.IsArray && aType.GetArrayRank () != bType.GetArrayRank () && aType.GetElementType () == bType.GetElementType ()) {
1335 Type aBaseType = aType;
1336 bool is_either_ref_or_out = false;
1338 if (aType.IsByRef || aType.IsPointer) {
1339 aBaseType = aType.GetElementType ();
1340 is_either_ref_or_out = true;
1343 Type bBaseType = bType;
1344 if (bType.IsByRef || bType.IsPointer)
1346 bBaseType = bType.GetElementType ();
1347 is_either_ref_or_out = !is_either_ref_or_out;
1350 if (aBaseType != bBaseType)
1353 if (is_either_ref_or_out)
1360 /// Goes through all parameters and test if they are CLS-Compliant.
1362 public static bool AreParametersCompliant (Parameter[] fixedParameters, Location loc)
1364 if (fixedParameters == null)
1367 foreach (Parameter arg in fixedParameters) {
1368 if (!AttributeTester.IsClsCompliant (arg.ParameterType)) {
1369 Report.Error (3001, loc, "Argument type '{0}' is not CLS-compliant", arg.GetSignatureForError ());
1378 /// This method tests the CLS compliance of external types. It doesn't test type visibility.
1380 public static bool IsClsCompliant (Type type)
1385 object type_compliance = analyzed_types[type];
1386 if (type_compliance != null)
1387 return type_compliance == TRUE;
1389 if (type.IsPointer) {
1390 analyzed_types.Add (type, null);
1395 if (type.IsArray || type.IsByRef) {
1396 result = IsClsCompliant (TypeManager.GetElementType (type));
1398 result = AnalyzeTypeCompliance (type);
1400 analyzed_types.Add (type, result ? TRUE : FALSE);
1404 static object TRUE = new object ();
1405 static object FALSE = new object ();
1407 public static void VerifyModulesClsCompliance ()
1409 Module[] modules = TypeManager.Modules;
1410 if (modules == null)
1413 // The first module is generated assembly
1414 for (int i = 1; i < modules.Length; ++i) {
1415 Module module = modules [i];
1416 if (!IsClsCompliant (module)) {
1417 Report.Error (3013, "Added modules must be marked with the CLSCompliant attribute to match the assembly", module.Name);
1424 /// Tests container name for CLS-Compliant name (differing only in case)
1426 public static void VerifyTopLevelNameClsCompliance ()
1428 Hashtable locase_table = new Hashtable ();
1430 // Convert imported type names to lower case and ignore not cls compliant
1431 foreach (DictionaryEntry de in TypeManager.all_imported_types) {
1432 Type t = (Type)de.Value;
1433 if (!AttributeTester.IsClsCompliant (t))
1436 locase_table.Add (((string)de.Key).ToLower (System.Globalization.CultureInfo.InvariantCulture), t);
1439 foreach (DictionaryEntry de in RootContext.Tree.Decls) {
1440 DeclSpace decl = (DeclSpace)de.Value;
1441 if (!decl.IsClsCompliaceRequired (decl))
1444 string lcase = decl.Name.ToLower (System.Globalization.CultureInfo.InvariantCulture);
1445 if (!locase_table.Contains (lcase)) {
1446 locase_table.Add (lcase, decl);
1450 object conflict = locase_table [lcase];
1451 if (conflict is Type)
1452 Report.SymbolRelatedToPreviousError ((Type)conflict);
1454 Report.SymbolRelatedToPreviousError ((MemberCore)conflict);
1456 Report.Error (3005, decl.Location, "Identifier '{0}' differing only in case is not CLS-compliant", decl.GetSignatureForError ());
1460 static bool IsClsCompliant (ICustomAttributeProvider attribute_provider)
1462 object[] CompliantAttribute = attribute_provider.GetCustomAttributes (TypeManager.cls_compliant_attribute_type, false);
1463 if (CompliantAttribute.Length == 0)
1466 return ((CLSCompliantAttribute)CompliantAttribute[0]).IsCompliant;
1469 static bool AnalyzeTypeCompliance (Type type)
1471 DeclSpace ds = TypeManager.LookupDeclSpace (type);
1473 return ds.IsClsCompliaceRequired (ds.Parent);
1476 if (type.IsGenericParameter)
1479 object[] CompliantAttribute = type.GetCustomAttributes (TypeManager.cls_compliant_attribute_type, false);
1480 if (CompliantAttribute.Length == 0)
1481 return IsClsCompliant (type.Assembly);
1483 return ((CLSCompliantAttribute)CompliantAttribute[0]).IsCompliant;
1487 /// Returns instance of ObsoleteAttribute when type is obsolete
1489 public static ObsoleteAttribute GetObsoleteAttribute (Type type)
1491 object type_obsolete = analyzed_types_obsolete [type];
1492 if (type_obsolete == FALSE)
1495 if (type_obsolete != null)
1496 return (ObsoleteAttribute)type_obsolete;
1498 ObsoleteAttribute result = null;
1499 if (type.IsByRef || type.IsArray || type.IsPointer) {
1500 result = GetObsoleteAttribute (TypeManager.GetElementType (type));
1501 } else if (type.IsGenericParameter || type.IsGenericInstance)
1504 DeclSpace type_ds = TypeManager.LookupDeclSpace (type);
1506 // Type is external, we can get attribute directly
1507 if (type_ds == null) {
1508 object[] attribute = type.GetCustomAttributes (TypeManager.obsolete_attribute_type, false);
1509 if (attribute.Length == 1)
1510 result = (ObsoleteAttribute)attribute [0];
1512 result = type_ds.GetObsoleteAttribute (type_ds);
1516 analyzed_types_obsolete.Add (type, result == null ? FALSE : result);
1521 /// Returns instance of ObsoleteAttribute when method is obsolete
1523 public static ObsoleteAttribute GetMethodObsoleteAttribute (MethodBase mb)
1525 IMethodData mc = TypeManager.GetMethod (mb);
1527 return mc.GetObsoleteAttribute ();
1529 // compiler generated methods are not registered by AddMethod
1530 if (mb.DeclaringType is TypeBuilder)
1533 return GetMemberObsoleteAttribute (mb);
1537 /// Returns instance of ObsoleteAttribute when member is obsolete
1539 public static ObsoleteAttribute GetMemberObsoleteAttribute (MemberInfo mi)
1541 object type_obsolete = analyzed_member_obsolete [mi];
1542 if (type_obsolete == FALSE)
1545 if (type_obsolete != null)
1546 return (ObsoleteAttribute)type_obsolete;
1548 if ((mi.DeclaringType is TypeBuilder) || mi.DeclaringType.IsGenericInstance)
1551 ObsoleteAttribute oa = System.Attribute.GetCustomAttribute (mi, TypeManager.obsolete_attribute_type, false) as ObsoleteAttribute;
1552 analyzed_member_obsolete.Add (mi, oa == null ? FALSE : oa);
1557 /// Common method for Obsolete error/warning reporting.
1559 public static void Report_ObsoleteMessage (ObsoleteAttribute oa, string member, Location loc)
1562 Report.Error (619, loc, "'{0}' is obsolete: '{1}'", member, oa.Message);
1566 if (oa.Message == null) {
1567 Report.Warning (612, loc, "'{0}' is obsolete", member);
1570 if (RootContext.WarningLevel >= 2)
1571 Report.Warning (618, loc, "'{0}' is obsolete: '{1}'", member, oa.Message);
1574 public static bool IsConditionalMethodExcluded (MethodBase mb)
1576 object excluded = analyzed_method_excluded [mb];
1577 if (excluded != null)
1578 return excluded == TRUE ? true : false;
1580 if (mb.Mono_IsInflatedMethod)
1583 ConditionalAttribute[] attrs = mb.GetCustomAttributes (TypeManager.conditional_attribute_type, true) as ConditionalAttribute[];
1584 if (attrs.Length == 0) {
1585 analyzed_method_excluded.Add (mb, FALSE);
1589 foreach (ConditionalAttribute a in attrs) {
1590 if (RootContext.AllDefines.Contains (a.ConditionString)) {
1591 analyzed_method_excluded.Add (mb, FALSE);
1595 analyzed_method_excluded.Add (mb, TRUE);