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;
23 namespace Mono.CSharp {
26 /// Base class for objects that can have Attributes applied to them.
28 public abstract class Attributable {
30 /// Attributes for this type
32 Attributes attributes;
34 public Attributable(Attributes attrs)
37 if (attributes != null)
38 attributes.CheckTargets (this);
41 public Attributes OptAttributes
48 if (attributes != null)
49 attributes.CheckTargets (this);
54 /// Use member-specific procedure to apply attribute @a in @cb to the entity being built in @builder
56 public abstract void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb);
59 /// Returns one AttributeTarget for this element.
61 public abstract AttributeTargets AttributeTargets { get; }
63 public abstract bool IsClsCompliaceRequired (DeclSpace ds);
66 /// Gets list of valid attribute targets for explicit target declaration.
67 /// The first array item is default target. Don't break this rule.
69 public abstract string[] ValidAttributeTargets { get; }
72 public class Attribute {
73 public readonly string ExplicitTarget;
74 public AttributeTargets Target;
76 public readonly string Name;
77 public readonly ArrayList Arguments;
79 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, "'" + name + "' is not a valid named attribute " +
116 "argument. Named attribute arguments must be fields which are not " +
117 "readonly, static or const, or read-write properties which are not static.");
120 static void Error_AttributeArgumentNotValid (Location loc)
122 Report.Error (182, loc,
123 "An attribute argument must be a constant expression, typeof " +
124 "expression or array creation expression");
127 static void Error_TypeParameterInAttribute (Location loc)
130 -202, loc, "Can not use a type parameter in an attribute");
133 void Error_AttributeConstructorMismatch ()
135 Report.Error (-6, Location,
136 "Could not find a constructor for this argument list.");
140 /// Tries to resolve the type of the attribute. Flags an error if it can't, and complain is true.
142 protected virtual Type CheckAttributeType (EmitContext ec, bool complain)
144 TypeExpr t1 = RootContext.LookupType (ec.DeclSpace, Name, true, Location);
145 // FIXME: Shouldn't do this for quoted attributes: [@A]
146 TypeExpr t2 = RootContext.LookupType (ec.DeclSpace, Name + "Attribute", true, Location);
148 String err0616 = null;
149 if (t1 != null && ! t1.IsAttribute) {
151 err0616 = "'" + Name + "': is not an attribute class";
153 if (t2 != null && ! t2.IsAttribute) {
155 err0616 = (err0616 != null)
156 ? "Neither '" + Name + "' nor '" + Name + "Attribute' is an attribute class"
157 : "'" + Name + "Attribute': is not an attribute class";
160 if (t1 != null && t2 != null) {
161 Report.Error(1614, Location, "'" + Name + "': is ambiguous; "
162 + " use either '@" + Name + "' or '" + Name + "Attribute'");
166 return t1.ResolveType (ec);
168 return t2.ResolveType (ec);
169 if (err0616 != null) {
170 Report.Error (616, Location, err0616);
175 Report.Error (246, Location,
176 "Could not find attribute '" + Name
177 + "' (are you missing a using directive or an assembly reference ?)");
181 public Type ResolveType (EmitContext ec, bool complain)
184 Type = CheckAttributeType (ec, complain);
189 /// Validates the guid string
191 bool ValidateGuid (string guid)
197 Report.Error (647, Location, "Format of GUID is invalid: " + guid);
202 string GetFullMemberName (string member)
204 return Type.FullName + '.' + member;
208 // Given an expression, if the expression is a valid attribute-argument-expression
209 // returns an object that can be used to encode it, or null on failure.
211 public static bool GetAttributeArgumentExpression (Expression e, Location loc, Type arg_type, out object result)
213 if (e is EnumConstant) {
218 Constant constant = e as Constant;
219 if (constant != null) {
220 if (e.Type != arg_type) {
221 constant = Const.ChangeType (loc, constant, arg_type);
222 if (constant == null) {
224 Error_AttributeArgumentNotValid (loc);
228 result = constant.GetValue ();
230 } else if (e is TypeOf) {
231 result = ((TypeOf) e).TypeArg;
233 } else if (e is ArrayCreation){
234 result = ((ArrayCreation) e).EncodeAsAttribute ();
237 } else if (e is EmptyCast) {
238 Expression child = ((EmptyCast)e).Child;
239 return GetAttributeArgumentExpression (child, loc, child.Type, out result);
243 Error_AttributeArgumentNotValid (loc);
247 public CustomAttributeBuilder Resolve (EmitContext ec)
252 Type = CheckAttributeType (ec, true);
254 if (oldType == null && Type == null)
256 if (oldType != null && oldType != Type){
257 Report.Error (-27, Location,
258 "Attribute {0} resolved to different types at different times: {1} vs. {2}",
259 Name, oldType, Type);
263 if (Type.IsAbstract) {
264 Report.Error (653, Location, "Cannot apply attribute class '{0}' because it is abstract", Name);
268 bool MethodImplAttr = false;
269 bool MarshalAsAttr = false;
270 bool GuidAttr = false;
271 bool usage_attr = false;
273 bool DoCompares = true;
276 // If we are a certain special attribute, we
277 // set the information accordingly
280 if (Type == TypeManager.attribute_usage_type)
282 else if (Type == TypeManager.methodimpl_attr_type)
283 MethodImplAttr = true;
284 else if (Type == TypeManager.marshal_as_attr_type)
285 MarshalAsAttr = true;
286 else if (Type == TypeManager.guid_attr_type)
291 // Now we extract the positional and named arguments
293 ArrayList pos_args = new ArrayList ();
294 ArrayList named_args = new ArrayList ();
295 int pos_arg_count = 0;
297 if (Arguments != null) {
298 pos_args = (ArrayList) Arguments [0];
299 if (pos_args != null)
300 pos_arg_count = pos_args.Count;
301 if (Arguments.Count > 1)
302 named_args = (ArrayList) Arguments [1];
305 pos_values = new object [pos_arg_count];
306 object[] real_pos_values = new object [pos_arg_count];
309 // First process positional arguments
313 for (i = 0; i < pos_arg_count; i++) {
314 Argument a = (Argument) pos_args [i];
317 if (!a.Resolve (ec, Location))
323 if (!GetAttributeArgumentExpression (e, Location, a.Type, out val))
326 if (val is EnumConstant) {
327 EnumConstant econst = (EnumConstant) e;
329 pos_values [i] = val = econst.GetValue ();
330 real_pos_values [i] = econst.GetValueAsEnumType ();
332 real_pos_values [i] = pos_values [i] = val;
337 usage_attribute = new AttributeUsageAttribute ((AttributeTargets) val);
338 else if (MethodImplAttr)
339 this.ImplOptions = (MethodImplOptions) val;
342 // we will later check the validity of the type
345 if (!ValidateGuid ((string) val))
349 } else if (MarshalAsAttr)
351 (System.Runtime.InteropServices.UnmanagedType) val;
356 // Now process named arguments
359 ArrayList field_infos = null;
360 ArrayList prop_infos = null;
361 ArrayList field_values = null;
362 ArrayList prop_values = null;
364 if (named_args.Count > 0) {
365 field_infos = new ArrayList ();
366 prop_infos = new ArrayList ();
367 field_values = new ArrayList ();
368 prop_values = new ArrayList ();
371 Hashtable seen_names = new Hashtable();
373 for (i = 0; i < named_args.Count; i++) {
374 DictionaryEntry de = (DictionaryEntry) named_args [i];
375 string member_name = (string) de.Key;
376 Argument a = (Argument) de.Value;
379 if (seen_names.Contains(member_name)) {
380 Report.Error(643, Location, "'" + member_name + "' duplicate named attribute argument");
383 seen_names.Add(member_name, 1);
385 if (!a.Resolve (ec, Location))
388 Expression member = Expression.MemberLookup (
389 ec, Type, member_name,
390 MemberTypes.Field | MemberTypes.Property,
391 BindingFlags.Public | BindingFlags.Instance,
394 if (member == null) {
395 member = Expression.MemberLookup (ec, Type, member_name,
396 MemberTypes.Field | MemberTypes.Property, BindingFlags.NonPublic | BindingFlags.Instance,
399 if (member != null) {
400 Report.Error (122, Location, "'{0}' is inaccessible due to its protection level", GetFullMemberName (member_name));
405 if (member == null || !(member is PropertyExpr || member is FieldExpr)) {
406 Error_InvalidNamedArgument (member_name);
411 if (e is TypeParameterExpr){
412 Error_TypeParameterInAttribute (Location);
416 if (member is PropertyExpr) {
417 PropertyExpr pe = (PropertyExpr) member;
418 PropertyInfo pi = pe.PropertyInfo;
420 if (!pi.CanWrite || !pi.CanRead) {
421 Report.SymbolRelatedToPreviousError (pi);
422 Error_InvalidNamedArgument (member_name);
427 if (!GetAttributeArgumentExpression (e, Location, pi.PropertyType, out value))
430 if (usage_attribute != null) {
431 if (member_name == "AllowMultiple")
432 usage_attribute.AllowMultiple = (bool) value;
433 if (member_name == "Inherited")
434 usage_attribute.Inherited = (bool) value;
437 prop_values.Add (value);
440 } else if (member is FieldExpr) {
441 FieldExpr fe = (FieldExpr) member;
442 FieldInfo fi = fe.FieldInfo;
445 Error_InvalidNamedArgument (member_name);
450 if (!GetAttributeArgumentExpression (e, Location, fi.FieldType, out value))
453 field_values.Add (value);
455 field_infos.Add (fi);
459 Expression mg = Expression.MemberLookup (
460 ec, Type, ".ctor", MemberTypes.Constructor,
461 BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly,
465 Error_AttributeConstructorMismatch ();
469 MethodBase constructor = Invocation.OverloadResolve (
470 ec, (MethodGroupExpr) mg, pos_args, false, Location);
472 if (constructor == null) {
477 // Now we perform some checks on the positional args as they
478 // cannot be null for a constructor which expects a parameter
482 ParameterData pd = Invocation.GetParameterData (constructor);
484 int group_in_params_array = Int32.MaxValue;
486 if (pc > 0 && pd.ParameterModifier (pc-1) == Parameter.Modifier.PARAMS)
487 group_in_params_array = pc-1;
489 for (int j = 0; j < pos_arg_count; ++j) {
490 Argument a = (Argument) pos_args [j];
492 if (a.Expr is NullLiteral && pd.ParameterType (j) == TypeManager.object_type) {
493 Error_AttributeArgumentNotValid (Location);
497 if (j < group_in_params_array)
500 if (j == group_in_params_array){
501 object v = real_pos_values [j];
502 int count = pos_arg_count - j;
504 object [] array = new object [count];
505 real_pos_values [j] = array;
508 object [] array = (object []) real_pos_values [group_in_params_array];
510 array [j - group_in_params_array] = real_pos_values [j];
515 // Adjust the size of the pos_values if it had params
517 if (group_in_params_array != Int32.MaxValue){
518 int argc = group_in_params_array+1;
519 object [] new_pos_values = new object [argc];
521 for (int p = 0; p < argc; p++)
522 new_pos_values [p] = real_pos_values [p];
523 real_pos_values = new_pos_values;
527 if (named_args.Count > 0) {
528 prop_info_arr = new PropertyInfo [prop_infos.Count];
529 field_info_arr = new FieldInfo [field_infos.Count];
530 field_values_arr = new object [field_values.Count];
531 prop_values_arr = new object [prop_values.Count];
533 field_infos.CopyTo (field_info_arr, 0);
534 field_values.CopyTo (field_values_arr, 0);
536 prop_values.CopyTo (prop_values_arr, 0);
537 prop_infos.CopyTo (prop_info_arr, 0);
539 cb = new CustomAttributeBuilder (
540 (ConstructorInfo) constructor, real_pos_values,
541 prop_info_arr, prop_values_arr,
542 field_info_arr, field_values_arr);
545 cb = new CustomAttributeBuilder (
546 (ConstructorInfo) constructor, real_pos_values);
547 } catch (NullReferenceException) {
549 // Don't know what to do here
552 -101, Location, "NullReferenceException while trying to create attribute." +
553 "Something's wrong!");
554 } catch (Exception e) {
557 // using System.ComponentModel;
558 // [DefaultValue (CollectionChangeAction.Add)]
559 // class X { static void Main () {} }
562 -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);
569 /// Get a string containing a list of valid targets for the attribute 'attr'
571 public string GetValidTargets ()
573 StringBuilder sb = new StringBuilder ();
574 AttributeTargets targets = GetAttributeUsage ().ValidOn;
576 if ((targets & AttributeTargets.Assembly) != 0)
577 sb.Append ("'assembly' ");
579 if ((targets & AttributeTargets.Class) != 0)
580 sb.Append ("'class' ");
582 if ((targets & AttributeTargets.Constructor) != 0)
583 sb.Append ("'constructor' ");
585 if ((targets & AttributeTargets.Delegate) != 0)
586 sb.Append ("'delegate' ");
588 if ((targets & AttributeTargets.Enum) != 0)
589 sb.Append ("'enum' ");
591 if ((targets & AttributeTargets.Event) != 0)
592 sb.Append ("'event' ");
594 if ((targets & AttributeTargets.Field) != 0)
595 sb.Append ("'field' ");
597 if ((targets & AttributeTargets.Interface) != 0)
598 sb.Append ("'interface' ");
600 if ((targets & AttributeTargets.Method) != 0)
601 sb.Append ("'method' ");
603 if ((targets & AttributeTargets.Module) != 0)
604 sb.Append ("'module' ");
606 if ((targets & AttributeTargets.Parameter) != 0)
607 sb.Append ("'parameter' ");
609 if ((targets & AttributeTargets.Property) != 0)
610 sb.Append ("'property' ");
612 if ((targets & AttributeTargets.ReturnValue) != 0)
613 sb.Append ("'return' ");
615 if ((targets & AttributeTargets.Struct) != 0)
616 sb.Append ("'struct' ");
618 return sb.ToString ();
623 /// Returns AttributeUsage attribute for this type
625 public AttributeUsageAttribute GetAttributeUsage ()
627 AttributeUsageAttribute ua = usage_attr_cache [Type] as AttributeUsageAttribute;
631 Class attr_class = TypeManager.LookupClass (Type);
633 if (attr_class == null) {
634 object[] usage_attr = Type.GetCustomAttributes (TypeManager.attribute_usage_type, true);
635 ua = (AttributeUsageAttribute)usage_attr [0];
636 usage_attr_cache.Add (Type, ua);
640 return attr_class.AttributeUsage;
644 /// Returns custom name of indexer
646 public string GetIndexerAttributeValue (EmitContext ec)
648 if (pos_values == null) {
649 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
650 // But because a lot of attribute class code must be rewritten will be better to wait...
654 return pos_values [0] as string;
658 /// Returns condition of ConditionalAttribute
660 public string GetConditionalAttributeValue (DeclSpace ds)
662 if (pos_values == null) {
663 EmitContext ec = new EmitContext (ds, ds, Location, null, null, 0, false);
665 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
666 // But because a lot of attribute class code must be rewritten will be better to wait...
670 // Some error occurred
671 if (pos_values [0] == null)
674 return (string)pos_values [0];
678 /// Creates the instance of ObsoleteAttribute from this attribute instance
680 public ObsoleteAttribute GetObsoleteAttribute (DeclSpace ds)
682 if (pos_values == null) {
683 EmitContext ec = new EmitContext (ds, ds, Location, null, null, 0, false);
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...
690 // Some error occurred
691 if (pos_values == null)
694 if (pos_values.Length == 0)
695 return new ObsoleteAttribute ();
697 if (pos_values.Length == 1)
698 return new ObsoleteAttribute ((string)pos_values [0]);
700 return new ObsoleteAttribute ((string)pos_values [0], (bool)pos_values [1]);
704 /// Returns value of CLSCompliantAttribute contructor parameter but because the method can be called
705 /// before ApplyAttribute. We need to resolve the arguments.
706 /// This situation occurs when class deps is differs from Emit order.
708 public bool GetClsCompliantAttributeValue (DeclSpace ds)
710 if (pos_values == null) {
711 EmitContext ec = new EmitContext (ds, ds, Location, null, null, 0, false);
713 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
714 // But because a lot of attribute class code must be rewritten will be better to wait...
718 // Some error occurred
719 if (pos_values [0] == null)
722 return (bool)pos_values [0];
725 object GetValue (object value)
727 if (value is EnumConstant)
728 return ((EnumConstant) value).GetValue ();
733 public object GetPositionalValue (int i)
735 return (pos_values == null) ? null : pos_values[i];
738 object GetFieldValue (string name)
741 if (field_info_arr == null)
744 foreach (FieldInfo fi in field_info_arr) {
746 return GetValue (field_values_arr [i]);
752 public UnmanagedMarshal GetMarshal ()
754 object o = GetFieldValue ("ArraySubType");
755 UnmanagedType array_sub_type = o == null ? UnmanagedType.I4 : (UnmanagedType) o;
757 switch (UnmanagedType) {
758 case UnmanagedType.CustomMarshaler:
759 MethodInfo define_custom = typeof (UnmanagedMarshal).GetMethod ("DefineCustom",
760 BindingFlags.Static | BindingFlags.Public);
761 if (define_custom == null)
764 object [] args = new object [4];
765 args [0] = GetFieldValue ("MarshalTypeRef");
766 args [1] = GetFieldValue ("MarshalCookie");
767 args [2] = GetFieldValue ("MarshalType");
768 args [3] = Guid.Empty;
769 return (UnmanagedMarshal) define_custom.Invoke (null, args);
771 case UnmanagedType.LPArray:
772 return UnmanagedMarshal.DefineLPArray (array_sub_type);
774 case UnmanagedType.SafeArray:
775 return UnmanagedMarshal.DefineSafeArray (array_sub_type);
777 case UnmanagedType.ByValArray:
778 return UnmanagedMarshal.DefineByValArray ((int) GetFieldValue ("SizeConst"));
780 case UnmanagedType.ByValTStr:
781 return UnmanagedMarshal.DefineByValTStr ((int) GetFieldValue ("SizeConst"));
784 return UnmanagedMarshal.DefineUnmanagedMarshal (UnmanagedType);
788 public bool IsInternalCall
790 get { return ImplOptions == MethodImplOptions.InternalCall; }
794 /// Emit attribute for Attributable symbol
796 public void Emit (EmitContext ec, Attributable ias, ListDictionary emitted_attr)
798 CustomAttributeBuilder cb = Resolve (ec);
802 AttributeUsageAttribute usage_attr = GetAttributeUsage ();
803 if ((usage_attr.ValidOn & Target) == 0) {
804 Report.Error (592, Location, "Attribute '{0}' is not valid on this declaration type. It is valid on {1} declarations only.", Name, GetValidTargets ());
808 ias.ApplyAttributeBuilder (this, cb);
810 if (!usage_attr.AllowMultiple) {
811 ArrayList emitted_targets = (ArrayList)emitted_attr [Type];
812 if (emitted_targets == null) {
813 emitted_targets = new ArrayList ();
814 emitted_attr.Add (Type, emitted_targets);
815 } else if (emitted_targets.Contains (Target)) {
816 Report.Error (579, Location, "Duplicate '" + Name + "' attribute");
819 emitted_targets.Add (Target);
822 if (!RootContext.VerifyClsCompliance)
825 // Here we are testing attribute arguments for array usage (error 3016)
826 if (ias.IsClsCompliaceRequired (ec.DeclSpace)) {
827 if (Arguments == null)
830 ArrayList pos_args = (ArrayList) Arguments [0];
831 if (pos_args != null) {
832 foreach (Argument arg in pos_args) {
833 // Type is undefined (was error 246)
834 if (arg.Type == null)
837 if (arg.Type.IsArray) {
838 Report.Error (3016, Location, "Arrays as attribute arguments are not CLS-compliant");
844 if (Arguments.Count < 2)
847 ArrayList named_args = (ArrayList) Arguments [1];
848 foreach (DictionaryEntry de in named_args) {
849 Argument arg = (Argument) de.Value;
851 // Type is undefined (was error 246)
852 if (arg.Type == null)
855 if (arg.Type.IsArray) {
856 Report.Error (3016, Location, "Arrays as attribute arguments are not CLS-compliant");
863 public object GetValue (EmitContext ec, Constant c, Type target)
865 if (Convert.ImplicitConversionExists (ec, c, target))
866 return c.GetValue ();
868 Convert.Error_CannotImplicitConversion (Location, c.Type, target);
872 public MethodBuilder DefinePInvokeMethod (EmitContext ec, TypeBuilder builder, string name,
873 MethodAttributes flags, Type ret_type, Type [] param_types)
876 // We extract from the attribute the information we need
879 if (Arguments == null) {
880 Console.WriteLine ("Internal error : this is not supposed to happen !");
884 ResolveType (ec, true);
888 ArrayList named_args = new ArrayList ();
890 ArrayList pos_args = (ArrayList) Arguments [0];
891 if (Arguments.Count > 1)
892 named_args = (ArrayList) Arguments [1];
895 string dll_name = null;
897 Argument tmp = (Argument) pos_args [0];
899 if (!tmp.Resolve (ec, Location))
902 if (tmp.Expr is Constant)
903 dll_name = (string) ((Constant) tmp.Expr).GetValue ();
905 Error_AttributeArgumentNotValid (Location);
909 // Now we process the named arguments
910 CallingConvention cc = CallingConvention.Winapi;
911 CharSet charset = CharSet.Ansi;
912 bool preserve_sig = true;
914 bool exact_spelling = false;
916 bool set_last_err = false;
917 string entry_point = null;
919 for (int i = 0; i < named_args.Count; i++) {
921 DictionaryEntry de = (DictionaryEntry) named_args [i];
923 string member_name = (string) de.Key;
924 Argument a = (Argument) de.Value;
926 if (!a.Resolve (ec, Location))
929 Expression member = Expression.MemberLookup (
930 ec, Type, member_name,
931 MemberTypes.Field | MemberTypes.Property,
932 BindingFlags.Public | BindingFlags.Instance,
935 if (member == null || !(member is FieldExpr)) {
936 Error_InvalidNamedArgument (member_name);
940 if (member is FieldExpr) {
941 FieldExpr fe = (FieldExpr) member;
942 FieldInfo fi = fe.FieldInfo;
945 Error_InvalidNamedArgument (member_name);
949 if (a.Expr is Constant) {
950 Constant c = (Constant) a.Expr;
953 if (member_name == "CallingConvention"){
954 object val = GetValue (ec, c, typeof (CallingConvention));
957 cc = (CallingConvention) val;
958 } else if (member_name == "CharSet"){
959 charset = (CharSet) c.GetValue ();
960 } else if (member_name == "EntryPoint")
961 entry_point = (string) c.GetValue ();
962 else if (member_name == "SetLastError")
963 set_last_err = (bool) c.GetValue ();
965 else if (member_name == "ExactSpelling")
966 exact_spelling = (bool) c.GetValue ();
968 else if (member_name == "PreserveSig")
969 preserve_sig = (bool) c.GetValue ();
970 } catch (InvalidCastException){
971 Error_InvalidNamedArgument (member_name);
972 Error_AttributeArgumentNotValid (Location);
975 Error_AttributeArgumentNotValid (Location);
982 if (entry_point == null)
985 charset = (CharSet)((int)charset | 0x40);
987 MethodBuilder mb = builder.DefinePInvokeMethod (
988 name, dll_name, entry_point, flags | MethodAttributes.HideBySig,
989 CallingConventions.Standard,
996 mb.SetImplementationFlags (MethodImplAttributes.PreserveSig);
1001 private Expression GetValue ()
1003 if ((Arguments == null) || (Arguments.Count < 1))
1005 ArrayList al = (ArrayList) Arguments [0];
1006 if ((al == null) || (al.Count < 1))
1008 Argument arg = (Argument) al [0];
1009 if ((arg == null) || (arg.Expr == null))
1014 public string GetString ()
1016 Expression e = GetValue ();
1017 if (e is StringLiteral)
1018 return (e as StringLiteral).Value;
1022 public bool GetBoolean ()
1024 Expression e = GetValue ();
1025 if (e is BoolLiteral)
1026 return (e as BoolLiteral).Value;
1033 /// For global attributes (assembly, module) we need special handling.
1034 /// Attributes can be located in the several files
1036 public class GlobalAttribute: Attribute
1038 public readonly NamespaceEntry ns;
1040 public GlobalAttribute (TypeContainer container, string target, string name, ArrayList args, Location loc):
1041 base (target, name, args, loc)
1043 ns = container.NamespaceEntry;
1046 protected override Type CheckAttributeType (EmitContext ec, bool complain)
1048 NamespaceEntry old = ec.DeclSpace.NamespaceEntry;
1049 if (old == null || old.NS == null || old.NS == Namespace.Root)
1050 ec.DeclSpace.NamespaceEntry = ns;
1051 return base.CheckAttributeType (ec, complain);
1055 public class Attributes {
1056 public ArrayList Attrs;
1058 public Attributes (Attribute a)
1060 Attrs = new ArrayList ();
1064 public Attributes (ArrayList attrs)
1069 public void AddAttributes (ArrayList attrs)
1071 Attrs.AddRange (attrs);
1075 /// Checks whether attribute target is valid for the current element
1077 public void CheckTargets (Attributable member)
1079 string[] valid_targets = member.ValidAttributeTargets;
1080 foreach (Attribute a in Attrs) {
1081 if (a.ExplicitTarget == null || a.ExplicitTarget == valid_targets [0]) {
1082 a.Target = member.AttributeTargets;
1086 // TODO: we can skip the first item
1087 if (((IList) valid_targets).Contains (a.ExplicitTarget)) {
1088 switch (a.ExplicitTarget) {
1089 case "return": a.Target = AttributeTargets.ReturnValue; continue;
1090 case "param": a.Target = AttributeTargets.Parameter; continue;
1091 case "field": a.Target = AttributeTargets.Field; continue;
1092 case "method": a.Target = AttributeTargets.Method; continue;
1093 case "property": a.Target = AttributeTargets.Property; continue;
1095 throw new InternalErrorException ("Unknown explicit target: " + a.ExplicitTarget);
1098 StringBuilder sb = new StringBuilder ();
1099 foreach (string s in valid_targets) {
1103 sb.Remove (sb.Length - 2, 2);
1104 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 ());
1108 private Attribute Search (Type t, EmitContext ec, bool complain)
1110 foreach (Attribute a in Attrs) {
1111 if (a.ResolveType (ec, complain) == t)
1117 public Attribute Search (Type t, EmitContext ec)
1119 return Search (t, ec, true);
1123 /// Returns all attributes of type 't'. Use it when attribute is AllowMultiple = true
1125 public Attribute[] SearchMulti (Type t, EmitContext ec)
1127 ArrayList ar = null;
1129 foreach (Attribute a in Attrs) {
1130 if (a.ResolveType (ec, false) == t) {
1132 ar = new ArrayList ();
1137 return ar == null ? null : ar.ToArray (typeof (Attribute)) as Attribute[];
1140 public void Emit (EmitContext ec, Attributable ias)
1142 ListDictionary ld = new ListDictionary ();
1144 foreach (Attribute a in Attrs)
1145 a.Emit (ec, ias, ld);
1148 public bool Contains (Type t, EmitContext ec)
1150 return Search (t, ec) != null;
1153 public Attribute GetClsCompliantAttribute (EmitContext ec)
1155 return Search (TypeManager.cls_compliant_attribute_type, ec, false);
1159 /// Pulls the IndexerName attribute from an Indexer if it exists.
1161 public Attribute GetIndexerNameAttribute (EmitContext ec)
1163 Attribute a = Search (TypeManager.indexer_name_type, ec, false);
1167 // Remove the attribute from the list because it is not emitted
1175 /// Helper class for attribute verification routine.
1177 sealed class AttributeTester
1179 static PtrHashtable analyzed_types = new PtrHashtable ();
1180 static PtrHashtable analyzed_types_obsolete = new PtrHashtable ();
1181 static PtrHashtable analyzed_member_obsolete = new PtrHashtable ();
1182 static PtrHashtable analyzed_method_excluded = new PtrHashtable ();
1184 private AttributeTester ()
1189 /// Returns true if parameters of two compared methods are CLS-Compliant.
1190 /// It tests differing only in ref or out, or in array rank.
1192 public static bool AreOverloadedMethodParamsClsCompliant (Type[] types_a, Type[] types_b)
1194 if (types_a == null || types_b == null)
1197 if (types_a.Length != types_b.Length)
1200 for (int i = 0; i < types_b.Length; ++i) {
1201 Type aType = types_a [i];
1202 Type bType = types_b [i];
1204 if (aType.IsArray && bType.IsArray && aType.GetArrayRank () != bType.GetArrayRank () && aType.GetElementType () == bType.GetElementType ()) {
1208 Type aBaseType = aType;
1209 bool is_either_ref_or_out = false;
1211 if (aType.IsByRef || aType.IsPointer) {
1212 aBaseType = aType.GetElementType ();
1213 is_either_ref_or_out = true;
1216 Type bBaseType = bType;
1217 if (bType.IsByRef || bType.IsPointer)
1219 bBaseType = bType.GetElementType ();
1220 is_either_ref_or_out = !is_either_ref_or_out;
1223 if (aBaseType != bBaseType)
1226 if (is_either_ref_or_out)
1233 /// Goes through all parameters and test if they are CLS-Compliant.
1235 public static bool AreParametersCompliant (Parameter[] fixedParameters, Location loc)
1237 if (fixedParameters == null)
1240 foreach (Parameter arg in fixedParameters) {
1241 if (!AttributeTester.IsClsCompliant (arg.ParameterType)) {
1242 Report.Error (3001, loc, "Argument type '{0}' is not CLS-compliant", arg.GetSignatureForError ());
1251 /// This method tests the CLS compliance of external types. It doesn't test type visibility.
1253 public static bool IsClsCompliant (Type type)
1258 object type_compliance = analyzed_types[type];
1259 if (type_compliance != null)
1260 return type_compliance == TRUE;
1262 if (type.IsPointer) {
1263 analyzed_types.Add (type, null);
1268 if (type.IsArray || type.IsByRef) {
1269 result = IsClsCompliant (TypeManager.GetElementType (type));
1271 result = AnalyzeTypeCompliance (type);
1273 analyzed_types.Add (type, result ? TRUE : FALSE);
1277 static object TRUE = new object ();
1278 static object FALSE = new object ();
1280 public static void VerifyModulesClsCompliance ()
1282 Module[] modules = TypeManager.Modules;
1283 if (modules == null)
1286 // The first module is generated assembly
1287 for (int i = 1; i < modules.Length; ++i) {
1288 Module module = modules [i];
1289 if (!IsClsCompliant (module)) {
1290 Report.Error (3013, "Added modules must be marked with the CLSCompliant attribute to match the assembly", module.Name);
1297 /// Tests container name for CLS-Compliant name (differing only in case)
1299 public static void VerifyTopLevelNameClsCompliance ()
1301 Hashtable locase_table = new Hashtable ();
1303 // Convert imported type names to lower case and ignore not cls compliant
1304 foreach (DictionaryEntry de in TypeManager.all_imported_types) {
1305 Type t = (Type)de.Value;
1306 if (!AttributeTester.IsClsCompliant (t))
1309 locase_table.Add (((string)de.Key).ToLower (System.Globalization.CultureInfo.InvariantCulture), t);
1312 foreach (DictionaryEntry de in RootContext.Tree.Decls) {
1313 DeclSpace decl = (DeclSpace)de.Value;
1314 if (!decl.IsClsCompliaceRequired (decl))
1317 string lcase = decl.Name.ToLower (System.Globalization.CultureInfo.InvariantCulture);
1318 if (!locase_table.Contains (lcase)) {
1319 locase_table.Add (lcase, decl);
1323 object conflict = locase_table [lcase];
1324 if (conflict is Type)
1325 Report.SymbolRelatedToPreviousError ((Type)conflict);
1327 Report.SymbolRelatedToPreviousError ((MemberCore)conflict);
1329 Report.Error (3005, decl.Location, "Identifier '{0}' differing only in case is not CLS-compliant", decl.GetSignatureForError ());
1333 static bool IsClsCompliant (ICustomAttributeProvider attribute_provider)
1335 object[] CompliantAttribute = attribute_provider.GetCustomAttributes (TypeManager.cls_compliant_attribute_type, false);
1336 if (CompliantAttribute.Length == 0)
1339 return ((CLSCompliantAttribute)CompliantAttribute[0]).IsCompliant;
1342 static bool AnalyzeTypeCompliance (Type type)
1344 DeclSpace ds = TypeManager.LookupDeclSpace (type);
1346 return ds.IsClsCompliaceRequired (ds.Parent);
1349 if (type.IsGenericParameter)
1352 object[] CompliantAttribute = type.GetCustomAttributes (TypeManager.cls_compliant_attribute_type, false);
1353 if (CompliantAttribute.Length == 0)
1354 return IsClsCompliant (type.Assembly);
1356 return ((CLSCompliantAttribute)CompliantAttribute[0]).IsCompliant;
1360 /// Returns instance of ObsoleteAttribute when type is obsolete
1362 public static ObsoleteAttribute GetObsoleteAttribute (Type type)
1364 object type_obsolete = analyzed_types_obsolete [type];
1365 if (type_obsolete == FALSE)
1368 if (type_obsolete != null)
1369 return (ObsoleteAttribute)type_obsolete;
1371 ObsoleteAttribute result = null;
1372 if (type.IsByRef || type.IsArray || type.IsPointer) {
1373 result = GetObsoleteAttribute (TypeManager.GetElementType (type));
1374 } else if (type.IsGenericParameter || type.IsGenericInstance)
1377 DeclSpace type_ds = TypeManager.LookupDeclSpace (type);
1379 // Type is external, we can get attribute directly
1380 if (type_ds == null) {
1381 object[] attribute = type.GetCustomAttributes (TypeManager.obsolete_attribute_type, false);
1382 if (attribute.Length == 1)
1383 result = (ObsoleteAttribute)attribute [0];
1385 result = type_ds.GetObsoleteAttribute (type_ds);
1389 analyzed_types_obsolete.Add (type, result == null ? FALSE : result);
1394 /// Returns instance of ObsoleteAttribute when method is obsolete
1396 public static ObsoleteAttribute GetMethodObsoleteAttribute (MethodBase mb)
1398 IMethodData mc = TypeManager.GetMethod (mb);
1400 return mc.GetObsoleteAttribute ();
1402 // compiler generated methods are not registered by AddMethod
1403 if (mb.DeclaringType is TypeBuilder)
1406 return GetMemberObsoleteAttribute (mb);
1410 /// Returns instance of ObsoleteAttribute when member is obsolete
1412 public static ObsoleteAttribute GetMemberObsoleteAttribute (MemberInfo mi)
1414 object type_obsolete = analyzed_member_obsolete [mi];
1415 if (type_obsolete == FALSE)
1418 if (type_obsolete != null)
1419 return (ObsoleteAttribute)type_obsolete;
1421 if ((mi.DeclaringType is TypeBuilder) || mi.DeclaringType.IsGenericInstance)
1424 ObsoleteAttribute oa = System.Attribute.GetCustomAttribute (mi, TypeManager.obsolete_attribute_type, false) as ObsoleteAttribute;
1425 analyzed_member_obsolete.Add (mi, oa == null ? FALSE : oa);
1430 /// Common method for Obsolete error/warning reporting.
1432 public static void Report_ObsoleteMessage (ObsoleteAttribute oa, string member, Location loc)
1435 Report.Error (619, loc, "'{0}' is obsolete: '{1}'", member, oa.Message);
1439 if (oa.Message == null) {
1440 Report.Warning (612, loc, "'{0}' is obsolete", member);
1443 if (RootContext.WarningLevel >= 2)
1444 Report.Warning (618, loc, "'{0}' is obsolete: '{1}'", member, oa.Message);
1447 public static bool IsConditionalMethodExcluded (MethodBase mb)
1449 object excluded = analyzed_method_excluded [mb];
1450 if (excluded != null)
1451 return excluded == TRUE ? true : false;
1453 if (mb.Mono_IsInflatedMethod)
1456 ConditionalAttribute[] attrs = mb.GetCustomAttributes (TypeManager.conditional_attribute_type, true) as ConditionalAttribute[];
1457 if (attrs.Length == 0) {
1458 analyzed_method_excluded.Add (mb, FALSE);
1462 foreach (ConditionalAttribute a in attrs) {
1463 if (RootContext.AllDefines.Contains (a.ConditionString)) {
1464 analyzed_method_excluded.Add (mb, FALSE);
1468 analyzed_method_excluded.Add (mb, TRUE);