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
51 /// Use member-specific procedure to apply attribute @a in @cb to the entity being built in @builder
53 public abstract void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb);
56 /// Returns combination of enabled AttributeTargets
58 public abstract AttributeTargets AttributeTargets { get; }
60 public abstract bool IsClsCompliaceRequired (DeclSpace ds);
63 /// Gets list of valid attribute targets for explicit target declaration
65 protected abstract string[] ValidAttributeTargets { get; }
68 public class Attribute {
69 public readonly string Target;
70 public readonly string Name;
71 public readonly ArrayList Arguments;
73 public readonly Location Location;
77 // Is non-null if type is AttributeUsageAttribute
78 AttributeUsageAttribute usage_attribute;
80 public AttributeUsageAttribute UsageAttribute {
82 return usage_attribute;
86 MethodImplOptions ImplOptions;
87 UnmanagedType UnmanagedType;
88 CustomAttributeBuilder cb;
90 // non-null if named args present after Resolve () is called
91 PropertyInfo [] prop_info_arr;
92 FieldInfo [] field_info_arr;
93 object [] field_values_arr;
94 object [] prop_values_arr;
97 static PtrHashtable usage_attr_cache = new PtrHashtable ();
99 public Attribute (string target, string name, ArrayList args, Location loc)
107 void Error_InvalidNamedArgument (string name)
109 Report.Error (617, Location, "'" + name + "' is not a valid named attribute " +
110 "argument. Named attribute arguments must be fields which are not " +
111 "readonly, static or const, or properties with a set accessor which "+
115 static void Error_AttributeArgumentNotValid (Location loc)
117 Report.Error (182, loc,
118 "An attribute argument must be a constant expression, typeof " +
119 "expression or array creation expression");
122 void Error_AttributeConstructorMismatch ()
124 Report.Error (-6, Location,
125 "Could not find a constructor for this argument list.");
128 static void Error_TypeParameterInAttribute (Location loc)
131 -202, loc, "Can not use a type parameter in an attribute");
135 /// Tries to resolve the type of the attribute. Flags an error if it can't, and complain is true.
137 protected virtual Type CheckAttributeType (EmitContext ec, bool complain)
139 TypeExpr t1 = RootContext.LookupType (ec.DeclSpace, Name, true, Location);
140 // FIXME: Shouldn't do this for quoted attributes: [@A]
141 TypeExpr t2 = RootContext.LookupType (ec.DeclSpace, Name + "Attribute", true, Location);
143 String err0616 = null;
144 if (t1 != null && ! t1.IsAttribute) {
146 err0616 = "'" + Name + "': is not an attribute class";
148 if (t2 != null && ! t2.IsAttribute) {
150 err0616 = (err0616 != null)
151 ? "Neither '" + Name + "' nor '" + Name + "Attribute' is an attribute class"
152 : "'" + Name + "Attribute': is not an attribute class";
155 if (t1 != null && t2 != null) {
156 Report.Error(1614, Location, "'" + Name + "': is ambiguous; "
157 + " use either '@" + Name + "' or '" + Name + "Attribute'");
161 return t1.ResolveType (ec);
163 return t2.ResolveType (ec);
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);
198 // Given an expression, if the expression is a valid attribute-argument-expression
199 // returns an object that can be used to encode it, or null on failure.
201 public static bool GetAttributeArgumentExpression (Expression e, Location loc, out object result)
204 result = ((Constant) e).GetValue ();
206 } else if (e is TypeOf) {
207 result = ((TypeOf) e).TypeArg;
209 } else if (e is ArrayCreation){
210 result = ((ArrayCreation) e).EncodeAsAttribute ();
213 } else if (e is EmptyCast) {
215 if (((EmptyCast) e).Child is Constant) {
216 result = ((Constant) ((EmptyCast)e).Child).GetValue();
222 Error_AttributeArgumentNotValid (loc);
226 public CustomAttributeBuilder Resolve (EmitContext ec)
231 Type = CheckAttributeType (ec, true);
232 if (oldType == null && Type == null)
234 if (oldType != null && oldType != Type) {
235 Report.Error (-6, Location,
236 "Attribute {0} resolved to different types at different times: {1} vs. {2}",
237 Name, oldType, Type);
241 bool MethodImplAttr = false;
242 bool MarshalAsAttr = false;
243 bool GuidAttr = false;
244 bool usage_attr = false;
246 bool DoCompares = true;
249 // If we are a certain special attribute, we
250 // set the information accordingly
253 if (Type == TypeManager.attribute_usage_type)
255 else if (Type == TypeManager.methodimpl_attr_type)
256 MethodImplAttr = true;
257 else if (Type == TypeManager.marshal_as_attr_type)
258 MarshalAsAttr = true;
259 else if (Type == TypeManager.guid_attr_type)
264 // Now we extract the positional and named arguments
266 ArrayList pos_args = new ArrayList ();
267 ArrayList named_args = new ArrayList ();
268 int pos_arg_count = 0;
270 if (Arguments != null) {
271 pos_args = (ArrayList) Arguments [0];
272 if (pos_args != null)
273 pos_arg_count = pos_args.Count;
274 if (Arguments.Count > 1)
275 named_args = (ArrayList) Arguments [1];
278 pos_values = new object [pos_arg_count];
281 // First process positional arguments
285 for (i = 0; i < pos_arg_count; i++) {
286 Argument a = (Argument) pos_args [i];
289 if (!a.Resolve (ec, Location))
295 if (!GetAttributeArgumentExpression (e, Location, out val))
298 pos_values [i] = val;
301 usage_attribute = new AttributeUsageAttribute ((AttributeTargets) pos_values [0]);
302 else if (MethodImplAttr)
303 this.ImplOptions = (MethodImplOptions) pos_values [0];
306 // we will later check the validity of the type
308 if (pos_values [0] is string){
309 if (!ValidateGuid ((string) pos_values [0]))
313 } else if (MarshalAsAttr)
315 (System.Runtime.InteropServices.UnmanagedType) pos_values [0];
320 // Now process named arguments
323 ArrayList field_infos = null;
324 ArrayList prop_infos = null;
325 ArrayList field_values = null;
326 ArrayList prop_values = null;
328 if (named_args.Count > 0) {
329 field_infos = new ArrayList ();
330 prop_infos = new ArrayList ();
331 field_values = new ArrayList ();
332 prop_values = new ArrayList ();
335 Hashtable seen_names = new Hashtable();
337 for (i = 0; i < named_args.Count; i++) {
338 DictionaryEntry de = (DictionaryEntry) named_args [i];
339 string member_name = (string) de.Key;
340 Argument a = (Argument) de.Value;
343 if (seen_names.Contains(member_name)) {
344 Report.Error(643, Location, "'" + member_name + "' duplicate named attribute argument");
347 seen_names.Add(member_name, 1);
349 if (!a.Resolve (ec, Location))
352 Expression member = Expression.MemberLookup (
353 ec, Type, member_name,
354 MemberTypes.Field | MemberTypes.Property,
355 BindingFlags.Public | BindingFlags.Instance,
358 if (member == null || !(member is PropertyExpr || member is FieldExpr)) {
359 Error_InvalidNamedArgument (member_name);
364 if (e is TypeParameterExpr){
365 Error_TypeParameterInAttribute (Location);
369 if (member is PropertyExpr) {
370 PropertyExpr pe = (PropertyExpr) member;
371 PropertyInfo pi = pe.PropertyInfo;
374 Error_InvalidNamedArgument (member_name);
381 if (e.Type != pi.PropertyType){
382 c = Const.ChangeType (Location, (Constant) e, pi.PropertyType);
388 object o = c.GetValue ();
391 if (usage_attribute != null) {
392 if (member_name == "AllowMultiple")
393 usage_attribute.AllowMultiple = (bool) o;
394 if (member_name == "Inherited")
395 usage_attribute.Inherited = (bool) o;
398 } else if (e is TypeOf) {
399 prop_values.Add (((TypeOf) e).TypeArg);
400 } else if (e is ArrayCreation) {
401 prop_values.Add (((ArrayCreation) e).EncodeAsAttribute());
403 Error_AttributeArgumentNotValid (Location);
409 } else if (member is FieldExpr) {
410 FieldExpr fe = (FieldExpr) member;
411 FieldInfo fi = fe.FieldInfo;
414 Error_InvalidNamedArgument (member_name);
419 // Handle charset here, and set the TypeAttributes
422 Constant c = (Constant) e;;
424 if (c.Type != fi.FieldType){
425 c = Const.ChangeType (Location, (Constant) e, fi.FieldType);
430 object value = c.GetValue ();
431 field_values.Add (value);
432 } else if (e is TypeOf) {
433 field_values.Add (((TypeOf) e).TypeArg);
435 Error_AttributeArgumentNotValid (Location);
439 field_infos.Add (fi);
443 Expression mg = Expression.MemberLookup (
444 ec, Type, ".ctor", MemberTypes.Constructor,
445 BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly,
449 Error_AttributeConstructorMismatch ();
453 MethodBase constructor = Invocation.OverloadResolve (
454 ec, (MethodGroupExpr) mg, pos_args, false, Location);
456 if (constructor == null) {
457 Error_AttributeConstructorMismatch ();
462 // Now we perform some checks on the positional args as they
463 // cannot be null for a constructor which expects a parameter
467 ParameterData pd = Invocation.GetParameterData (constructor);
469 int group_in_params_array = Int32.MaxValue;
471 if (pc > 0 && pd.ParameterModifier (pc-1) == Parameter.Modifier.PARAMS)
472 group_in_params_array = pc-1;
474 for (int j = 0; j < pos_arg_count; ++j) {
475 Argument a = (Argument) pos_args [j];
477 if (a.Expr is NullLiteral && pd.ParameterType (j) == TypeManager.object_type) {
478 Error_AttributeArgumentNotValid (Location);
482 if (j < group_in_params_array)
485 if (j == group_in_params_array){
486 object v = pos_values [j];
487 int count = pos_arg_count - j;
489 object [] array = new object [count];
490 pos_values [j] = array;
493 object [] array = (object []) pos_values [group_in_params_array];
495 array [j - group_in_params_array] = pos_values [j];
500 // Adjust the size of the pos_values if it had params
502 if (group_in_params_array != Int32.MaxValue){
503 int argc = group_in_params_array+1;
504 object [] new_pos_values = new object [argc];
506 for (int p = 0; p < argc; p++)
507 new_pos_values [p] = pos_values [p];
508 pos_values = new_pos_values;
512 if (named_args.Count > 0) {
513 prop_info_arr = new PropertyInfo [prop_infos.Count];
514 field_info_arr = new FieldInfo [field_infos.Count];
515 field_values_arr = new object [field_values.Count];
516 prop_values_arr = new object [prop_values.Count];
518 field_infos.CopyTo (field_info_arr, 0);
519 field_values.CopyTo (field_values_arr, 0);
521 prop_values.CopyTo (prop_values_arr, 0);
522 prop_infos.CopyTo (prop_info_arr, 0);
524 cb = new CustomAttributeBuilder (
525 (ConstructorInfo) constructor, pos_values,
526 prop_info_arr, prop_values_arr,
527 field_info_arr, field_values_arr);
530 cb = new CustomAttributeBuilder (
531 (ConstructorInfo) constructor, pos_values);
532 } catch (NullReferenceException) {
534 // Don't know what to do here
537 -101, Location, "NullReferenceException while trying to create attribute." +
538 "Something's wrong!");
539 } catch (Exception e) {
542 // using System.ComponentModel;
543 // [DefaultValue (CollectionChangeAction.Add)]
544 // class X { static void Main () {} }
548 "The compiler can not encode this attribute in .NET due to\n" +
549 "\ta bug in the .NET runtime. Try the Mono runtime.\nThe error was: " + e.Message);
556 /// Get a string containing a list of valid targets for the attribute 'attr'
558 static string GetValidTargets (Attribute attr)
560 StringBuilder sb = new StringBuilder ();
561 AttributeTargets targets = attr.GetAttributeUsage ().ValidOn;
563 if ((targets & AttributeTargets.Assembly) != 0)
564 sb.Append ("'assembly' ");
566 if ((targets & AttributeTargets.Class) != 0)
567 sb.Append ("'class' ");
569 if ((targets & AttributeTargets.Constructor) != 0)
570 sb.Append ("'constructor' ");
572 if ((targets & AttributeTargets.Delegate) != 0)
573 sb.Append ("'delegate' ");
575 if ((targets & AttributeTargets.Enum) != 0)
576 sb.Append ("'enum' ");
578 if ((targets & AttributeTargets.Event) != 0)
579 sb.Append ("'event' ");
581 if ((targets & AttributeTargets.Field) != 0)
582 sb.Append ("'field' ");
584 if ((targets & AttributeTargets.Interface) != 0)
585 sb.Append ("'interface' ");
587 if ((targets & AttributeTargets.Method) != 0)
588 sb.Append ("'method' ");
590 if ((targets & AttributeTargets.Module) != 0)
591 sb.Append ("'module' ");
593 if ((targets & AttributeTargets.Parameter) != 0)
594 sb.Append ("'parameter' ");
596 if ((targets & AttributeTargets.Property) != 0)
597 sb.Append ("'property' ");
599 if ((targets & AttributeTargets.ReturnValue) != 0)
600 sb.Append ("'return' ");
602 if ((targets & AttributeTargets.Struct) != 0)
603 sb.Append ("'struct' ");
605 return sb.ToString ();
609 public static void Error_AttributeNotValidForElement (Attribute a, Location loc)
612 592, loc, "Attribute '" + a.Name +
613 "' is not valid on this declaration type. " +
614 "It is valid on " + GetValidTargets (a) + "declarations only.");
619 /// Returns AttributeUsage attribute for this type
621 public AttributeUsageAttribute GetAttributeUsage ()
623 AttributeUsageAttribute ua = usage_attr_cache [Type] as AttributeUsageAttribute;
627 Class attr_class = TypeManager.LookupClass (Type);
629 if (attr_class == null) {
630 object[] usage_attr = Type.GetCustomAttributes (TypeManager.attribute_usage_type, true);
631 ua = (AttributeUsageAttribute)usage_attr [0];
632 usage_attr_cache.Add (Type, ua);
636 return attr_class.AttributeUsage;
641 // This pulls the condition name out of a Conditional attribute
643 public string Conditional_GetConditionName ()
646 // So we have a Conditional, pull the data out.
648 if (Arguments == null || Arguments [0] == null){
649 Error_AttributeConstructorMismatch ();
653 ArrayList pos_args = (ArrayList) Arguments [0];
654 if (pos_args.Count != 1){
655 Error_AttributeConstructorMismatch ();
659 Argument arg = (Argument) pos_args [0];
660 if (!(arg.Expr is StringConstant)){
661 Error_AttributeConstructorMismatch ();
665 return ((StringConstant) arg.Expr).Value;
669 // This pulls the obsolete message and error flag out of an Obsolete attribute
671 public string Obsolete_GetObsoleteMessage (out bool is_error)
675 // So we have an Obsolete, pull the data out.
677 if (Arguments == null || Arguments [0] == null)
680 ArrayList pos_args = (ArrayList) Arguments [0];
681 if (pos_args.Count == 0)
683 else if (pos_args.Count > 2){
684 Error_AttributeConstructorMismatch ();
688 Argument arg = (Argument) pos_args [0];
689 if (!(arg.Expr is StringConstant)){
690 Error_AttributeConstructorMismatch ();
694 if (pos_args.Count == 2){
695 Argument arg2 = (Argument) pos_args [1];
696 if (!(arg2.Expr is BoolConstant)){
697 Error_AttributeConstructorMismatch ();
700 is_error = ((BoolConstant) arg2.Expr).Value;
703 return ((StringConstant) arg.Expr).Value;
706 public string IndexerName_GetIndexerName (EmitContext ec)
708 if (Arguments == null || Arguments [0] == null){
709 Error_AttributeConstructorMismatch ();
712 ArrayList pos_args = (ArrayList) Arguments [0];
713 if (pos_args.Count != 1) {
714 Error_AttributeConstructorMismatch ();
718 Argument arg = (Argument) pos_args [0];
719 if (!arg.Resolve (ec, Location))
722 StringConstant sc = arg.Expr as StringConstant;
724 Error_AttributeConstructorMismatch ();
732 /// Returns value of CLSCompliantAttribute contructor parameter but because the method can be called
733 /// before ApplyAttribute. We need to resolve the arguments.
734 /// This situation occurs when class deps is differs from Emit order.
736 public bool GetClsCompliantAttributeValue (DeclSpace ds)
738 if (pos_values == null) {
739 EmitContext ec = new EmitContext (ds, ds, Location, null, null, 0, false);
741 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
742 // But because a lot of attribute class code must be rewritten will be better to wait...
746 // Some error occurred
747 if (pos_values [0] == null)
750 return (bool)pos_values [0];
753 public object GetPositionalValue (int i)
755 return (pos_values == null) ? null : pos_values[i];
758 object GetFieldValue (string name)
761 if (field_info_arr == null)
764 foreach (FieldInfo fi in field_info_arr) {
766 return field_values_arr [i];
772 public UnmanagedMarshal GetMarshal ()
774 object o = GetFieldValue ("ArraySubType");
775 UnmanagedType array_sub_type = o == null ? UnmanagedType.I4 : (UnmanagedType) o;
777 switch (UnmanagedType) {
778 case UnmanagedType.CustomMarshaler:
779 MethodInfo define_custom = typeof (UnmanagedMarshal).GetMethod ("DefineCustom",
780 BindingFlags.Static | BindingFlags.Public);
781 if (define_custom == null)
784 object [] args = new object [4];
785 args [0] = GetFieldValue ("MarshalTypeRef");
786 args [1] = GetFieldValue ("MarshalCookie");
787 args [2] = GetFieldValue ("MarshalType");
788 args [3] = Guid.Empty;
789 return (UnmanagedMarshal) define_custom.Invoke (null, args);
791 case UnmanagedType.LPArray:
792 return UnmanagedMarshal.DefineLPArray (array_sub_type);
794 case UnmanagedType.SafeArray:
795 return UnmanagedMarshal.DefineSafeArray (array_sub_type);
797 case UnmanagedType.ByValArray:
798 return UnmanagedMarshal.DefineByValArray ((int) GetFieldValue ("SizeConst"));
800 case UnmanagedType.ByValTStr:
801 return UnmanagedMarshal.DefineByValTStr ((int) GetFieldValue ("SizeConst"));
804 return UnmanagedMarshal.DefineUnmanagedMarshal (UnmanagedType);
808 public bool IsInternalCall
810 get { return ImplOptions == MethodImplOptions.InternalCall; }
813 protected virtual bool CanIgnoreInvalidAttribute (Attributable ias)
819 /// Emit attribute for Attributable symbol
821 public void Emit (EmitContext ec, Attributable ias, ListDictionary emitted_attr)
823 CustomAttributeBuilder cb = Resolve (ec);
827 AttributeUsageAttribute usage_attr = GetAttributeUsage ();
828 if ((usage_attr.ValidOn & ias.AttributeTargets) == 0) {
829 // The parser applies toplevel attributes both to the assembly and
830 // to a top-level class, if any. So, be silent about them.
831 if (! CanIgnoreInvalidAttribute (ias))
832 Error_AttributeNotValidForElement (this, Location);
836 ias.ApplyAttributeBuilder (this, cb);
838 // Because default target is null (we save some space). We need to transform it here
839 // for distinction between "default" and "doesn't exist"
840 string target = Target == null ? "default" : Target;
841 string emitted = emitted_attr [Type] as string;
842 if (emitted == target && !usage_attr.AllowMultiple) {
843 Report.Error (579, Location, "Duplicate '" + Name + "' attribute");
846 emitted_attr [Type] = target;
848 // Here we are testing attribute arguments for array usage (error 3016)
849 if (ias.IsClsCompliaceRequired (ec.DeclSpace)) {
850 if (Arguments == null)
853 ArrayList pos_args = (ArrayList) Arguments [0];
854 if (pos_args != null) {
855 foreach (Argument arg in pos_args) {
856 // Type is undefined (was error 246)
857 if (arg.Type == null)
860 if (arg.Type.IsArray) {
861 Report.Error_T (3016, Location);
867 if (Arguments.Count < 2)
870 ArrayList named_args = (ArrayList) Arguments [1];
871 foreach (DictionaryEntry de in named_args) {
872 Argument arg = (Argument) de.Value;
874 // Type is undefined (was error 246)
875 if (arg.Type == null)
878 if (arg.Type.IsArray) {
879 Report.Error_T (3016, Location);
886 public object GetValue (EmitContext ec, Constant c, Type target)
888 if (Convert.ImplicitConversionExists (ec, c, target))
889 return c.GetValue ();
891 Convert.Error_CannotImplicitConversion (Location, c.Type, target);
895 public MethodBuilder DefinePInvokeMethod (EmitContext ec, TypeBuilder builder, string name,
896 MethodAttributes flags, Type ret_type, Type [] param_types)
899 // We extract from the attribute the information we need
902 if (Arguments == null) {
903 Console.WriteLine ("Internal error : this is not supposed to happen !");
907 ResolveType (ec, true);
911 ArrayList named_args = new ArrayList ();
913 ArrayList pos_args = (ArrayList) Arguments [0];
914 if (Arguments.Count > 1)
915 named_args = (ArrayList) Arguments [1];
918 string dll_name = null;
920 Argument tmp = (Argument) pos_args [0];
922 if (!tmp.Resolve (ec, Location))
925 if (tmp.Expr is Constant)
926 dll_name = (string) ((Constant) tmp.Expr).GetValue ();
928 Error_AttributeArgumentNotValid (Location);
932 // Now we process the named arguments
933 CallingConvention cc = CallingConvention.Winapi;
934 CharSet charset = CharSet.Ansi;
935 bool preserve_sig = true;
937 bool exact_spelling = false;
939 bool set_last_err = false;
940 string entry_point = null;
942 for (int i = 0; i < named_args.Count; i++) {
944 DictionaryEntry de = (DictionaryEntry) named_args [i];
946 string member_name = (string) de.Key;
947 Argument a = (Argument) de.Value;
949 if (!a.Resolve (ec, Location))
952 Expression member = Expression.MemberLookup (
953 ec, Type, member_name,
954 MemberTypes.Field | MemberTypes.Property,
955 BindingFlags.Public | BindingFlags.Instance,
958 if (member == null || !(member is FieldExpr)) {
959 Error_InvalidNamedArgument (member_name);
963 if (member is FieldExpr) {
964 FieldExpr fe = (FieldExpr) member;
965 FieldInfo fi = fe.FieldInfo;
968 Error_InvalidNamedArgument (member_name);
972 if (a.Expr is Constant) {
973 Constant c = (Constant) a.Expr;
976 if (member_name == "CallingConvention"){
977 object val = GetValue (ec, c, typeof (CallingConvention));
980 cc = (CallingConvention) val;
981 } else if (member_name == "CharSet"){
982 charset = (CharSet) c.GetValue ();
983 } else if (member_name == "EntryPoint")
984 entry_point = (string) c.GetValue ();
985 else if (member_name == "SetLastError")
986 set_last_err = (bool) c.GetValue ();
988 else if (member_name == "ExactSpelling")
989 exact_spelling = (bool) c.GetValue ();
991 else if (member_name == "PreserveSig")
992 preserve_sig = (bool) c.GetValue ();
993 } catch (InvalidCastException){
994 Error_InvalidNamedArgument (member_name);
995 Error_AttributeArgumentNotValid (Location);
998 Error_AttributeArgumentNotValid (Location);
1005 if (entry_point == null)
1008 charset = (CharSet)((int)charset | 0x40);
1010 MethodBuilder mb = builder.DefinePInvokeMethod (
1011 name, dll_name, entry_point, flags | MethodAttributes.HideBySig,
1012 CallingConventions.Standard,
1019 mb.SetImplementationFlags (MethodImplAttributes.PreserveSig);
1024 private Expression GetValue ()
1026 if ((Arguments == null) || (Arguments.Count < 1))
1028 ArrayList al = (ArrayList) Arguments [0];
1029 if ((al == null) || (al.Count < 1))
1031 Argument arg = (Argument) al [0];
1032 if ((arg == null) || (arg.Expr == null))
1037 public string GetString ()
1039 Expression e = GetValue ();
1040 if (e is StringLiteral)
1041 return (e as StringLiteral).Value;
1045 public bool GetBoolean ()
1047 Expression e = GetValue ();
1048 if (e is BoolLiteral)
1049 return (e as BoolLiteral).Value;
1056 /// For global attributes (assembly, module) we need special handling.
1057 /// Attributes can be located in the several files
1059 public class GlobalAttribute: Attribute
1061 public readonly NamespaceEntry ns;
1063 public GlobalAttribute (TypeContainer container, string target, string name, ArrayList args, Location loc):
1064 base (target, name, args, loc)
1066 ns = container.NamespaceEntry;
1069 protected override Type CheckAttributeType (EmitContext ec, bool complain)
1071 NamespaceEntry old = ec.DeclSpace.NamespaceEntry;
1072 if (old == null || old.NS == null || old.NS == Namespace.Root)
1073 ec.DeclSpace.NamespaceEntry = ns;
1074 return base.CheckAttributeType (ec, complain);
1077 protected override bool CanIgnoreInvalidAttribute (Attributable ias)
1079 // Ignore error if this attribute is shared between the Assembly
1080 // and a top-level class. The parser couldn't figure out which entity
1081 // this attribute belongs to. If this attribute is erroneous, it should
1082 // be caught when it is processed by the top-level class.
1084 return (Target == null && ias is CommonAssemblyModulClass);
1088 public class Attributes {
1089 public ArrayList Attrs;
1091 public Attributes (Attribute a)
1093 Attrs = new ArrayList ();
1097 public Attributes (ArrayList attrs)
1102 public void AddAttributes (ArrayList attrs)
1104 Attrs.AddRange (attrs);
1108 /// Checks whether attribute target is valid for the current element
1110 public void CheckTargets (string[] possible_targets)
1112 foreach (Attribute a in Attrs) {
1113 if (a.Target == null)
1116 if (((IList) possible_targets).Contains (a.Target))
1119 StringBuilder sb = new StringBuilder ();
1120 foreach (string s in possible_targets) {
1124 sb.Remove (sb.Length - 2, 2);
1125 Report.Error_T (657, a.Location, a.Target, sb.ToString ());
1129 private Attribute Search (Type t, EmitContext ec, bool complain)
1131 foreach (Attribute a in Attrs) {
1132 if (a.ResolveType (ec, false) == t)
1138 public Attribute Search (Type t, EmitContext ec)
1140 return Search (t, ec, true);
1143 public void Emit (EmitContext ec, Attributable ias)
1145 ListDictionary ld = new ListDictionary ();
1147 foreach (Attribute a in Attrs)
1148 a.Emit (ec, ias, ld);
1151 public bool Contains (Type t, EmitContext ec)
1153 return Search (t, ec) != null;
1156 public Attribute GetClsCompliantAttribute (EmitContext ec)
1158 return Search (TypeManager.cls_compliant_attribute_type, ec, false);
1162 /// Pulls the IndexerName attribute from an Indexer if it exists.
1164 public string ScanForIndexerName (EmitContext ec)
1166 Attribute a = Search (TypeManager.indexer_name_type, ec);
1170 // Remove the attribute from the list
1171 //TODO: It is very close to hack and it can crash here
1174 return a.IndexerName_GetIndexerName (ec);
1180 /// Helper class for attribute verification routine.
1182 sealed class AttributeTester
1184 static PtrHashtable analyzed_types = new PtrHashtable ();
1186 private AttributeTester ()
1191 /// Returns true if parameters of two compared methods are CLS-Compliant.
1192 /// It tests differing only in ref or out, or in array rank.
1194 public static bool AreOverloadedMethodParamsClsCompliant (Type[] types_a, Type[] types_b)
1196 if (types_a == null || types_b == null)
1199 if (types_a.Length != types_b.Length)
1202 for (int i = 0; i < types_b.Length; ++i) {
1203 Type aType = types_a [i];
1204 Type bType = types_b [i];
1206 if (aType.IsArray && bType.IsArray && aType.GetArrayRank () != bType.GetArrayRank () && aType.GetElementType () == bType.GetElementType ()) {
1210 Type aBaseType = aType;
1211 bool is_either_ref_or_out = false;
1213 if (aType.IsByRef || aType.IsPointer) {
1214 aBaseType = aType.GetElementType ();
1215 is_either_ref_or_out = true;
1218 Type bBaseType = bType;
1219 if (bType.IsByRef || bType.IsPointer)
1221 bBaseType = bType.GetElementType ();
1222 is_either_ref_or_out = !is_either_ref_or_out;
1225 if (aBaseType != bBaseType)
1228 if (is_either_ref_or_out)
1235 /// Goes through all parameters and test if they are CLS-Compliant.
1237 public static bool AreParametersCompliant (Parameter[] fixedParameters, Location loc)
1239 if (fixedParameters == null)
1242 foreach (Parameter arg in fixedParameters) {
1243 if (!AttributeTester.IsClsCompliant (arg.ParameterType)) {
1244 Report.Error_T (3001, loc, arg.GetSignatureForError ());
1253 /// This method tests the CLS compliance of external types. It doesn't test type visibility.
1255 public static bool IsClsCompliant (Type type)
1260 object type_compliance = analyzed_types[type];
1261 if (type_compliance != null)
1262 return type_compliance == TRUE;
1264 if (type.IsPointer) {
1265 analyzed_types.Add (type, null);
1270 if (type.IsArray || type.IsByRef) {
1271 result = IsClsCompliant (TypeManager.GetElementType (type));
1273 result = AnalyzeTypeCompliance (type);
1275 analyzed_types.Add (type, result ? TRUE : FALSE);
1279 static object TRUE = new object ();
1280 static object FALSE = new object ();
1283 /// Non-hierarchical CLS Compliance analyzer
1285 public static bool IsComplianceRequired (MemberInfo mi, DeclSpace ds)
1287 DeclSpace temp_ds = TypeManager.LookupDeclSpace (mi.DeclaringType);
1289 // Type is external, we can get attribute directly
1290 if (temp_ds == null) {
1291 object[] cls_attribute = mi.GetCustomAttributes (TypeManager.cls_compliant_attribute_type, false);
1292 return (cls_attribute.Length == 1 && ((CLSCompliantAttribute)cls_attribute[0]).IsCompliant);
1296 // Interface doesn't store full name
1297 if (temp_ds is Interface)
1300 tmp_name = String.Concat (temp_ds.Name, ".", mi.Name);
1302 MemberCore mc = temp_ds.GetDefinition (tmp_name) as MemberCore;
1303 return mc.IsClsCompliaceRequired (ds);
1306 public static void VerifyModulesClsCompliance ()
1308 Module[] modules = TypeManager.Modules;
1309 if (modules == null)
1312 // The first module is generated assembly
1313 for (int i = 1; i < modules.Length; ++i) {
1314 Module module = modules [i];
1315 if (!IsClsCompliant (module)) {
1316 Report.Error_T (3013, module.Name);
1322 static bool IsClsCompliant (ICustomAttributeProvider attribute_provider)
1324 object[] CompliantAttribute = attribute_provider.GetCustomAttributes (TypeManager.cls_compliant_attribute_type, false);
1325 if (CompliantAttribute.Length == 0)
1328 return ((CLSCompliantAttribute)CompliantAttribute[0]).IsCompliant;
1331 static bool AnalyzeTypeCompliance (Type type)
1333 DeclSpace ds = TypeManager.LookupDeclSpace (type);
1335 return ds.IsClsCompliaceRequired (ds.Parent);
1338 if (type.IsGenericParameter)
1341 object[] CompliantAttribute = type.GetCustomAttributes (TypeManager.cls_compliant_attribute_type, false);
1342 if (CompliantAttribute.Length == 0)
1343 return IsClsCompliant (type.Assembly);
1345 return ((CLSCompliantAttribute)CompliantAttribute[0]).IsCompliant;