2 // attribute.cs: Attribute Handler
4 // Author: Ravi Pratap (ravi@ximian.com)
6 // Licensed under the terms of the GNU GPL
8 // (C) 2001 Ximian, Inc (http://www.ximian.com)
13 using System.Diagnostics;
14 using System.Collections;
15 using System.Collections.Specialized;
16 using System.Reflection;
17 using System.Reflection.Emit;
18 using System.Runtime.InteropServices;
19 using System.Runtime.CompilerServices;
22 namespace Mono.CSharp {
25 /// Base class for objects that can have Attributes applied to them.
27 public abstract class Attributable {
29 /// Attributes for this type
31 Attributes attributes;
33 public Attributable(Attributes attrs)
36 if (attributes != null)
37 attributes.CheckTargets (ValidAttributeTargets);
40 public Attributes OptAttributes
47 if (attributes != null)
48 attributes.CheckTargets (ValidAttributeTargets);
53 /// Use member-specific procedure to apply attribute @a in @cb to the entity being built in @builder
55 public abstract void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb);
58 /// Returns combination of enabled AttributeTargets
60 public abstract AttributeTargets AttributeTargets { get; }
62 public abstract bool IsClsCompliaceRequired (DeclSpace ds);
65 /// Gets list of valid attribute targets for explicit target declaration.
66 /// The first array item is default target. Don't break this rule.
68 protected abstract string[] ValidAttributeTargets { get; }
71 public class Attribute {
73 public readonly string Name;
74 public readonly ArrayList Arguments;
76 public readonly Location Location;
80 // Is non-null if type is AttributeUsageAttribute
81 AttributeUsageAttribute usage_attribute;
83 public AttributeUsageAttribute UsageAttribute {
85 return usage_attribute;
89 MethodImplOptions ImplOptions;
90 UnmanagedType UnmanagedType;
91 CustomAttributeBuilder cb;
93 // non-null if named args present after Resolve () is called
94 PropertyInfo [] prop_info_arr;
95 FieldInfo [] field_info_arr;
96 object [] field_values_arr;
97 object [] prop_values_arr;
100 static PtrHashtable usage_attr_cache = new PtrHashtable ();
102 public Attribute (string target, string name, ArrayList args, Location loc)
110 void Error_InvalidNamedArgument (string name)
112 Report.Error (617, Location, "'" + name + "' is not a valid named attribute " +
113 "argument. Named attribute arguments must be fields which are not " +
114 "readonly, static or const, or properties with a set accessor which "+
118 static void Error_AttributeArgumentNotValid (Location loc)
120 Report.Error (182, loc,
121 "An attribute argument must be a constant expression, typeof " +
122 "expression or array creation expression");
125 void Error_AttributeConstructorMismatch ()
127 Report.Error (-6, Location,
128 "Could not find a constructor for this argument list.");
132 /// Tries to resolve the type of the attribute. Flags an error if it can't, and complain is true.
134 protected virtual Type CheckAttributeType (EmitContext ec, bool complain)
136 Type t1 = RootContext.LookupType (ec.DeclSpace, Name, true, Location);
138 // FIXME: Shouldn't do this for quoted attributes: [@A]
139 Type t2 = RootContext.LookupType (ec.DeclSpace, Name + "Attribute", true, Location);
141 String err0616 = null;
143 if (t1 != null && ! t1.IsSubclassOf (TypeManager.attribute_type)) {
145 err0616 = "'" + Name + "': is not an attribute class";
147 if (t2 != null && ! t2.IsSubclassOf (TypeManager.attribute_type)) {
149 err0616 = (err0616 != null)
150 ? "Neither '" + Name + "' nor '" + Name + "Attribute' is an attribute class"
151 : "'" + Name + "Attribute': is not an attribute class";
154 if (t1 != null && t2 != null) {
155 Report.Error(1614, Location, "'" + Name + "': is ambiguous; "
156 + " use either '@" + Name + "' or '" + Name + "Attribute'");
164 if (err0616 != null) {
165 Report.Error (616, Location, err0616);
170 Report.Error (246, Location,
171 "Could not find attribute '" + Name
172 + "' (are you missing a using directive or an assembly reference ?)");
176 public Type ResolveType (EmitContext ec, bool complain)
179 Type = CheckAttributeType (ec, complain);
184 /// Validates the guid string
186 bool ValidateGuid (string guid)
192 Report.Error (647, Location, "Format of GUID is invalid: " + guid);
197 string GetFullMemberName (string member)
199 return Type.FullName + '.' + member;
203 // Given an expression, if the expression is a valid attribute-argument-expression
204 // returns an object that can be used to encode it, or null on failure.
206 public static bool GetAttributeArgumentExpression (Expression e, Location loc, out object result)
209 result = ((Constant) e).GetValue ();
211 } else if (e is TypeOf) {
212 result = ((TypeOf) e).TypeArg;
214 } else if (e is ArrayCreation){
215 result = ((ArrayCreation) e).EncodeAsAttribute ();
218 } else if (e is EmptyCast) {
220 if (((EmptyCast) e).Child is Constant) {
221 result = ((Constant) ((EmptyCast)e).Child).GetValue();
227 Error_AttributeArgumentNotValid (loc);
231 public CustomAttributeBuilder Resolve (EmitContext ec)
236 Type = CheckAttributeType (ec, true);
237 if (oldType == null && Type == null)
239 if (oldType != null && oldType != Type) {
240 Report.Error (-6, Location,
241 "Attribute {0} resolved to different types at different times: {1} vs. {2}",
242 Name, oldType, Type);
246 bool MethodImplAttr = false;
247 bool MarshalAsAttr = false;
248 bool GuidAttr = false;
249 bool usage_attr = false;
251 bool DoCompares = true;
254 // If we are a certain special attribute, we
255 // set the information accordingly
258 if (Type == TypeManager.attribute_usage_type)
260 else if (Type == TypeManager.methodimpl_attr_type)
261 MethodImplAttr = true;
262 else if (Type == TypeManager.marshal_as_attr_type)
263 MarshalAsAttr = true;
264 else if (Type == TypeManager.guid_attr_type)
269 // Now we extract the positional and named arguments
271 ArrayList pos_args = new ArrayList ();
272 ArrayList named_args = new ArrayList ();
273 int pos_arg_count = 0;
275 if (Arguments != null) {
276 pos_args = (ArrayList) Arguments [0];
277 if (pos_args != null)
278 pos_arg_count = pos_args.Count;
279 if (Arguments.Count > 1)
280 named_args = (ArrayList) Arguments [1];
283 pos_values = new object [pos_arg_count];
286 // First process positional arguments
290 for (i = 0; i < pos_arg_count; i++) {
291 Argument a = (Argument) pos_args [i];
294 if (!a.Resolve (ec, Location))
300 if (!GetAttributeArgumentExpression (e, Location, out val))
303 pos_values [i] = val;
306 usage_attribute = new AttributeUsageAttribute ((AttributeTargets) pos_values [0]);
307 else if (MethodImplAttr)
308 this.ImplOptions = (MethodImplOptions) pos_values [0];
311 // we will later check the validity of the type
313 if (pos_values [0] is string){
314 if (!ValidateGuid ((string) pos_values [0]))
318 } else if (MarshalAsAttr)
320 (System.Runtime.InteropServices.UnmanagedType) pos_values [0];
325 // Now process named arguments
328 ArrayList field_infos = null;
329 ArrayList prop_infos = null;
330 ArrayList field_values = null;
331 ArrayList prop_values = null;
333 if (named_args.Count > 0) {
334 field_infos = new ArrayList ();
335 prop_infos = new ArrayList ();
336 field_values = new ArrayList ();
337 prop_values = new ArrayList ();
340 Hashtable seen_names = new Hashtable();
342 for (i = 0; i < named_args.Count; i++) {
343 DictionaryEntry de = (DictionaryEntry) named_args [i];
344 string member_name = (string) de.Key;
345 Argument a = (Argument) de.Value;
348 if (seen_names.Contains(member_name)) {
349 Report.Error(643, Location, "'" + member_name + "' duplicate named attribute argument");
352 seen_names.Add(member_name, 1);
354 if (!a.Resolve (ec, Location))
357 Expression member = Expression.MemberLookup (
358 ec, Type, member_name,
359 MemberTypes.Field | MemberTypes.Property,
360 BindingFlags.Public | BindingFlags.Instance,
363 if (member == null) {
364 member = Expression.MemberLookup (ec, Type, member_name,
365 MemberTypes.Field | MemberTypes.Property, BindingFlags.NonPublic | BindingFlags.Instance,
368 if (member != null) {
369 Report.Error_T (122, Location, GetFullMemberName (member_name));
374 if (member == null || !(member is PropertyExpr || member is FieldExpr)) {
375 Error_InvalidNamedArgument (member_name);
380 if (member is PropertyExpr) {
381 PropertyExpr pe = (PropertyExpr) member;
382 PropertyInfo pi = pe.PropertyInfo;
385 Error_InvalidNamedArgument (member_name);
389 Constant c = e as Constant;
391 if (c.Type != pi.PropertyType) {
392 c = Const.ChangeType (Location, c, pi.PropertyType);
397 object o = c.GetValue ();
400 if (usage_attribute != null) {
401 if (member_name == "AllowMultiple")
402 usage_attribute.AllowMultiple = (bool) o;
403 if (member_name == "Inherited")
404 usage_attribute.Inherited = (bool) o;
407 } else if (e is TypeOf) {
408 prop_values.Add (((TypeOf) e).TypeArg);
409 } else if (e is ArrayCreation) {
410 prop_values.Add (((ArrayCreation) e).EncodeAsAttribute());
412 Error_AttributeArgumentNotValid (Location);
418 } else if (member is FieldExpr) {
419 FieldExpr fe = (FieldExpr) member;
420 FieldInfo fi = fe.FieldInfo;
423 Error_InvalidNamedArgument (member_name);
428 // Handle charset here, and set the TypeAttributes
430 Constant c = e as Constant;
432 if (c.Type != fi.FieldType) {
433 c = Const.ChangeType (Location, c, fi.FieldType);
438 object value = c.GetValue ();
439 field_values.Add (value);
440 } else if (e is TypeOf) {
441 field_values.Add (((TypeOf) e).TypeArg);
443 Error_AttributeArgumentNotValid (Location);
447 field_infos.Add (fi);
451 Expression mg = Expression.MemberLookup (
452 ec, Type, ".ctor", MemberTypes.Constructor,
453 BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly,
457 Error_AttributeConstructorMismatch ();
461 MethodBase constructor = Invocation.OverloadResolve (
462 ec, (MethodGroupExpr) mg, pos_args, Location);
464 if (constructor == null) {
465 Error_AttributeConstructorMismatch ();
470 // Now we perform some checks on the positional args as they
471 // cannot be null for a constructor which expects a parameter
475 ParameterData pd = Invocation.GetParameterData (constructor);
477 int group_in_params_array = Int32.MaxValue;
479 if (pc > 0 && pd.ParameterModifier (pc-1) == Parameter.Modifier.PARAMS)
480 group_in_params_array = pc-1;
482 for (int j = 0; j < pos_arg_count; ++j) {
483 Argument a = (Argument) pos_args [j];
485 if (a.Expr is NullLiteral && pd.ParameterType (j) == TypeManager.object_type) {
486 Error_AttributeArgumentNotValid (Location);
490 if (j < group_in_params_array)
493 if (j == group_in_params_array){
494 object v = pos_values [j];
495 int count = pos_arg_count - j;
497 object [] array = new object [count];
498 pos_values [j] = array;
501 object [] array = (object []) pos_values [group_in_params_array];
503 array [j - group_in_params_array] = pos_values [j];
508 // Adjust the size of the pos_values if it had params
510 if (group_in_params_array != Int32.MaxValue){
511 int argc = group_in_params_array+1;
512 object [] new_pos_values = new object [argc];
514 for (int p = 0; p < argc; p++)
515 new_pos_values [p] = pos_values [p];
516 pos_values = new_pos_values;
520 if (named_args.Count > 0) {
521 prop_info_arr = new PropertyInfo [prop_infos.Count];
522 field_info_arr = new FieldInfo [field_infos.Count];
523 field_values_arr = new object [field_values.Count];
524 prop_values_arr = new object [prop_values.Count];
526 field_infos.CopyTo (field_info_arr, 0);
527 field_values.CopyTo (field_values_arr, 0);
529 prop_values.CopyTo (prop_values_arr, 0);
530 prop_infos.CopyTo (prop_info_arr, 0);
532 cb = new CustomAttributeBuilder (
533 (ConstructorInfo) constructor, pos_values,
534 prop_info_arr, prop_values_arr,
535 field_info_arr, field_values_arr);
538 cb = new CustomAttributeBuilder (
539 (ConstructorInfo) constructor, pos_values);
540 } catch (NullReferenceException) {
542 // Don't know what to do here
545 -101, Location, "NullReferenceException while trying to create attribute." +
546 "Something's wrong!");
547 } catch (Exception e) {
550 // using System.ComponentModel;
551 // [DefaultValue (CollectionChangeAction.Add)]
552 // class X { static void Main () {} }
555 -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);
562 /// Get a string containing a list of valid targets for the attribute 'attr'
564 static string GetValidTargets (Attribute attr)
566 StringBuilder sb = new StringBuilder ();
567 AttributeTargets targets = attr.GetAttributeUsage ().ValidOn;
569 if ((targets & AttributeTargets.Assembly) != 0)
570 sb.Append ("'assembly' ");
572 if ((targets & AttributeTargets.Class) != 0)
573 sb.Append ("'class' ");
575 if ((targets & AttributeTargets.Constructor) != 0)
576 sb.Append ("'constructor' ");
578 if ((targets & AttributeTargets.Delegate) != 0)
579 sb.Append ("'delegate' ");
581 if ((targets & AttributeTargets.Enum) != 0)
582 sb.Append ("'enum' ");
584 if ((targets & AttributeTargets.Event) != 0)
585 sb.Append ("'event' ");
587 if ((targets & AttributeTargets.Field) != 0)
588 sb.Append ("'field' ");
590 if ((targets & AttributeTargets.Interface) != 0)
591 sb.Append ("'interface' ");
593 if ((targets & AttributeTargets.Method) != 0)
594 sb.Append ("'method' ");
596 if ((targets & AttributeTargets.Module) != 0)
597 sb.Append ("'module' ");
599 if ((targets & AttributeTargets.Parameter) != 0)
600 sb.Append ("'parameter' ");
602 if ((targets & AttributeTargets.Property) != 0)
603 sb.Append ("'property' ");
605 if ((targets & AttributeTargets.ReturnValue) != 0)
606 sb.Append ("'return' ");
608 if ((targets & AttributeTargets.Struct) != 0)
609 sb.Append ("'struct' ");
611 return sb.ToString ();
615 public static void Error_AttributeNotValidForElement (Attribute a, Location loc)
618 592, loc, "Attribute '" + a.Name +
619 "' is not valid on this declaration type. " +
620 "It is valid on " + GetValidTargets (a) + "declarations only.");
625 /// Returns AttributeUsage attribute for this type
627 public AttributeUsageAttribute GetAttributeUsage ()
629 AttributeUsageAttribute ua = usage_attr_cache [Type] as AttributeUsageAttribute;
633 Class attr_class = TypeManager.LookupClass (Type);
635 if (attr_class == null) {
636 object[] usage_attr = Type.GetCustomAttributes (TypeManager.attribute_usage_type, true);
637 ua = (AttributeUsageAttribute)usage_attr [0];
638 usage_attr_cache.Add (Type, ua);
642 return attr_class.AttributeUsage;
647 // This pulls the condition name out of a Conditional attribute
649 public string Conditional_GetConditionName ()
652 // So we have a Conditional, pull the data out.
654 if (Arguments == null || Arguments [0] == null){
655 Error_AttributeConstructorMismatch ();
659 ArrayList pos_args = (ArrayList) Arguments [0];
660 if (pos_args.Count != 1){
661 Error_AttributeConstructorMismatch ();
665 Argument arg = (Argument) pos_args [0];
666 if (!(arg.Expr is StringConstant)){
667 Error_AttributeConstructorMismatch ();
671 return ((StringConstant) arg.Expr).Value;
674 public string IndexerName_GetIndexerName (EmitContext ec)
676 if (Arguments == null || Arguments [0] == null){
677 Error_AttributeConstructorMismatch ();
680 ArrayList pos_args = (ArrayList) Arguments [0];
681 if (pos_args.Count != 1) {
682 Error_AttributeConstructorMismatch ();
686 Argument arg = (Argument) pos_args [0];
687 if (!arg.Resolve (ec, Location))
690 StringConstant sc = arg.Expr as StringConstant;
692 Error_AttributeConstructorMismatch ();
700 /// Returns condition of ConditionalAttribute
702 public string GetConditionalAttributeValue (DeclSpace ds)
704 if (pos_values == null) {
705 EmitContext ec = new EmitContext (ds, ds, Location, null, null, 0, false);
707 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
708 // But because a lot of attribute class code must be rewritten will be better to wait...
712 // Some error occurred
713 if (pos_values [0] == null)
716 return (string)pos_values [0];
720 /// Creates the instance of ObsoleteAttribute from this attribute instance
722 public ObsoleteAttribute GetObsoleteAttribute (DeclSpace ds)
724 if (pos_values == null) {
725 EmitContext ec = new EmitContext (ds, ds, Location, null, null, 0, false);
727 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
728 // But because a lot of attribute class code must be rewritten will be better to wait...
732 // Some error occurred
733 if (pos_values == null)
736 if (pos_values.Length == 0)
737 return new ObsoleteAttribute ();
739 if (pos_values.Length == 1)
740 return new ObsoleteAttribute ((string)pos_values [0]);
742 return new ObsoleteAttribute ((string)pos_values [0], (bool)pos_values [1]);
746 /// Returns value of CLSCompliantAttribute contructor parameter but because the method can be called
747 /// before ApplyAttribute. We need to resolve the arguments.
748 /// This situation occurs when class deps is differs from Emit order.
750 public bool GetClsCompliantAttributeValue (DeclSpace ds)
752 if (pos_values == null) {
753 EmitContext ec = new EmitContext (ds, ds, Location, null, null, 0, false);
755 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
756 // But because a lot of attribute class code must be rewritten will be better to wait...
760 // Some error occurred
761 if (pos_values [0] == null)
764 return (bool)pos_values [0];
767 public object GetPositionalValue (int i)
769 return (pos_values == null) ? null : pos_values[i];
772 object GetFieldValue (string name)
775 if (field_info_arr == null)
778 foreach (FieldInfo fi in field_info_arr) {
780 return field_values_arr [i];
786 public UnmanagedMarshal GetMarshal ()
788 object o = GetFieldValue ("ArraySubType");
789 UnmanagedType array_sub_type = o == null ? UnmanagedType.I4 : (UnmanagedType) o;
791 switch (UnmanagedType) {
792 case UnmanagedType.CustomMarshaler:
793 MethodInfo define_custom = typeof (UnmanagedMarshal).GetMethod ("DefineCustom",
794 BindingFlags.Static | BindingFlags.Public);
795 if (define_custom == null)
798 object [] args = new object [4];
799 args [0] = GetFieldValue ("MarshalTypeRef");
800 args [1] = GetFieldValue ("MarshalCookie");
801 args [2] = GetFieldValue ("MarshalType");
802 args [3] = Guid.Empty;
803 return (UnmanagedMarshal) define_custom.Invoke (null, args);
805 case UnmanagedType.LPArray:
806 return UnmanagedMarshal.DefineLPArray (array_sub_type);
808 case UnmanagedType.SafeArray:
809 return UnmanagedMarshal.DefineSafeArray (array_sub_type);
811 case UnmanagedType.ByValArray:
812 return UnmanagedMarshal.DefineByValArray ((int) GetFieldValue ("SizeConst"));
814 case UnmanagedType.ByValTStr:
815 return UnmanagedMarshal.DefineByValTStr ((int) GetFieldValue ("SizeConst"));
818 return UnmanagedMarshal.DefineUnmanagedMarshal (UnmanagedType);
822 public bool IsInternalCall
824 get { return ImplOptions == MethodImplOptions.InternalCall; }
828 /// Emit attribute for Attributable symbol
830 public void Emit (EmitContext ec, Attributable ias, ListDictionary emitted_attr)
832 CustomAttributeBuilder cb = Resolve (ec);
836 AttributeUsageAttribute usage_attr = GetAttributeUsage ();
837 if ((usage_attr.ValidOn & ias.AttributeTargets) == 0) {
838 Error_AttributeNotValidForElement (this, Location);
842 ias.ApplyAttributeBuilder (this, cb);
844 if (!usage_attr.AllowMultiple && emitted_attr.Contains (Target)) {
845 Report.Error (579, Location, "Duplicate '" + Name + "' attribute");
848 emitted_attr [Type] = Target;
850 // Here we are testing attribute arguments for array usage (error 3016)
851 if (ias.IsClsCompliaceRequired (ec.DeclSpace)) {
852 if (Arguments == null)
855 ArrayList pos_args = (ArrayList) Arguments [0];
856 if (pos_args != null) {
857 foreach (Argument arg in pos_args) {
858 // Type is undefined (was error 246)
859 if (arg.Type == null)
862 if (arg.Type.IsArray) {
863 Report.Error_T (3016, Location);
869 if (Arguments.Count < 2)
872 ArrayList named_args = (ArrayList) Arguments [1];
873 foreach (DictionaryEntry de in named_args) {
874 Argument arg = (Argument) de.Value;
876 // Type is undefined (was error 246)
877 if (arg.Type == null)
880 if (arg.Type.IsArray) {
881 Report.Error_T (3016, Location);
888 public object GetValue (EmitContext ec, Constant c, Type target)
890 if (Convert.ImplicitConversionExists (ec, c, target))
891 return c.GetValue ();
893 Convert.Error_CannotImplicitConversion (Location, c.Type, target);
897 public MethodBuilder DefinePInvokeMethod (EmitContext ec, TypeBuilder builder, string name,
898 MethodAttributes flags, Type ret_type, Type [] param_types)
901 // We extract from the attribute the information we need
904 if (Arguments == null) {
905 Console.WriteLine ("Internal error : this is not supposed to happen !");
909 ResolveType (ec, true);
913 ArrayList named_args = new ArrayList ();
915 ArrayList pos_args = (ArrayList) Arguments [0];
916 if (Arguments.Count > 1)
917 named_args = (ArrayList) Arguments [1];
920 string dll_name = null;
922 Argument tmp = (Argument) pos_args [0];
924 if (!tmp.Resolve (ec, Location))
927 if (tmp.Expr is Constant)
928 dll_name = (string) ((Constant) tmp.Expr).GetValue ();
930 Error_AttributeArgumentNotValid (Location);
934 // Now we process the named arguments
935 CallingConvention cc = CallingConvention.Winapi;
936 CharSet charset = CharSet.Ansi;
937 bool preserve_sig = true;
939 bool exact_spelling = false;
941 bool set_last_err = false;
942 string entry_point = null;
944 for (int i = 0; i < named_args.Count; i++) {
946 DictionaryEntry de = (DictionaryEntry) named_args [i];
948 string member_name = (string) de.Key;
949 Argument a = (Argument) de.Value;
951 if (!a.Resolve (ec, Location))
954 Expression member = Expression.MemberLookup (
955 ec, Type, member_name,
956 MemberTypes.Field | MemberTypes.Property,
957 BindingFlags.Public | BindingFlags.Instance,
960 if (member == null || !(member is FieldExpr)) {
961 Error_InvalidNamedArgument (member_name);
965 if (member is FieldExpr) {
966 FieldExpr fe = (FieldExpr) member;
967 FieldInfo fi = fe.FieldInfo;
970 Error_InvalidNamedArgument (member_name);
974 if (a.Expr is Constant) {
975 Constant c = (Constant) a.Expr;
978 if (member_name == "CallingConvention"){
979 object val = GetValue (ec, c, typeof (CallingConvention));
982 cc = (CallingConvention) val;
983 } else if (member_name == "CharSet"){
984 charset = (CharSet) c.GetValue ();
985 } else if (member_name == "EntryPoint")
986 entry_point = (string) c.GetValue ();
987 else if (member_name == "SetLastError")
988 set_last_err = (bool) c.GetValue ();
990 else if (member_name == "ExactSpelling")
991 exact_spelling = (bool) c.GetValue ();
993 else if (member_name == "PreserveSig")
994 preserve_sig = (bool) c.GetValue ();
995 } catch (InvalidCastException){
996 Error_InvalidNamedArgument (member_name);
997 Error_AttributeArgumentNotValid (Location);
1000 Error_AttributeArgumentNotValid (Location);
1007 if (entry_point == null)
1010 charset = (CharSet)((int)charset | 0x40);
1012 MethodBuilder mb = builder.DefinePInvokeMethod (
1013 name, dll_name, entry_point, flags | MethodAttributes.HideBySig,
1014 CallingConventions.Standard,
1021 mb.SetImplementationFlags (MethodImplAttributes.PreserveSig);
1026 private Expression GetValue ()
1028 if ((Arguments == null) || (Arguments.Count < 1))
1030 ArrayList al = (ArrayList) Arguments [0];
1031 if ((al == null) || (al.Count < 1))
1033 Argument arg = (Argument) al [0];
1034 if ((arg == null) || (arg.Expr == null))
1039 public string GetString ()
1041 Expression e = GetValue ();
1042 if (e is StringLiteral)
1043 return (e as StringLiteral).Value;
1047 public bool GetBoolean ()
1049 Expression e = GetValue ();
1050 if (e is BoolLiteral)
1051 return (e as BoolLiteral).Value;
1058 /// For global attributes (assembly, module) we need special handling.
1059 /// Attributes can be located in the several files
1061 public class GlobalAttribute: Attribute
1063 public readonly NamespaceEntry ns;
1065 public GlobalAttribute (TypeContainer container, string target, string name, ArrayList args, Location loc):
1066 base (target, name, args, loc)
1068 ns = container.NamespaceEntry;
1071 protected override Type CheckAttributeType (EmitContext ec, bool complain)
1073 NamespaceEntry old = ec.DeclSpace.NamespaceEntry;
1074 if (old == null || old.NS == null || old.NS == Namespace.Root)
1075 ec.DeclSpace.NamespaceEntry = ns;
1076 return base.CheckAttributeType (ec, complain);
1080 public class Attributes {
1081 public ArrayList Attrs;
1083 public Attributes (Attribute a)
1085 Attrs = new ArrayList ();
1089 public Attributes (ArrayList attrs)
1094 public void AddAttributes (ArrayList attrs)
1096 Attrs.AddRange (attrs);
1100 /// Checks whether attribute target is valid for the current element
1102 public void CheckTargets (string[] possible_targets)
1104 foreach (Attribute a in Attrs) {
1105 if (a.Target == null) {
1106 a.Target = possible_targets [0];
1110 if (((IList) possible_targets).Contains (a.Target))
1113 StringBuilder sb = new StringBuilder ();
1114 foreach (string s in possible_targets) {
1118 sb.Remove (sb.Length - 2, 2);
1119 Report.Error_T (657, a.Location, a.Target, sb.ToString ());
1123 private Attribute Search (Type t, EmitContext ec, bool complain)
1125 foreach (Attribute a in Attrs) {
1126 if (a.ResolveType (ec, false) == t)
1132 public Attribute Search (Type t, EmitContext ec)
1134 return Search (t, ec, true);
1138 /// Returns all attributes of type 't'. Use it when attribute is AllowMultiple = true
1140 public Attribute[] SearchMulti (Type t, EmitContext ec)
1142 ArrayList ar = new ArrayList ();
1144 foreach (Attribute a in Attrs) {
1145 if (a.ResolveType (ec, false) == t)
1148 return ar.ToArray (typeof (Attribute)) as Attribute[];
1151 public void Emit (EmitContext ec, Attributable ias)
1153 ListDictionary ld = new ListDictionary ();
1155 foreach (Attribute a in Attrs)
1156 a.Emit (ec, ias, ld);
1159 public bool Contains (Type t, EmitContext ec)
1161 return Search (t, ec) != null;
1164 public Attribute GetClsCompliantAttribute (EmitContext ec)
1166 return Search (TypeManager.cls_compliant_attribute_type, ec, false);
1170 /// Pulls the IndexerName attribute from an Indexer if it exists.
1172 public string ScanForIndexerName (EmitContext ec)
1174 Attribute a = Search (TypeManager.indexer_name_type, ec);
1178 // Remove the attribute from the list
1179 //TODO: It is very close to hack and it can crash here
1182 return a.IndexerName_GetIndexerName (ec);
1188 /// Helper class for attribute verification routine.
1190 sealed class AttributeTester
1192 static PtrHashtable analyzed_types = new PtrHashtable ();
1193 static PtrHashtable analyzed_member_obsolete = new PtrHashtable ();
1194 static PtrHashtable analyzed_method_excluded = new PtrHashtable ();
1196 private AttributeTester ()
1201 /// Returns true if parameters of two compared methods are CLS-Compliant.
1202 /// It tests differing only in ref or out, or in array rank.
1204 public static bool AreOverloadedMethodParamsClsCompliant (Type[] types_a, Type[] types_b)
1206 if (types_a == null || types_b == null)
1209 if (types_a.Length != types_b.Length)
1212 for (int i = 0; i < types_b.Length; ++i) {
1213 Type aType = types_a [i];
1214 Type bType = types_b [i];
1216 if (aType.IsArray && bType.IsArray && aType.GetArrayRank () != bType.GetArrayRank () && aType.GetElementType () == bType.GetElementType ()) {
1220 Type aBaseType = aType;
1221 bool is_either_ref_or_out = false;
1223 if (aType.IsByRef || aType.IsPointer) {
1224 aBaseType = aType.GetElementType ();
1225 is_either_ref_or_out = true;
1228 Type bBaseType = bType;
1229 if (bType.IsByRef || bType.IsPointer)
1231 bBaseType = bType.GetElementType ();
1232 is_either_ref_or_out = !is_either_ref_or_out;
1235 if (aBaseType != bBaseType)
1238 if (is_either_ref_or_out)
1245 /// Goes through all parameters and test if they are CLS-Compliant.
1247 public static bool AreParametersCompliant (Parameter[] fixedParameters, Location loc)
1249 if (fixedParameters == null)
1252 foreach (Parameter arg in fixedParameters) {
1253 if (!AttributeTester.IsClsCompliant (arg.ParameterType)) {
1254 Report.Error_T (3001, loc, arg.GetSignatureForError ());
1263 /// This method tests the CLS compliance of external types. It doesn't test type visibility.
1265 public static bool IsClsCompliant (Type type)
1270 object type_compliance = analyzed_types[type];
1271 if (type_compliance != null)
1272 return type_compliance == TRUE;
1274 if (type.IsPointer) {
1275 analyzed_types.Add (type, null);
1280 if (type.IsArray || type.IsByRef) {
1281 result = IsClsCompliant (TypeManager.GetElementType (type));
1283 result = AnalyzeTypeCompliance (type);
1285 analyzed_types.Add (type, result ? TRUE : FALSE);
1289 static object TRUE = new object ();
1290 static object FALSE = new object ();
1293 /// Non-hierarchical CLS Compliance analyzer
1295 public static bool IsComplianceRequired (MemberInfo mi, DeclSpace ds)
1297 DeclSpace temp_ds = TypeManager.LookupDeclSpace (mi.DeclaringType);
1299 // Type is external, we can get attribute directly
1300 if (temp_ds == null) {
1301 object[] cls_attribute = mi.GetCustomAttributes (TypeManager.cls_compliant_attribute_type, false);
1302 return (cls_attribute.Length == 1 && ((CLSCompliantAttribute)cls_attribute[0]).IsCompliant);
1306 // Interface doesn't store full name
1307 if (temp_ds is Interface)
1310 tmp_name = String.Concat (temp_ds.Name, ".", mi.Name);
1312 MemberCore mc = temp_ds.GetDefinition (tmp_name) as MemberCore;
1313 return mc.IsClsCompliaceRequired (ds);
1316 public static void VerifyModulesClsCompliance ()
1318 Module[] modules = TypeManager.Modules;
1319 if (modules == null)
1322 // The first module is generated assembly
1323 for (int i = 1; i < modules.Length; ++i) {
1324 Module module = modules [i];
1325 if (!IsClsCompliant (module)) {
1326 Report.Error_T (3013, module.Name);
1332 static bool IsClsCompliant (ICustomAttributeProvider attribute_provider)
1334 object[] CompliantAttribute = attribute_provider.GetCustomAttributes (TypeManager.cls_compliant_attribute_type, false);
1335 if (CompliantAttribute.Length == 0)
1338 return ((CLSCompliantAttribute)CompliantAttribute[0]).IsCompliant;
1341 static bool AnalyzeTypeCompliance (Type type)
1343 DeclSpace ds = TypeManager.LookupDeclSpace (type);
1345 return ds.IsClsCompliaceRequired (ds.Parent);
1348 object[] CompliantAttribute = type.GetCustomAttributes (TypeManager.cls_compliant_attribute_type, false);
1349 if (CompliantAttribute.Length == 0)
1350 return IsClsCompliant (type.Assembly);
1352 return ((CLSCompliantAttribute)CompliantAttribute[0]).IsCompliant;
1356 /// Returns instance of ObsoleteAttribute when method is obsolete
1358 public static ObsoleteAttribute GetMethodObsoleteAttribute (MethodBase mb)
1360 IMethodData mc = TypeManager.GetMethod (mb);
1362 return mc.GetObsoleteAttribute ();
1364 // TODO: remove after Constructor will be ready for IMethodData
1365 if (mb.DeclaringType is TypeBuilder)
1368 return GetMemberObsoleteAttribute (mb);
1372 /// Returns instance of ObsoleteAttribute when member is obsolete
1374 public static ObsoleteAttribute GetMemberObsoleteAttribute (MemberInfo mi)
1376 object type_obsolete = analyzed_member_obsolete [mi];
1377 if (type_obsolete == FALSE)
1380 if (type_obsolete != null)
1381 return (ObsoleteAttribute)type_obsolete;
1383 ObsoleteAttribute oa = System.Attribute.GetCustomAttribute (mi, TypeManager.obsolete_attribute_type, false) as ObsoleteAttribute;
1384 analyzed_member_obsolete.Add (mi, oa == null ? FALSE : oa);
1389 /// Common method for Obsolete error/warning reporting.
1391 public static void Report_ObsoleteMessage (ObsoleteAttribute oa, string member, Location loc)
1394 Report.Error_T (619, loc, member, oa.Message);
1398 if (oa.Message == null) {
1399 Report.Warning_T (612, loc, member);
1402 Report.Warning_T (618, loc, member, oa.Message);
1405 public static bool IsConditionalMethodExcluded (MethodBase mb)
1407 object excluded = analyzed_method_excluded [mb];
1408 if (excluded != null)
1409 return excluded == TRUE ? true : false;
1411 ConditionalAttribute[] attrs = mb.GetCustomAttributes (TypeManager.conditional_attribute_type, true) as ConditionalAttribute[];
1412 if (attrs.Length == 0) {
1413 analyzed_method_excluded.Add (mb, FALSE);
1417 foreach (ConditionalAttribute a in attrs) {
1418 if (RootContext.AllDefines.Contains (a.ConditionString)) {
1419 analyzed_method_excluded.Add (mb, FALSE);
1423 analyzed_method_excluded.Add (mb, TRUE);