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);
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 (member is PropertyExpr) {
365 PropertyExpr pe = (PropertyExpr) member;
366 PropertyInfo pi = pe.PropertyInfo;
369 Error_InvalidNamedArgument (member_name);
376 if (e.Type != pi.PropertyType){
377 c = Const.ChangeType (Location, (Constant) e, pi.PropertyType);
383 object o = c.GetValue ();
386 if (usage_attribute != null) {
387 if (member_name == "AllowMultiple")
388 usage_attribute.AllowMultiple = (bool) o;
389 if (member_name == "Inherited")
390 usage_attribute.Inherited = (bool) o;
393 } else if (e is TypeOf) {
394 prop_values.Add (((TypeOf) e).TypeArg);
395 } else if (e is ArrayCreation) {
396 prop_values.Add (((ArrayCreation) e).EncodeAsAttribute());
398 Error_AttributeArgumentNotValid (Location);
404 } else if (member is FieldExpr) {
405 FieldExpr fe = (FieldExpr) member;
406 FieldInfo fi = fe.FieldInfo;
409 Error_InvalidNamedArgument (member_name);
414 // Handle charset here, and set the TypeAttributes
417 Constant c = (Constant) e;;
419 if (c.Type != fi.FieldType){
420 c = Const.ChangeType (Location, (Constant) e, fi.FieldType);
425 object value = c.GetValue ();
426 field_values.Add (value);
427 } else if (e is TypeOf) {
428 field_values.Add (((TypeOf) e).TypeArg);
430 Error_AttributeArgumentNotValid (Location);
434 field_infos.Add (fi);
438 Expression mg = Expression.MemberLookup (
439 ec, Type, ".ctor", MemberTypes.Constructor,
440 BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly,
444 Error_AttributeConstructorMismatch ();
448 MethodBase constructor = Invocation.OverloadResolve (
449 ec, (MethodGroupExpr) mg, pos_args, Location);
451 if (constructor == null) {
452 Error_AttributeConstructorMismatch ();
457 // Now we perform some checks on the positional args as they
458 // cannot be null for a constructor which expects a parameter
462 ParameterData pd = Invocation.GetParameterData (constructor);
464 int group_in_params_array = Int32.MaxValue;
466 if (pc > 0 && pd.ParameterModifier (pc-1) == Parameter.Modifier.PARAMS)
467 group_in_params_array = pc-1;
469 for (int j = 0; j < pos_arg_count; ++j) {
470 Argument a = (Argument) pos_args [j];
472 if (a.Expr is NullLiteral && pd.ParameterType (j) == TypeManager.object_type) {
473 Error_AttributeArgumentNotValid (Location);
477 if (j < group_in_params_array)
480 if (j == group_in_params_array){
481 object v = pos_values [j];
482 int count = pos_arg_count - j;
484 object [] array = new object [count];
485 pos_values [j] = array;
488 object [] array = (object []) pos_values [group_in_params_array];
490 array [j - group_in_params_array] = pos_values [j];
495 // Adjust the size of the pos_values if it had params
497 if (group_in_params_array != Int32.MaxValue){
498 int argc = group_in_params_array+1;
499 object [] new_pos_values = new object [argc];
501 for (int p = 0; p < argc; p++)
502 new_pos_values [p] = pos_values [p];
503 pos_values = new_pos_values;
507 if (named_args.Count > 0) {
508 prop_info_arr = new PropertyInfo [prop_infos.Count];
509 field_info_arr = new FieldInfo [field_infos.Count];
510 field_values_arr = new object [field_values.Count];
511 prop_values_arr = new object [prop_values.Count];
513 field_infos.CopyTo (field_info_arr, 0);
514 field_values.CopyTo (field_values_arr, 0);
516 prop_values.CopyTo (prop_values_arr, 0);
517 prop_infos.CopyTo (prop_info_arr, 0);
519 cb = new CustomAttributeBuilder (
520 (ConstructorInfo) constructor, pos_values,
521 prop_info_arr, prop_values_arr,
522 field_info_arr, field_values_arr);
525 cb = new CustomAttributeBuilder (
526 (ConstructorInfo) constructor, pos_values);
527 } catch (NullReferenceException) {
529 // Don't know what to do here
532 -101, Location, "NullReferenceException while trying to create attribute." +
533 "Something's wrong!");
534 } catch (Exception e) {
537 // using System.ComponentModel;
538 // [DefaultValue (CollectionChangeAction.Add)]
539 // class X { static void Main () {} }
543 "The compiler can not encode this attribute in .NET due to\n" +
544 "\ta bug in the .NET runtime. Try the Mono runtime.\nThe error was: " + e.Message);
551 /// Get a string containing a list of valid targets for the attribute 'attr'
553 static string GetValidTargets (Attribute attr)
555 StringBuilder sb = new StringBuilder ();
556 AttributeTargets targets = attr.GetAttributeUsage ().ValidOn;
558 if ((targets & AttributeTargets.Assembly) != 0)
559 sb.Append ("'assembly' ");
561 if ((targets & AttributeTargets.Class) != 0)
562 sb.Append ("'class' ");
564 if ((targets & AttributeTargets.Constructor) != 0)
565 sb.Append ("'constructor' ");
567 if ((targets & AttributeTargets.Delegate) != 0)
568 sb.Append ("'delegate' ");
570 if ((targets & AttributeTargets.Enum) != 0)
571 sb.Append ("'enum' ");
573 if ((targets & AttributeTargets.Event) != 0)
574 sb.Append ("'event' ");
576 if ((targets & AttributeTargets.Field) != 0)
577 sb.Append ("'field' ");
579 if ((targets & AttributeTargets.Interface) != 0)
580 sb.Append ("'interface' ");
582 if ((targets & AttributeTargets.Method) != 0)
583 sb.Append ("'method' ");
585 if ((targets & AttributeTargets.Module) != 0)
586 sb.Append ("'module' ");
588 if ((targets & AttributeTargets.Parameter) != 0)
589 sb.Append ("'parameter' ");
591 if ((targets & AttributeTargets.Property) != 0)
592 sb.Append ("'property' ");
594 if ((targets & AttributeTargets.ReturnValue) != 0)
595 sb.Append ("'return' ");
597 if ((targets & AttributeTargets.Struct) != 0)
598 sb.Append ("'struct' ");
600 return sb.ToString ();
604 public static void Error_AttributeNotValidForElement (Attribute a, Location loc)
607 592, loc, "Attribute '" + a.Name +
608 "' is not valid on this declaration type. " +
609 "It is valid on " + GetValidTargets (a) + "declarations only.");
614 /// Returns AttributeUsage attribute for this type
616 public AttributeUsageAttribute GetAttributeUsage ()
618 AttributeUsageAttribute ua = usage_attr_cache [Type] as AttributeUsageAttribute;
622 Class attr_class = TypeManager.LookupClass (Type);
624 if (attr_class == null) {
625 object[] usage_attr = Type.GetCustomAttributes (TypeManager.attribute_usage_type, true);
626 ua = (AttributeUsageAttribute)usage_attr [0];
627 usage_attr_cache.Add (Type, ua);
631 return attr_class.AttributeUsage;
636 // This pulls the condition name out of a Conditional attribute
638 public string Conditional_GetConditionName ()
641 // So we have a Conditional, pull the data out.
643 if (Arguments == null || Arguments [0] == null){
644 Error_AttributeConstructorMismatch ();
648 ArrayList pos_args = (ArrayList) Arguments [0];
649 if (pos_args.Count != 1){
650 Error_AttributeConstructorMismatch ();
654 Argument arg = (Argument) pos_args [0];
655 if (!(arg.Expr is StringConstant)){
656 Error_AttributeConstructorMismatch ();
660 return ((StringConstant) arg.Expr).Value;
664 // This pulls the obsolete message and error flag out of an Obsolete attribute
666 public string Obsolete_GetObsoleteMessage (out bool is_error)
670 // So we have an Obsolete, pull the data out.
672 if (Arguments == null || Arguments [0] == null)
675 ArrayList pos_args = (ArrayList) Arguments [0];
676 if (pos_args.Count == 0)
678 else if (pos_args.Count > 2){
679 Error_AttributeConstructorMismatch ();
683 Argument arg = (Argument) pos_args [0];
684 if (!(arg.Expr is StringConstant)){
685 Error_AttributeConstructorMismatch ();
689 if (pos_args.Count == 2){
690 Argument arg2 = (Argument) pos_args [1];
691 if (!(arg2.Expr is BoolConstant)){
692 Error_AttributeConstructorMismatch ();
695 is_error = ((BoolConstant) arg2.Expr).Value;
698 return ((StringConstant) arg.Expr).Value;
701 public string IndexerName_GetIndexerName (EmitContext ec)
703 if (Arguments == null || Arguments [0] == null){
704 Error_AttributeConstructorMismatch ();
707 ArrayList pos_args = (ArrayList) Arguments [0];
708 if (pos_args.Count != 1) {
709 Error_AttributeConstructorMismatch ();
713 Argument arg = (Argument) pos_args [0];
714 if (!arg.Resolve (ec, Location))
717 StringConstant sc = arg.Expr as StringConstant;
719 Error_AttributeConstructorMismatch ();
727 /// Returns value of CLSCompliantAttribute contructor parameter but because the method can be called
728 /// before ApplyAttribute. We need to resolve the arguments.
729 /// This situation occurs when class deps is differs from Emit order.
731 public bool GetClsCompliantAttributeValue (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 [0] == null)
745 return (bool)pos_values [0];
748 public object GetPositionalValue (int i)
750 return (pos_values == null) ? null : pos_values[i];
753 object GetFieldValue (string name)
756 if (field_info_arr == null)
759 foreach (FieldInfo fi in field_info_arr) {
761 return field_values_arr [i];
767 public UnmanagedMarshal GetMarshal ()
769 object o = GetFieldValue ("ArraySubType");
770 UnmanagedType array_sub_type = o == null ? UnmanagedType.I4 : (UnmanagedType) o;
772 switch (UnmanagedType) {
773 case UnmanagedType.CustomMarshaler:
774 MethodInfo define_custom = typeof (UnmanagedMarshal).GetMethod ("DefineCustom",
775 BindingFlags.Static | BindingFlags.Public);
776 if (define_custom == null)
779 object [] args = new object [4];
780 args [0] = GetFieldValue ("MarshalTypeRef");
781 args [1] = GetFieldValue ("MarshalCookie");
782 args [2] = GetFieldValue ("MarshalType");
783 args [3] = Guid.Empty;
784 return (UnmanagedMarshal) define_custom.Invoke (null, args);
786 case UnmanagedType.LPArray:
787 return UnmanagedMarshal.DefineLPArray (array_sub_type);
789 case UnmanagedType.SafeArray:
790 return UnmanagedMarshal.DefineSafeArray (array_sub_type);
792 case UnmanagedType.ByValArray:
793 return UnmanagedMarshal.DefineByValArray ((int) GetFieldValue ("SizeConst"));
795 case UnmanagedType.ByValTStr:
796 return UnmanagedMarshal.DefineByValTStr ((int) GetFieldValue ("SizeConst"));
799 return UnmanagedMarshal.DefineUnmanagedMarshal (UnmanagedType);
803 public bool IsInternalCall
805 get { return ImplOptions == MethodImplOptions.InternalCall; }
809 /// Emit attribute for Attributable symbol
811 public void Emit (EmitContext ec, Attributable ias, ListDictionary emitted_attr)
813 CustomAttributeBuilder cb = Resolve (ec);
817 AttributeUsageAttribute usage_attr = GetAttributeUsage ();
818 if ((usage_attr.ValidOn & ias.AttributeTargets) == 0) {
819 Error_AttributeNotValidForElement (this, Location);
823 ias.ApplyAttributeBuilder (this, cb);
825 if (!usage_attr.AllowMultiple && emitted_attr.Contains (Target)) {
826 Report.Error (579, Location, "Duplicate '" + Name + "' attribute");
829 emitted_attr [Type] = Target;
831 // Here we are testing attribute arguments for array usage (error 3016)
832 if (ias.IsClsCompliaceRequired (ec.DeclSpace)) {
833 if (Arguments == null)
836 ArrayList pos_args = (ArrayList) Arguments [0];
837 if (pos_args != null) {
838 foreach (Argument arg in pos_args) {
839 // Type is undefined (was error 246)
840 if (arg.Type == null)
843 if (arg.Type.IsArray) {
844 Report.Error_T (3016, Location);
850 if (Arguments.Count < 2)
853 ArrayList named_args = (ArrayList) Arguments [1];
854 foreach (DictionaryEntry de in named_args) {
855 Argument arg = (Argument) de.Value;
857 // Type is undefined (was error 246)
858 if (arg.Type == null)
861 if (arg.Type.IsArray) {
862 Report.Error_T (3016, Location);
869 public object GetValue (EmitContext ec, Constant c, Type target)
871 if (Convert.ImplicitConversionExists (ec, c, target))
872 return c.GetValue ();
874 Convert.Error_CannotImplicitConversion (Location, c.Type, target);
878 public MethodBuilder DefinePInvokeMethod (EmitContext ec, TypeBuilder builder, string name,
879 MethodAttributes flags, Type ret_type, Type [] param_types)
882 // We extract from the attribute the information we need
885 if (Arguments == null) {
886 Console.WriteLine ("Internal error : this is not supposed to happen !");
890 ResolveType (ec, true);
894 ArrayList named_args = new ArrayList ();
896 ArrayList pos_args = (ArrayList) Arguments [0];
897 if (Arguments.Count > 1)
898 named_args = (ArrayList) Arguments [1];
901 string dll_name = null;
903 Argument tmp = (Argument) pos_args [0];
905 if (!tmp.Resolve (ec, Location))
908 if (tmp.Expr is Constant)
909 dll_name = (string) ((Constant) tmp.Expr).GetValue ();
911 Error_AttributeArgumentNotValid (Location);
915 // Now we process the named arguments
916 CallingConvention cc = CallingConvention.Winapi;
917 CharSet charset = CharSet.Ansi;
918 bool preserve_sig = true;
920 bool exact_spelling = false;
922 bool set_last_err = false;
923 string entry_point = null;
925 for (int i = 0; i < named_args.Count; i++) {
927 DictionaryEntry de = (DictionaryEntry) named_args [i];
929 string member_name = (string) de.Key;
930 Argument a = (Argument) de.Value;
932 if (!a.Resolve (ec, Location))
935 Expression member = Expression.MemberLookup (
936 ec, Type, member_name,
937 MemberTypes.Field | MemberTypes.Property,
938 BindingFlags.Public | BindingFlags.Instance,
941 if (member == null || !(member is FieldExpr)) {
942 Error_InvalidNamedArgument (member_name);
946 if (member is FieldExpr) {
947 FieldExpr fe = (FieldExpr) member;
948 FieldInfo fi = fe.FieldInfo;
951 Error_InvalidNamedArgument (member_name);
955 if (a.Expr is Constant) {
956 Constant c = (Constant) a.Expr;
959 if (member_name == "CallingConvention"){
960 object val = GetValue (ec, c, typeof (CallingConvention));
963 cc = (CallingConvention) val;
964 } else if (member_name == "CharSet"){
965 charset = (CharSet) c.GetValue ();
966 } else if (member_name == "EntryPoint")
967 entry_point = (string) c.GetValue ();
968 else if (member_name == "SetLastError")
969 set_last_err = (bool) c.GetValue ();
971 else if (member_name == "ExactSpelling")
972 exact_spelling = (bool) c.GetValue ();
974 else if (member_name == "PreserveSig")
975 preserve_sig = (bool) c.GetValue ();
976 } catch (InvalidCastException){
977 Error_InvalidNamedArgument (member_name);
978 Error_AttributeArgumentNotValid (Location);
981 Error_AttributeArgumentNotValid (Location);
988 if (entry_point == null)
991 charset = (CharSet)((int)charset | 0x40);
993 MethodBuilder mb = builder.DefinePInvokeMethod (
994 name, dll_name, entry_point, flags | MethodAttributes.HideBySig,
995 CallingConventions.Standard,
1002 mb.SetImplementationFlags (MethodImplAttributes.PreserveSig);
1007 private Expression GetValue ()
1009 if ((Arguments == null) || (Arguments.Count < 1))
1011 ArrayList al = (ArrayList) Arguments [0];
1012 if ((al == null) || (al.Count < 1))
1014 Argument arg = (Argument) al [0];
1015 if ((arg == null) || (arg.Expr == null))
1020 public string GetString ()
1022 Expression e = GetValue ();
1023 if (e is StringLiteral)
1024 return (e as StringLiteral).Value;
1028 public bool GetBoolean ()
1030 Expression e = GetValue ();
1031 if (e is BoolLiteral)
1032 return (e as BoolLiteral).Value;
1039 /// For global attributes (assembly, module) we need special handling.
1040 /// Attributes can be located in the several files
1042 public class GlobalAttribute: Attribute
1044 public readonly NamespaceEntry ns;
1046 public GlobalAttribute (TypeContainer container, string target, string name, ArrayList args, Location loc):
1047 base (target, name, args, loc)
1049 ns = container.NamespaceEntry;
1052 protected override Type CheckAttributeType (EmitContext ec, bool complain)
1054 NamespaceEntry old = ec.DeclSpace.NamespaceEntry;
1055 if (old == null || old.NS == null || old.NS == Namespace.Root)
1056 ec.DeclSpace.NamespaceEntry = ns;
1057 return base.CheckAttributeType (ec, complain);
1061 public class Attributes {
1062 public ArrayList Attrs;
1064 public Attributes (Attribute a)
1066 Attrs = new ArrayList ();
1070 public Attributes (ArrayList attrs)
1075 public void AddAttributes (ArrayList attrs)
1077 Attrs.AddRange (attrs);
1081 /// Checks whether attribute target is valid for the current element
1083 public void CheckTargets (string[] possible_targets)
1085 foreach (Attribute a in Attrs) {
1086 if (a.Target == null) {
1087 a.Target = possible_targets [0];
1091 if (((IList) possible_targets).Contains (a.Target))
1094 StringBuilder sb = new StringBuilder ();
1095 foreach (string s in possible_targets) {
1099 sb.Remove (sb.Length - 2, 2);
1100 Report.Error_T (657, a.Location, a.Target, sb.ToString ());
1104 private Attribute Search (Type t, EmitContext ec, bool complain)
1106 foreach (Attribute a in Attrs) {
1107 if (a.ResolveType (ec, false) == t)
1113 public Attribute Search (Type t, EmitContext ec)
1115 return Search (t, ec, true);
1118 public void Emit (EmitContext ec, Attributable ias)
1120 ListDictionary ld = new ListDictionary ();
1122 foreach (Attribute a in Attrs)
1123 a.Emit (ec, ias, ld);
1126 public bool Contains (Type t, EmitContext ec)
1128 return Search (t, ec) != null;
1131 public Attribute GetClsCompliantAttribute (EmitContext ec)
1133 return Search (TypeManager.cls_compliant_attribute_type, ec, false);
1137 /// Pulls the IndexerName attribute from an Indexer if it exists.
1139 public string ScanForIndexerName (EmitContext ec)
1141 Attribute a = Search (TypeManager.indexer_name_type, ec);
1145 // Remove the attribute from the list
1146 //TODO: It is very close to hack and it can crash here
1149 return a.IndexerName_GetIndexerName (ec);
1155 /// Helper class for attribute verification routine.
1157 sealed class AttributeTester
1159 static PtrHashtable analyzed_types = new PtrHashtable ();
1161 private AttributeTester ()
1166 /// Returns true if parameters of two compared methods are CLS-Compliant.
1167 /// It tests differing only in ref or out, or in array rank.
1169 public static bool AreOverloadedMethodParamsClsCompliant (Type[] types_a, Type[] types_b)
1171 if (types_a == null || types_b == null)
1174 if (types_a.Length != types_b.Length)
1177 for (int i = 0; i < types_b.Length; ++i) {
1178 Type aType = types_a [i];
1179 Type bType = types_b [i];
1181 if (aType.IsArray && bType.IsArray && aType.GetArrayRank () != bType.GetArrayRank () && aType.GetElementType () == bType.GetElementType ()) {
1185 Type aBaseType = aType;
1186 bool is_either_ref_or_out = false;
1188 if (aType.IsByRef || aType.IsPointer) {
1189 aBaseType = aType.GetElementType ();
1190 is_either_ref_or_out = true;
1193 Type bBaseType = bType;
1194 if (bType.IsByRef || bType.IsPointer)
1196 bBaseType = bType.GetElementType ();
1197 is_either_ref_or_out = !is_either_ref_or_out;
1200 if (aBaseType != bBaseType)
1203 if (is_either_ref_or_out)
1210 /// Goes through all parameters and test if they are CLS-Compliant.
1212 public static bool AreParametersCompliant (Parameter[] fixedParameters, Location loc)
1214 if (fixedParameters == null)
1217 foreach (Parameter arg in fixedParameters) {
1218 if (!AttributeTester.IsClsCompliant (arg.ParameterType)) {
1219 Report.Error_T (3001, loc, arg.GetSignatureForError ());
1228 /// This method tests the CLS compliance of external types. It doesn't test type visibility.
1230 public static bool IsClsCompliant (Type type)
1235 object type_compliance = analyzed_types[type];
1236 if (type_compliance != null)
1237 return type_compliance == TRUE;
1239 if (type.IsPointer) {
1240 analyzed_types.Add (type, null);
1245 if (type.IsArray || type.IsByRef) {
1246 result = IsClsCompliant (TypeManager.GetElementType (type));
1248 result = AnalyzeTypeCompliance (type);
1250 analyzed_types.Add (type, result ? TRUE : FALSE);
1254 static object TRUE = new object ();
1255 static object FALSE = new object ();
1258 /// Non-hierarchical CLS Compliance analyzer
1260 public static bool IsComplianceRequired (MemberInfo mi, DeclSpace ds)
1262 DeclSpace temp_ds = TypeManager.LookupDeclSpace (mi.DeclaringType);
1264 // Type is external, we can get attribute directly
1265 if (temp_ds == null) {
1266 object[] cls_attribute = mi.GetCustomAttributes (TypeManager.cls_compliant_attribute_type, false);
1267 return (cls_attribute.Length == 1 && ((CLSCompliantAttribute)cls_attribute[0]).IsCompliant);
1271 // Interface doesn't store full name
1272 if (temp_ds is Interface)
1275 tmp_name = String.Concat (temp_ds.Name, ".", mi.Name);
1277 MemberCore mc = temp_ds.GetDefinition (tmp_name) as MemberCore;
1278 return mc.IsClsCompliaceRequired (ds);
1281 public static void VerifyModulesClsCompliance ()
1283 Module[] modules = TypeManager.Modules;
1284 if (modules == null)
1287 // The first module is generated assembly
1288 for (int i = 1; i < modules.Length; ++i) {
1289 Module module = modules [i];
1290 if (!IsClsCompliant (module)) {
1291 Report.Error_T (3013, module.Name);
1297 static bool IsClsCompliant (ICustomAttributeProvider attribute_provider)
1299 object[] CompliantAttribute = attribute_provider.GetCustomAttributes (TypeManager.cls_compliant_attribute_type, false);
1300 if (CompliantAttribute.Length == 0)
1303 return ((CLSCompliantAttribute)CompliantAttribute[0]).IsCompliant;
1306 static bool AnalyzeTypeCompliance (Type type)
1308 DeclSpace ds = TypeManager.LookupDeclSpace (type);
1310 return ds.IsClsCompliaceRequired (ds.Parent);
1313 object[] CompliantAttribute = type.GetCustomAttributes (TypeManager.cls_compliant_attribute_type, false);
1314 if (CompliantAttribute.Length == 0)
1315 return IsClsCompliant (type.Assembly);
1317 return ((CLSCompliantAttribute)CompliantAttribute[0]).IsCompliant;