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 (ValidAttributeTargets);
41 public Attributes OptAttributes
48 if (attributes != null)
49 attributes.CheckTargets (ValidAttributeTargets);
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 combination of enabled AttributeTargets
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 protected abstract string[] ValidAttributeTargets { get; }
72 public class Attribute {
74 public readonly string Name;
75 public readonly ArrayList Arguments;
77 public readonly Location Location;
81 // Is non-null if type is AttributeUsageAttribute
82 AttributeUsageAttribute usage_attribute;
84 public AttributeUsageAttribute UsageAttribute {
86 return usage_attribute;
90 MethodImplOptions ImplOptions;
91 UnmanagedType UnmanagedType;
92 CustomAttributeBuilder cb;
94 // non-null if named args present after Resolve () is called
95 PropertyInfo [] prop_info_arr;
96 FieldInfo [] field_info_arr;
97 object [] field_values_arr;
98 object [] prop_values_arr;
101 static PtrHashtable usage_attr_cache = new PtrHashtable ();
103 public Attribute (string target, string name, ArrayList args, Location loc)
111 void Error_InvalidNamedArgument (string name)
113 Report.Error (617, Location, "'" + name + "' is not a valid named attribute " +
114 "argument. Named attribute arguments must be fields which are not " +
115 "readonly, static or const, or properties with a set accessor which "+
119 static void Error_AttributeArgumentNotValid (Location loc)
121 Report.Error (182, loc,
122 "An attribute argument must be a constant expression, typeof " +
123 "expression or array creation expression");
126 static void Error_TypeParameterInAttribute (Location loc)
129 -202, loc, "Can not use a type parameter in an attribute");
132 void Error_AttributeConstructorMismatch ()
134 Report.Error (-6, Location,
135 "Could not find a constructor for this argument list.");
139 /// Tries to resolve the type of the attribute. Flags an error if it can't, and complain is true.
141 protected virtual Type CheckAttributeType (EmitContext ec, bool complain)
143 TypeExpr t1 = RootContext.LookupType (ec.DeclSpace, Name, true, Location);
144 // FIXME: Shouldn't do this for quoted attributes: [@A]
145 TypeExpr t2 = RootContext.LookupType (ec.DeclSpace, Name + "Attribute", true, Location);
147 String err0616 = null;
148 if (t1 != null && ! t1.IsAttribute) {
150 err0616 = "'" + Name + "': is not an attribute class";
152 if (t2 != null && ! t2.IsAttribute) {
154 err0616 = (err0616 != null)
155 ? "Neither '" + Name + "' nor '" + Name + "Attribute' is an attribute class"
156 : "'" + Name + "Attribute': is not an attribute class";
159 if (t1 != null && t2 != null) {
160 Report.Error(1614, Location, "'" + Name + "': is ambiguous; "
161 + " use either '@" + Name + "' or '" + Name + "Attribute'");
165 return t1.ResolveType (ec);
167 return t2.ResolveType (ec);
168 if (err0616 != null) {
169 Report.Error (616, Location, err0616);
174 Report.Error (246, Location,
175 "Could not find attribute '" + Name
176 + "' (are you missing a using directive or an assembly reference ?)");
180 public Type ResolveType (EmitContext ec, bool complain)
183 Type = CheckAttributeType (ec, complain);
188 /// Validates the guid string
190 bool ValidateGuid (string guid)
196 Report.Error (647, Location, "Format of GUID is invalid: " + guid);
201 string GetFullMemberName (string member)
203 return Type.FullName + '.' + member;
207 // Given an expression, if the expression is a valid attribute-argument-expression
208 // returns an object that can be used to encode it, or null on failure.
210 public static bool GetAttributeArgumentExpression (Expression e, Location loc, out object result)
213 result = ((Constant) e).GetValue ();
215 } else if (e is TypeOf) {
216 result = ((TypeOf) e).TypeArg;
218 } else if (e is ArrayCreation){
219 result = ((ArrayCreation) e).EncodeAsAttribute ();
222 } else if (e is EmptyCast) {
224 if (((EmptyCast) e).Child is Constant) {
225 result = ((Constant) ((EmptyCast)e).Child).GetValue();
231 Error_AttributeArgumentNotValid (loc);
235 public CustomAttributeBuilder Resolve (EmitContext ec)
240 Type = CheckAttributeType (ec, true);
241 if (oldType == null && Type == null)
243 if (oldType != null && oldType != Type) {
244 Report.Error (-6, Location,
245 "Attribute {0} resolved to different types at different times: {1} vs. {2}",
246 Name, oldType, Type);
250 bool MethodImplAttr = false;
251 bool MarshalAsAttr = false;
252 bool GuidAttr = false;
253 bool usage_attr = false;
255 bool DoCompares = true;
258 // If we are a certain special attribute, we
259 // set the information accordingly
262 if (Type == TypeManager.attribute_usage_type)
264 else if (Type == TypeManager.methodimpl_attr_type)
265 MethodImplAttr = true;
266 else if (Type == TypeManager.marshal_as_attr_type)
267 MarshalAsAttr = true;
268 else if (Type == TypeManager.guid_attr_type)
273 // Now we extract the positional and named arguments
275 ArrayList pos_args = new ArrayList ();
276 ArrayList named_args = new ArrayList ();
277 int pos_arg_count = 0;
279 if (Arguments != null) {
280 pos_args = (ArrayList) Arguments [0];
281 if (pos_args != null)
282 pos_arg_count = pos_args.Count;
283 if (Arguments.Count > 1)
284 named_args = (ArrayList) Arguments [1];
287 pos_values = new object [pos_arg_count];
290 // First process positional arguments
294 for (i = 0; i < pos_arg_count; i++) {
295 Argument a = (Argument) pos_args [i];
298 if (!a.Resolve (ec, Location))
304 if (!GetAttributeArgumentExpression (e, Location, out val))
307 pos_values [i] = val;
310 usage_attribute = new AttributeUsageAttribute ((AttributeTargets) pos_values [0]);
311 else if (MethodImplAttr)
312 this.ImplOptions = (MethodImplOptions) pos_values [0];
315 // we will later check the validity of the type
317 if (pos_values [0] is string){
318 if (!ValidateGuid ((string) pos_values [0]))
322 } else if (MarshalAsAttr)
324 (System.Runtime.InteropServices.UnmanagedType) pos_values [0];
329 // Now process named arguments
332 ArrayList field_infos = null;
333 ArrayList prop_infos = null;
334 ArrayList field_values = null;
335 ArrayList prop_values = null;
337 if (named_args.Count > 0) {
338 field_infos = new ArrayList ();
339 prop_infos = new ArrayList ();
340 field_values = new ArrayList ();
341 prop_values = new ArrayList ();
344 Hashtable seen_names = new Hashtable();
346 for (i = 0; i < named_args.Count; i++) {
347 DictionaryEntry de = (DictionaryEntry) named_args [i];
348 string member_name = (string) de.Key;
349 Argument a = (Argument) de.Value;
352 if (seen_names.Contains(member_name)) {
353 Report.Error(643, Location, "'" + member_name + "' duplicate named attribute argument");
356 seen_names.Add(member_name, 1);
358 if (!a.Resolve (ec, Location))
361 Expression member = Expression.MemberLookup (
362 ec, Type, member_name,
363 MemberTypes.Field | MemberTypes.Property,
364 BindingFlags.Public | BindingFlags.Instance,
367 if (member == null) {
368 member = Expression.MemberLookup (ec, Type, member_name,
369 MemberTypes.Field | MemberTypes.Property, BindingFlags.NonPublic | BindingFlags.Instance,
372 if (member != null) {
373 Report.Error_T (122, Location, GetFullMemberName (member_name));
378 if (member == null || !(member is PropertyExpr || member is FieldExpr)) {
379 Error_InvalidNamedArgument (member_name);
384 if (e is TypeParameterExpr){
385 Error_TypeParameterInAttribute (Location);
389 if (member is PropertyExpr) {
390 PropertyExpr pe = (PropertyExpr) member;
391 PropertyInfo pi = pe.PropertyInfo;
394 Error_InvalidNamedArgument (member_name);
398 Constant c = e as Constant;
400 if (c.Type != pi.PropertyType) {
401 c = Const.ChangeType (Location, c, pi.PropertyType);
406 object o = c.GetValue ();
409 if (usage_attribute != null) {
410 if (member_name == "AllowMultiple")
411 usage_attribute.AllowMultiple = (bool) o;
412 if (member_name == "Inherited")
413 usage_attribute.Inherited = (bool) o;
416 } else if (e is TypeOf) {
417 prop_values.Add (((TypeOf) e).TypeArg);
418 } else if (e is ArrayCreation) {
419 prop_values.Add (((ArrayCreation) e).EncodeAsAttribute());
421 Error_AttributeArgumentNotValid (Location);
427 } else if (member is FieldExpr) {
428 FieldExpr fe = (FieldExpr) member;
429 FieldInfo fi = fe.FieldInfo;
432 Error_InvalidNamedArgument (member_name);
437 // Handle charset here, and set the TypeAttributes
439 Constant c = e as Constant;
441 if (c.Type != fi.FieldType){
442 c = Const.ChangeType (Location, c, fi.FieldType);
447 object value = c.GetValue ();
448 field_values.Add (value);
449 } else if (e is TypeOf) {
450 field_values.Add (((TypeOf) e).TypeArg);
452 Error_AttributeArgumentNotValid (Location);
456 field_infos.Add (fi);
460 Expression mg = Expression.MemberLookup (
461 ec, Type, ".ctor", MemberTypes.Constructor,
462 BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly,
466 Error_AttributeConstructorMismatch ();
470 MethodBase constructor = Invocation.OverloadResolve (
471 ec, (MethodGroupExpr) mg, pos_args, false, Location);
473 if (constructor == null) {
474 Error_AttributeConstructorMismatch ();
479 // Now we perform some checks on the positional args as they
480 // cannot be null for a constructor which expects a parameter
484 ParameterData pd = Invocation.GetParameterData (constructor);
486 int group_in_params_array = Int32.MaxValue;
488 if (pc > 0 && pd.ParameterModifier (pc-1) == Parameter.Modifier.PARAMS)
489 group_in_params_array = pc-1;
491 for (int j = 0; j < pos_arg_count; ++j) {
492 Argument a = (Argument) pos_args [j];
494 if (a.Expr is NullLiteral && pd.ParameterType (j) == TypeManager.object_type) {
495 Error_AttributeArgumentNotValid (Location);
499 if (j < group_in_params_array)
502 if (j == group_in_params_array){
503 object v = pos_values [j];
504 int count = pos_arg_count - j;
506 object [] array = new object [count];
507 pos_values [j] = array;
510 object [] array = (object []) pos_values [group_in_params_array];
512 array [j - group_in_params_array] = pos_values [j];
517 // Adjust the size of the pos_values if it had params
519 if (group_in_params_array != Int32.MaxValue){
520 int argc = group_in_params_array+1;
521 object [] new_pos_values = new object [argc];
523 for (int p = 0; p < argc; p++)
524 new_pos_values [p] = pos_values [p];
525 pos_values = new_pos_values;
529 if (named_args.Count > 0) {
530 prop_info_arr = new PropertyInfo [prop_infos.Count];
531 field_info_arr = new FieldInfo [field_infos.Count];
532 field_values_arr = new object [field_values.Count];
533 prop_values_arr = new object [prop_values.Count];
535 field_infos.CopyTo (field_info_arr, 0);
536 field_values.CopyTo (field_values_arr, 0);
538 prop_values.CopyTo (prop_values_arr, 0);
539 prop_infos.CopyTo (prop_info_arr, 0);
541 cb = new CustomAttributeBuilder (
542 (ConstructorInfo) constructor, pos_values,
543 prop_info_arr, prop_values_arr,
544 field_info_arr, field_values_arr);
547 cb = new CustomAttributeBuilder (
548 (ConstructorInfo) constructor, pos_values);
549 } catch (NullReferenceException) {
551 // Don't know what to do here
554 -101, Location, "NullReferenceException while trying to create attribute." +
555 "Something's wrong!");
556 } catch (Exception e) {
559 // using System.ComponentModel;
560 // [DefaultValue (CollectionChangeAction.Add)]
561 // class X { static void Main () {} }
564 -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);
571 /// Get a string containing a list of valid targets for the attribute 'attr'
573 static string GetValidTargets (Attribute attr)
575 StringBuilder sb = new StringBuilder ();
576 AttributeTargets targets = attr.GetAttributeUsage ().ValidOn;
578 if ((targets & AttributeTargets.Assembly) != 0)
579 sb.Append ("'assembly' ");
581 if ((targets & AttributeTargets.Class) != 0)
582 sb.Append ("'class' ");
584 if ((targets & AttributeTargets.Constructor) != 0)
585 sb.Append ("'constructor' ");
587 if ((targets & AttributeTargets.Delegate) != 0)
588 sb.Append ("'delegate' ");
590 if ((targets & AttributeTargets.Enum) != 0)
591 sb.Append ("'enum' ");
593 if ((targets & AttributeTargets.Event) != 0)
594 sb.Append ("'event' ");
596 if ((targets & AttributeTargets.Field) != 0)
597 sb.Append ("'field' ");
599 if ((targets & AttributeTargets.Interface) != 0)
600 sb.Append ("'interface' ");
602 if ((targets & AttributeTargets.Method) != 0)
603 sb.Append ("'method' ");
605 if ((targets & AttributeTargets.Module) != 0)
606 sb.Append ("'module' ");
608 if ((targets & AttributeTargets.Parameter) != 0)
609 sb.Append ("'parameter' ");
611 if ((targets & AttributeTargets.Property) != 0)
612 sb.Append ("'property' ");
614 if ((targets & AttributeTargets.ReturnValue) != 0)
615 sb.Append ("'return' ");
617 if ((targets & AttributeTargets.Struct) != 0)
618 sb.Append ("'struct' ");
620 return sb.ToString ();
624 public static void Error_AttributeNotValidForElement (Attribute a, Location loc)
627 592, loc, "Attribute '" + a.Name +
628 "' is not valid on this declaration type. " +
629 "It is valid on " + GetValidTargets (a) + "declarations only.");
634 /// Returns AttributeUsage attribute for this type
636 public AttributeUsageAttribute GetAttributeUsage ()
638 AttributeUsageAttribute ua = usage_attr_cache [Type] as AttributeUsageAttribute;
642 Class attr_class = TypeManager.LookupClass (Type);
644 if (attr_class == null) {
645 object[] usage_attr = Type.GetCustomAttributes (TypeManager.attribute_usage_type, true);
646 ua = (AttributeUsageAttribute)usage_attr [0];
647 usage_attr_cache.Add (Type, ua);
651 return attr_class.AttributeUsage;
656 // This pulls the condition name out of a Conditional attribute
658 public string Conditional_GetConditionName ()
661 // So we have a Conditional, pull the data out.
663 if (Arguments == null || Arguments [0] == null){
664 Error_AttributeConstructorMismatch ();
668 ArrayList pos_args = (ArrayList) Arguments [0];
669 if (pos_args.Count != 1){
670 Error_AttributeConstructorMismatch ();
674 Argument arg = (Argument) pos_args [0];
675 if (!(arg.Expr is StringConstant)){
676 Error_AttributeConstructorMismatch ();
680 return ((StringConstant) arg.Expr).Value;
683 public string IndexerName_GetIndexerName (EmitContext ec)
685 if (Arguments == null || Arguments [0] == null){
686 Error_AttributeConstructorMismatch ();
689 ArrayList pos_args = (ArrayList) Arguments [0];
690 if (pos_args.Count != 1) {
691 Error_AttributeConstructorMismatch ();
695 Argument arg = (Argument) pos_args [0];
696 if (!arg.Resolve (ec, Location))
699 StringConstant sc = arg.Expr as StringConstant;
701 Error_AttributeConstructorMismatch ();
709 /// Returns condition of ConditionalAttribute
711 public string GetConditionalAttributeValue (DeclSpace ds)
713 if (pos_values == null) {
714 EmitContext ec = new EmitContext (ds, ds, Location, null, null, 0, false);
716 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
717 // But because a lot of attribute class code must be rewritten will be better to wait...
721 // Some error occurred
722 if (pos_values [0] == null)
725 return (string)pos_values [0];
729 /// Creates the instance of ObsoleteAttribute from this attribute instance
731 public ObsoleteAttribute GetObsoleteAttribute (DeclSpace ds)
733 if (pos_values == null) {
734 EmitContext ec = new EmitContext (ds, ds, Location, null, null, 0, false);
736 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
737 // But because a lot of attribute class code must be rewritten will be better to wait...
741 // Some error occurred
742 if (pos_values == null)
745 if (pos_values.Length == 0)
746 return new ObsoleteAttribute ();
748 if (pos_values.Length == 1)
749 return new ObsoleteAttribute ((string)pos_values [0]);
751 return new ObsoleteAttribute ((string)pos_values [0], (bool)pos_values [1]);
755 /// Returns value of CLSCompliantAttribute contructor parameter but because the method can be called
756 /// before ApplyAttribute. We need to resolve the arguments.
757 /// This situation occurs when class deps is differs from Emit order.
759 public bool GetClsCompliantAttributeValue (DeclSpace ds)
761 if (pos_values == null) {
762 EmitContext ec = new EmitContext (ds, ds, Location, null, null, 0, false);
764 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
765 // But because a lot of attribute class code must be rewritten will be better to wait...
769 // Some error occurred
770 if (pos_values [0] == null)
773 return (bool)pos_values [0];
776 public object GetPositionalValue (int i)
778 return (pos_values == null) ? null : pos_values[i];
781 object GetFieldValue (string name)
784 if (field_info_arr == null)
787 foreach (FieldInfo fi in field_info_arr) {
789 return field_values_arr [i];
795 public UnmanagedMarshal GetMarshal ()
797 object o = GetFieldValue ("ArraySubType");
798 UnmanagedType array_sub_type = o == null ? UnmanagedType.I4 : (UnmanagedType) o;
800 switch (UnmanagedType) {
801 case UnmanagedType.CustomMarshaler:
802 MethodInfo define_custom = typeof (UnmanagedMarshal).GetMethod ("DefineCustom",
803 BindingFlags.Static | BindingFlags.Public);
804 if (define_custom == null)
807 object [] args = new object [4];
808 args [0] = GetFieldValue ("MarshalTypeRef");
809 args [1] = GetFieldValue ("MarshalCookie");
810 args [2] = GetFieldValue ("MarshalType");
811 args [3] = Guid.Empty;
812 return (UnmanagedMarshal) define_custom.Invoke (null, args);
814 case UnmanagedType.LPArray:
815 return UnmanagedMarshal.DefineLPArray (array_sub_type);
817 case UnmanagedType.SafeArray:
818 return UnmanagedMarshal.DefineSafeArray (array_sub_type);
820 case UnmanagedType.ByValArray:
821 return UnmanagedMarshal.DefineByValArray ((int) GetFieldValue ("SizeConst"));
823 case UnmanagedType.ByValTStr:
824 return UnmanagedMarshal.DefineByValTStr ((int) GetFieldValue ("SizeConst"));
827 return UnmanagedMarshal.DefineUnmanagedMarshal (UnmanagedType);
831 public bool IsInternalCall
833 get { return ImplOptions == MethodImplOptions.InternalCall; }
837 /// Emit attribute for Attributable symbol
839 public void Emit (EmitContext ec, Attributable ias, ListDictionary emitted_attr)
841 CustomAttributeBuilder cb = Resolve (ec);
845 AttributeUsageAttribute usage_attr = GetAttributeUsage ();
846 if ((usage_attr.ValidOn & ias.AttributeTargets) == 0) {
847 Error_AttributeNotValidForElement (this, Location);
851 ias.ApplyAttributeBuilder (this, cb);
853 if (!usage_attr.AllowMultiple && emitted_attr.Contains (Target)) {
854 Report.Error (579, Location, "Duplicate '" + Name + "' attribute");
857 emitted_attr [Type] = Target;
859 // Here we are testing attribute arguments for array usage (error 3016)
860 if (ias.IsClsCompliaceRequired (ec.DeclSpace)) {
861 if (Arguments == null)
864 ArrayList pos_args = (ArrayList) Arguments [0];
865 if (pos_args != null) {
866 foreach (Argument arg in pos_args) {
867 // Type is undefined (was error 246)
868 if (arg.Type == null)
871 if (arg.Type.IsArray) {
872 Report.Error_T (3016, Location);
878 if (Arguments.Count < 2)
881 ArrayList named_args = (ArrayList) Arguments [1];
882 foreach (DictionaryEntry de in named_args) {
883 Argument arg = (Argument) de.Value;
885 // Type is undefined (was error 246)
886 if (arg.Type == null)
889 if (arg.Type.IsArray) {
890 Report.Error_T (3016, Location);
897 public object GetValue (EmitContext ec, Constant c, Type target)
899 if (Convert.ImplicitConversionExists (ec, c, target))
900 return c.GetValue ();
902 Convert.Error_CannotImplicitConversion (Location, c.Type, target);
906 public MethodBuilder DefinePInvokeMethod (EmitContext ec, TypeBuilder builder, string name,
907 MethodAttributes flags, Type ret_type, Type [] param_types)
910 // We extract from the attribute the information we need
913 if (Arguments == null) {
914 Console.WriteLine ("Internal error : this is not supposed to happen !");
918 ResolveType (ec, true);
922 ArrayList named_args = new ArrayList ();
924 ArrayList pos_args = (ArrayList) Arguments [0];
925 if (Arguments.Count > 1)
926 named_args = (ArrayList) Arguments [1];
929 string dll_name = null;
931 Argument tmp = (Argument) pos_args [0];
933 if (!tmp.Resolve (ec, Location))
936 if (tmp.Expr is Constant)
937 dll_name = (string) ((Constant) tmp.Expr).GetValue ();
939 Error_AttributeArgumentNotValid (Location);
943 // Now we process the named arguments
944 CallingConvention cc = CallingConvention.Winapi;
945 CharSet charset = CharSet.Ansi;
946 bool preserve_sig = true;
948 bool exact_spelling = false;
950 bool set_last_err = false;
951 string entry_point = null;
953 for (int i = 0; i < named_args.Count; i++) {
955 DictionaryEntry de = (DictionaryEntry) named_args [i];
957 string member_name = (string) de.Key;
958 Argument a = (Argument) de.Value;
960 if (!a.Resolve (ec, Location))
963 Expression member = Expression.MemberLookup (
964 ec, Type, member_name,
965 MemberTypes.Field | MemberTypes.Property,
966 BindingFlags.Public | BindingFlags.Instance,
969 if (member == null || !(member is FieldExpr)) {
970 Error_InvalidNamedArgument (member_name);
974 if (member is FieldExpr) {
975 FieldExpr fe = (FieldExpr) member;
976 FieldInfo fi = fe.FieldInfo;
979 Error_InvalidNamedArgument (member_name);
983 if (a.Expr is Constant) {
984 Constant c = (Constant) a.Expr;
987 if (member_name == "CallingConvention"){
988 object val = GetValue (ec, c, typeof (CallingConvention));
991 cc = (CallingConvention) val;
992 } else if (member_name == "CharSet"){
993 charset = (CharSet) c.GetValue ();
994 } else if (member_name == "EntryPoint")
995 entry_point = (string) c.GetValue ();
996 else if (member_name == "SetLastError")
997 set_last_err = (bool) c.GetValue ();
999 else if (member_name == "ExactSpelling")
1000 exact_spelling = (bool) c.GetValue ();
1002 else if (member_name == "PreserveSig")
1003 preserve_sig = (bool) c.GetValue ();
1004 } catch (InvalidCastException){
1005 Error_InvalidNamedArgument (member_name);
1006 Error_AttributeArgumentNotValid (Location);
1009 Error_AttributeArgumentNotValid (Location);
1016 if (entry_point == null)
1019 charset = (CharSet)((int)charset | 0x40);
1021 MethodBuilder mb = builder.DefinePInvokeMethod (
1022 name, dll_name, entry_point, flags | MethodAttributes.HideBySig,
1023 CallingConventions.Standard,
1030 mb.SetImplementationFlags (MethodImplAttributes.PreserveSig);
1035 private Expression GetValue ()
1037 if ((Arguments == null) || (Arguments.Count < 1))
1039 ArrayList al = (ArrayList) Arguments [0];
1040 if ((al == null) || (al.Count < 1))
1042 Argument arg = (Argument) al [0];
1043 if ((arg == null) || (arg.Expr == null))
1048 public string GetString ()
1050 Expression e = GetValue ();
1051 if (e is StringLiteral)
1052 return (e as StringLiteral).Value;
1056 public bool GetBoolean ()
1058 Expression e = GetValue ();
1059 if (e is BoolLiteral)
1060 return (e as BoolLiteral).Value;
1067 /// For global attributes (assembly, module) we need special handling.
1068 /// Attributes can be located in the several files
1070 public class GlobalAttribute: Attribute
1072 public readonly NamespaceEntry ns;
1074 public GlobalAttribute (TypeContainer container, string target, string name, ArrayList args, Location loc):
1075 base (target, name, args, loc)
1077 ns = container.NamespaceEntry;
1080 protected override Type CheckAttributeType (EmitContext ec, bool complain)
1082 NamespaceEntry old = ec.DeclSpace.NamespaceEntry;
1083 if (old == null || old.NS == null || old.NS == Namespace.Root)
1084 ec.DeclSpace.NamespaceEntry = ns;
1085 return base.CheckAttributeType (ec, complain);
1089 public class Attributes {
1090 public ArrayList Attrs;
1092 public Attributes (Attribute a)
1094 Attrs = new ArrayList ();
1098 public Attributes (ArrayList attrs)
1103 public void AddAttributes (ArrayList attrs)
1105 Attrs.AddRange (attrs);
1109 /// Checks whether attribute target is valid for the current element
1111 public void CheckTargets (string[] possible_targets)
1113 foreach (Attribute a in Attrs) {
1114 if (a.Target == null) {
1115 a.Target = possible_targets [0];
1119 if (((IList) possible_targets).Contains (a.Target))
1122 StringBuilder sb = new StringBuilder ();
1123 foreach (string s in possible_targets) {
1127 sb.Remove (sb.Length - 2, 2);
1128 Report.Error_T (657, a.Location, a.Target, sb.ToString ());
1132 private Attribute Search (Type t, EmitContext ec, bool complain)
1134 foreach (Attribute a in Attrs) {
1135 if (a.ResolveType (ec, false) == t)
1141 public Attribute Search (Type t, EmitContext ec)
1143 return Search (t, ec, true);
1147 /// Returns all attributes of type 't'. Use it when attribute is AllowMultiple = true
1149 public Attribute[] SearchMulti (Type t, EmitContext ec)
1151 ArrayList ar = null;
1153 foreach (Attribute a in Attrs) {
1154 if (a.ResolveType (ec, false) == t) {
1156 ar = new ArrayList ();
1161 return ar == null ? null : ar.ToArray (typeof (Attribute)) as Attribute[];
1164 public void Emit (EmitContext ec, Attributable ias)
1166 ListDictionary ld = new ListDictionary ();
1168 foreach (Attribute a in Attrs)
1169 a.Emit (ec, ias, ld);
1172 public bool Contains (Type t, EmitContext ec)
1174 return Search (t, ec) != null;
1177 public Attribute GetClsCompliantAttribute (EmitContext ec)
1179 return Search (TypeManager.cls_compliant_attribute_type, ec, false);
1183 /// Pulls the IndexerName attribute from an Indexer if it exists.
1185 public string ScanForIndexerName (EmitContext ec)
1187 Attribute a = Search (TypeManager.indexer_name_type, ec);
1191 // Remove the attribute from the list
1192 //TODO: It is very close to hack and it can crash here
1195 return a.IndexerName_GetIndexerName (ec);
1201 /// Helper class for attribute verification routine.
1203 sealed class AttributeTester
1205 static PtrHashtable analyzed_types = new PtrHashtable ();
1206 static PtrHashtable analyzed_types_obsolete = new PtrHashtable ();
1207 static PtrHashtable analyzed_member_obsolete = new PtrHashtable ();
1208 static PtrHashtable analyzed_method_excluded = new PtrHashtable ();
1210 private AttributeTester ()
1215 /// Returns true if parameters of two compared methods are CLS-Compliant.
1216 /// It tests differing only in ref or out, or in array rank.
1218 public static bool AreOverloadedMethodParamsClsCompliant (Type[] types_a, Type[] types_b)
1220 if (types_a == null || types_b == null)
1223 if (types_a.Length != types_b.Length)
1226 for (int i = 0; i < types_b.Length; ++i) {
1227 Type aType = types_a [i];
1228 Type bType = types_b [i];
1230 if (aType.IsArray && bType.IsArray && aType.GetArrayRank () != bType.GetArrayRank () && aType.GetElementType () == bType.GetElementType ()) {
1234 Type aBaseType = aType;
1235 bool is_either_ref_or_out = false;
1237 if (aType.IsByRef || aType.IsPointer) {
1238 aBaseType = aType.GetElementType ();
1239 is_either_ref_or_out = true;
1242 Type bBaseType = bType;
1243 if (bType.IsByRef || bType.IsPointer)
1245 bBaseType = bType.GetElementType ();
1246 is_either_ref_or_out = !is_either_ref_or_out;
1249 if (aBaseType != bBaseType)
1252 if (is_either_ref_or_out)
1259 /// Goes through all parameters and test if they are CLS-Compliant.
1261 public static bool AreParametersCompliant (Parameter[] fixedParameters, Location loc)
1263 if (fixedParameters == null)
1266 foreach (Parameter arg in fixedParameters) {
1267 if (!AttributeTester.IsClsCompliant (arg.ParameterType)) {
1268 Report.Error_T (3001, loc, arg.GetSignatureForError ());
1277 /// This method tests the CLS compliance of external types. It doesn't test type visibility.
1279 public static bool IsClsCompliant (Type type)
1284 object type_compliance = analyzed_types[type];
1285 if (type_compliance != null)
1286 return type_compliance == TRUE;
1288 if (type.IsPointer) {
1289 analyzed_types.Add (type, null);
1294 if (type.IsArray || type.IsByRef) {
1295 result = IsClsCompliant (TypeManager.GetElementType (type));
1297 result = AnalyzeTypeCompliance (type);
1299 analyzed_types.Add (type, result ? TRUE : FALSE);
1303 static object TRUE = new object ();
1304 static object FALSE = new object ();
1307 /// Non-hierarchical CLS Compliance analyzer
1309 public static bool IsComplianceRequired (MemberInfo mi, DeclSpace ds)
1311 DeclSpace temp_ds = TypeManager.LookupDeclSpace (mi.DeclaringType);
1313 // Type is external, we can get attribute directly
1314 if (temp_ds == null) {
1315 object[] cls_attribute = mi.GetCustomAttributes (TypeManager.cls_compliant_attribute_type, false);
1316 return (cls_attribute.Length == 1 && ((CLSCompliantAttribute)cls_attribute[0]).IsCompliant);
1320 // Interface doesn't store full name
1321 if (temp_ds is Interface)
1324 tmp_name = String.Concat (temp_ds.Name, ".", mi.Name);
1326 MemberCore mc = temp_ds.GetDefinition (tmp_name) as MemberCore;
1327 return mc.IsClsCompliaceRequired (ds);
1330 public static void VerifyModulesClsCompliance ()
1332 Module[] modules = TypeManager.Modules;
1333 if (modules == null)
1336 // The first module is generated assembly
1337 for (int i = 1; i < modules.Length; ++i) {
1338 Module module = modules [i];
1339 if (!IsClsCompliant (module)) {
1340 Report.Error_T (3013, module.Name);
1346 static bool IsClsCompliant (ICustomAttributeProvider attribute_provider)
1348 object[] CompliantAttribute = attribute_provider.GetCustomAttributes (TypeManager.cls_compliant_attribute_type, false);
1349 if (CompliantAttribute.Length == 0)
1352 return ((CLSCompliantAttribute)CompliantAttribute[0]).IsCompliant;
1355 static bool AnalyzeTypeCompliance (Type type)
1357 DeclSpace ds = TypeManager.LookupDeclSpace (type);
1359 return ds.IsClsCompliaceRequired (ds.Parent);
1362 if (type.IsGenericParameter)
1365 object[] CompliantAttribute = type.GetCustomAttributes (TypeManager.cls_compliant_attribute_type, false);
1366 if (CompliantAttribute.Length == 0)
1367 return IsClsCompliant (type.Assembly);
1369 return ((CLSCompliantAttribute)CompliantAttribute[0]).IsCompliant;
1373 /// Returns instance of ObsoleteAttribute when type is obsolete
1375 public static ObsoleteAttribute GetObsoleteAttribute (Type type)
1377 object type_obsolete = analyzed_types_obsolete [type];
1378 if (type_obsolete == FALSE)
1381 if (type_obsolete != null)
1382 return (ObsoleteAttribute)type_obsolete;
1384 ObsoleteAttribute result = null;
1385 if (type.IsByRef || type.IsArray || type.IsPointer) {
1386 result = GetObsoleteAttribute (TypeManager.GetElementType (type));
1387 } else if (type.IsGenericParameter || type.IsGenericInstance)
1390 DeclSpace type_ds = TypeManager.LookupDeclSpace (type);
1392 // Type is external, we can get attribute directly
1393 if (type_ds == null) {
1394 object[] attribute = type.GetCustomAttributes (TypeManager.obsolete_attribute_type, false);
1395 if (attribute.Length == 1)
1396 result = (ObsoleteAttribute)attribute [0];
1398 result = type_ds.GetObsoleteAttribute (type_ds);
1402 analyzed_types_obsolete.Add (type, result == null ? FALSE : result);
1407 /// Returns instance of ObsoleteAttribute when method is obsolete
1409 public static ObsoleteAttribute GetMethodObsoleteAttribute (MethodBase mb)
1411 IMethodData mc = TypeManager.GetMethod (mb);
1413 return mc.GetObsoleteAttribute ();
1415 return GetMemberObsoleteAttribute (mb);
1419 /// Returns instance of ObsoleteAttribute when member is obsolete
1421 public static ObsoleteAttribute GetMemberObsoleteAttribute (MemberInfo mi)
1423 object type_obsolete = analyzed_member_obsolete [mi];
1424 if (type_obsolete == FALSE)
1427 if (type_obsolete != null)
1428 return (ObsoleteAttribute)type_obsolete;
1430 if ((mi.DeclaringType is TypeBuilder) || mi.DeclaringType.IsGenericInstance)
1433 ObsoleteAttribute oa = System.Attribute.GetCustomAttribute (mi, TypeManager.obsolete_attribute_type, false) as ObsoleteAttribute;
1434 analyzed_member_obsolete.Add (mi, oa == null ? FALSE : oa);
1439 /// Common method for Obsolete error/warning reporting.
1441 public static void Report_ObsoleteMessage (ObsoleteAttribute oa, string member, Location loc)
1444 Report.Error_T (619, loc, member, oa.Message);
1448 if (oa.Message == null) {
1449 Report.Warning_T (612, loc, member);
1452 Report.Warning_T (618, loc, member, oa.Message);
1455 public static bool IsConditionalMethodExcluded (MethodBase mb)
1457 object excluded = analyzed_method_excluded [mb];
1458 if (excluded != null)
1459 return excluded == TRUE ? true : false;
1461 if (mb.Mono_IsInflatedMethod)
1464 ConditionalAttribute[] attrs = mb.GetCustomAttributes (TypeManager.conditional_attribute_type, true) as ConditionalAttribute[];
1465 if (attrs.Length == 0) {
1466 analyzed_method_excluded.Add (mb, FALSE);
1470 foreach (ConditionalAttribute a in attrs) {
1471 if (RootContext.AllDefines.Contains (a.ConditionString)) {
1472 analyzed_method_excluded.Add (mb, FALSE);
1476 analyzed_method_excluded.Add (mb, TRUE);