2 // attribute.cs: Attribute Handler
4 // Author: Ravi Pratap (ravi@ximian.com)
5 // Marek Safar (marek.safar@seznam.cz)
7 // Licensed under the terms of the GNU GPL
9 // (C) 2001 Ximian, Inc (http://www.ximian.com)
14 using System.Diagnostics;
15 using System.Collections;
16 using System.Collections.Specialized;
17 using System.Reflection;
18 using System.Reflection.Emit;
19 using System.Runtime.InteropServices;
20 using System.Runtime.CompilerServices;
23 namespace Mono.CSharp {
26 /// Base class for objects that can have Attributes applied to them.
28 public abstract class Attributable {
30 /// Attributes for this type
32 Attributes attributes;
34 public Attributable(Attributes attrs)
37 if (attributes != null)
38 attributes.CheckTargets (ValidAttributeTargets);
41 public Attributes OptAttributes
48 if (attributes != null)
49 attributes.CheckTargets (ValidAttributeTargets);
54 /// Use member-specific procedure to apply attribute @a in @cb to the entity being built in @builder
56 public abstract void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb);
59 /// Returns combination of enabled AttributeTargets
61 public abstract AttributeTargets AttributeTargets { get; }
63 public abstract bool IsClsCompliaceRequired (DeclSpace ds);
66 /// Gets list of valid attribute targets for explicit target declaration.
67 /// The first array item is default target. Don't break this rule.
69 protected abstract string[] ValidAttributeTargets { get; }
72 public class Attribute {
74 public readonly string Name;
75 public readonly ArrayList Arguments;
77 public readonly Location Location;
81 // Is non-null if type is AttributeUsageAttribute
82 AttributeUsageAttribute usage_attribute;
84 public AttributeUsageAttribute UsageAttribute {
86 return usage_attribute;
90 MethodImplOptions ImplOptions;
91 UnmanagedType UnmanagedType;
92 CustomAttributeBuilder cb;
94 // non-null if named args present after Resolve () is called
95 PropertyInfo [] prop_info_arr;
96 FieldInfo [] field_info_arr;
97 object [] field_values_arr;
98 object [] prop_values_arr;
101 static PtrHashtable usage_attr_cache = new PtrHashtable ();
103 public Attribute (string target, string name, ArrayList args, Location loc)
111 void Error_InvalidNamedArgument (string name)
113 Report.Error (617, Location, "'" + name + "' is not a valid named attribute " +
114 "argument. Named attribute arguments must be fields which are not " +
115 "readonly, static or const, or properties with a set accessor which "+
119 static void Error_AttributeArgumentNotValid (Location loc)
121 Report.Error (182, loc,
122 "An attribute argument must be a constant expression, typeof " +
123 "expression or array creation expression");
126 void Error_AttributeConstructorMismatch ()
128 Report.Error (-6, Location,
129 "Could not find a constructor for this argument list.");
133 /// Tries to resolve the type of the attribute. Flags an error if it can't, and complain is true.
135 protected virtual Type CheckAttributeType (EmitContext ec, bool complain)
137 Type t1 = RootContext.LookupType (ec.DeclSpace, Name, true, Location);
139 // FIXME: Shouldn't do this for quoted attributes: [@A]
140 Type t2 = RootContext.LookupType (ec.DeclSpace, Name + "Attribute", true, Location);
142 String err0616 = null;
144 if (t1 != null && ! t1.IsSubclassOf (TypeManager.attribute_type)) {
146 err0616 = "'" + Name + "': is not an attribute class";
148 if (t2 != null && ! t2.IsSubclassOf (TypeManager.attribute_type)) {
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'");
165 if (err0616 != null) {
166 Report.Error (616, Location, err0616);
171 Report.Error (246, Location,
172 "Could not find attribute '" + Name
173 + "' (are you missing a using directive or an assembly reference ?)");
177 public Type ResolveType (EmitContext ec, bool complain)
180 Type = CheckAttributeType (ec, complain);
185 /// Validates the guid string
187 bool ValidateGuid (string guid)
193 Report.Error (647, Location, "Format of GUID is invalid: " + guid);
198 string GetFullMemberName (string member)
200 return Type.FullName + '.' + member;
204 // Given an expression, if the expression is a valid attribute-argument-expression
205 // returns an object that can be used to encode it, or null on failure.
207 public static bool GetAttributeArgumentExpression (Expression e, Location loc, out object result)
210 result = ((Constant) e).GetValue ();
212 } else if (e is TypeOf) {
213 result = ((TypeOf) e).TypeArg;
215 } else if (e is ArrayCreation){
216 result = ((ArrayCreation) e).EncodeAsAttribute ();
219 } else if (e is EmptyCast) {
221 if (((EmptyCast) e).Child is Constant) {
222 result = ((Constant) ((EmptyCast)e).Child).GetValue();
228 Error_AttributeArgumentNotValid (loc);
232 public CustomAttributeBuilder Resolve (EmitContext ec)
237 Type = CheckAttributeType (ec, true);
238 if (oldType == null && Type == null)
240 if (oldType != null && oldType != Type) {
241 Report.Error (-6, Location,
242 "Attribute {0} resolved to different types at different times: {1} vs. {2}",
243 Name, oldType, Type);
247 bool MethodImplAttr = false;
248 bool MarshalAsAttr = false;
249 bool GuidAttr = false;
250 bool usage_attr = false;
252 bool DoCompares = true;
255 // If we are a certain special attribute, we
256 // set the information accordingly
259 if (Type == TypeManager.attribute_usage_type)
261 else if (Type == TypeManager.methodimpl_attr_type)
262 MethodImplAttr = true;
263 else if (Type == TypeManager.marshal_as_attr_type)
264 MarshalAsAttr = true;
265 else if (Type == TypeManager.guid_attr_type)
270 // Now we extract the positional and named arguments
272 ArrayList pos_args = new ArrayList ();
273 ArrayList named_args = new ArrayList ();
274 int pos_arg_count = 0;
276 if (Arguments != null) {
277 pos_args = (ArrayList) Arguments [0];
278 if (pos_args != null)
279 pos_arg_count = pos_args.Count;
280 if (Arguments.Count > 1)
281 named_args = (ArrayList) Arguments [1];
284 pos_values = new object [pos_arg_count];
287 // First process positional arguments
291 for (i = 0; i < pos_arg_count; i++) {
292 Argument a = (Argument) pos_args [i];
295 if (!a.Resolve (ec, Location))
301 if (!GetAttributeArgumentExpression (e, Location, out val))
304 pos_values [i] = val;
307 usage_attribute = new AttributeUsageAttribute ((AttributeTargets) pos_values [0]);
308 else if (MethodImplAttr)
309 this.ImplOptions = (MethodImplOptions) pos_values [0];
312 // we will later check the validity of the type
314 if (pos_values [0] is string){
315 if (!ValidateGuid ((string) pos_values [0]))
319 } else if (MarshalAsAttr)
321 (System.Runtime.InteropServices.UnmanagedType) pos_values [0];
326 // Now process named arguments
329 ArrayList field_infos = null;
330 ArrayList prop_infos = null;
331 ArrayList field_values = null;
332 ArrayList prop_values = null;
334 if (named_args.Count > 0) {
335 field_infos = new ArrayList ();
336 prop_infos = new ArrayList ();
337 field_values = new ArrayList ();
338 prop_values = new ArrayList ();
341 Hashtable seen_names = new Hashtable();
343 for (i = 0; i < named_args.Count; i++) {
344 DictionaryEntry de = (DictionaryEntry) named_args [i];
345 string member_name = (string) de.Key;
346 Argument a = (Argument) de.Value;
349 if (seen_names.Contains(member_name)) {
350 Report.Error(643, Location, "'" + member_name + "' duplicate named attribute argument");
353 seen_names.Add(member_name, 1);
355 if (!a.Resolve (ec, Location))
358 Expression member = Expression.MemberLookup (
359 ec, Type, member_name,
360 MemberTypes.Field | MemberTypes.Property,
361 BindingFlags.Public | BindingFlags.Instance,
364 if (member == null) {
365 member = Expression.MemberLookup (ec, Type, member_name,
366 MemberTypes.Field | MemberTypes.Property, BindingFlags.NonPublic | BindingFlags.Instance,
369 if (member != null) {
370 Report.Error_T (122, Location, GetFullMemberName (member_name));
375 if (member == null || !(member is PropertyExpr || member is FieldExpr)) {
376 Error_InvalidNamedArgument (member_name);
381 if (member is PropertyExpr) {
382 PropertyExpr pe = (PropertyExpr) member;
383 PropertyInfo pi = pe.PropertyInfo;
386 Error_InvalidNamedArgument (member_name);
390 Constant c = e as Constant;
392 if (c.Type != pi.PropertyType) {
393 c = Const.ChangeType (Location, c, pi.PropertyType);
398 object o = c.GetValue ();
401 if (usage_attribute != null) {
402 if (member_name == "AllowMultiple")
403 usage_attribute.AllowMultiple = (bool) o;
404 if (member_name == "Inherited")
405 usage_attribute.Inherited = (bool) o;
408 } else if (e is TypeOf) {
409 prop_values.Add (((TypeOf) e).TypeArg);
410 } else if (e is ArrayCreation) {
411 prop_values.Add (((ArrayCreation) e).EncodeAsAttribute());
413 Error_AttributeArgumentNotValid (Location);
419 } else if (member is FieldExpr) {
420 FieldExpr fe = (FieldExpr) member;
421 FieldInfo fi = fe.FieldInfo;
424 Error_InvalidNamedArgument (member_name);
429 // Handle charset here, and set the TypeAttributes
431 Constant c = e as Constant;
433 if (c.Type != fi.FieldType) {
434 c = Const.ChangeType (Location, c, fi.FieldType);
439 object value = c.GetValue ();
440 field_values.Add (value);
441 } else if (e is TypeOf) {
442 field_values.Add (((TypeOf) e).TypeArg);
444 Error_AttributeArgumentNotValid (Location);
448 field_infos.Add (fi);
452 Expression mg = Expression.MemberLookup (
453 ec, Type, ".ctor", MemberTypes.Constructor,
454 BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly,
458 Error_AttributeConstructorMismatch ();
462 MethodBase constructor = Invocation.OverloadResolve (
463 ec, (MethodGroupExpr) mg, pos_args, Location);
465 if (constructor == null) {
466 Error_AttributeConstructorMismatch ();
471 // Now we perform some checks on the positional args as they
472 // cannot be null for a constructor which expects a parameter
476 ParameterData pd = Invocation.GetParameterData (constructor);
478 int group_in_params_array = Int32.MaxValue;
480 if (pc > 0 && pd.ParameterModifier (pc-1) == Parameter.Modifier.PARAMS)
481 group_in_params_array = pc-1;
483 for (int j = 0; j < pos_arg_count; ++j) {
484 Argument a = (Argument) pos_args [j];
486 if (a.Expr is NullLiteral && pd.ParameterType (j) == TypeManager.object_type) {
487 Error_AttributeArgumentNotValid (Location);
491 if (j < group_in_params_array)
494 if (j == group_in_params_array){
495 object v = pos_values [j];
496 int count = pos_arg_count - j;
498 object [] array = new object [count];
499 pos_values [j] = array;
502 object [] array = (object []) pos_values [group_in_params_array];
504 array [j - group_in_params_array] = pos_values [j];
509 // Adjust the size of the pos_values if it had params
511 if (group_in_params_array != Int32.MaxValue){
512 int argc = group_in_params_array+1;
513 object [] new_pos_values = new object [argc];
515 for (int p = 0; p < argc; p++)
516 new_pos_values [p] = pos_values [p];
517 pos_values = new_pos_values;
521 if (named_args.Count > 0) {
522 prop_info_arr = new PropertyInfo [prop_infos.Count];
523 field_info_arr = new FieldInfo [field_infos.Count];
524 field_values_arr = new object [field_values.Count];
525 prop_values_arr = new object [prop_values.Count];
527 field_infos.CopyTo (field_info_arr, 0);
528 field_values.CopyTo (field_values_arr, 0);
530 prop_values.CopyTo (prop_values_arr, 0);
531 prop_infos.CopyTo (prop_info_arr, 0);
533 cb = new CustomAttributeBuilder (
534 (ConstructorInfo) constructor, pos_values,
535 prop_info_arr, prop_values_arr,
536 field_info_arr, field_values_arr);
539 cb = new CustomAttributeBuilder (
540 (ConstructorInfo) constructor, pos_values);
541 } catch (NullReferenceException) {
543 // Don't know what to do here
546 -101, Location, "NullReferenceException while trying to create attribute." +
547 "Something's wrong!");
548 } catch (Exception e) {
551 // using System.ComponentModel;
552 // [DefaultValue (CollectionChangeAction.Add)]
553 // class X { static void Main () {} }
556 -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);
563 /// Get a string containing a list of valid targets for the attribute 'attr'
565 string GetValidTargets ()
567 StringBuilder sb = new StringBuilder ();
568 AttributeTargets targets = GetAttributeUsage ().ValidOn;
570 if ((targets & AttributeTargets.Assembly) != 0)
571 sb.Append ("'assembly' ");
573 if ((targets & AttributeTargets.Class) != 0)
574 sb.Append ("'class' ");
576 if ((targets & AttributeTargets.Constructor) != 0)
577 sb.Append ("'constructor' ");
579 if ((targets & AttributeTargets.Delegate) != 0)
580 sb.Append ("'delegate' ");
582 if ((targets & AttributeTargets.Enum) != 0)
583 sb.Append ("'enum' ");
585 if ((targets & AttributeTargets.Event) != 0)
586 sb.Append ("'event' ");
588 if ((targets & AttributeTargets.Field) != 0)
589 sb.Append ("'field' ");
591 if ((targets & AttributeTargets.Interface) != 0)
592 sb.Append ("'interface' ");
594 if ((targets & AttributeTargets.Method) != 0)
595 sb.Append ("'method' ");
597 if ((targets & AttributeTargets.Module) != 0)
598 sb.Append ("'module' ");
600 if ((targets & AttributeTargets.Parameter) != 0)
601 sb.Append ("'parameter' ");
603 if ((targets & AttributeTargets.Property) != 0)
604 sb.Append ("'property' ");
606 if ((targets & AttributeTargets.ReturnValue) != 0)
607 sb.Append ("'return' ");
609 if ((targets & AttributeTargets.Struct) != 0)
610 sb.Append ("'struct' ");
612 return sb.ToString ();
617 /// Returns AttributeUsage attribute for this type
619 public AttributeUsageAttribute GetAttributeUsage ()
621 AttributeUsageAttribute ua = usage_attr_cache [Type] as AttributeUsageAttribute;
625 Class attr_class = TypeManager.LookupClass (Type);
627 if (attr_class == null) {
628 object[] usage_attr = Type.GetCustomAttributes (TypeManager.attribute_usage_type, true);
629 ua = (AttributeUsageAttribute)usage_attr [0];
630 usage_attr_cache.Add (Type, ua);
634 return attr_class.AttributeUsage;
637 public string IndexerName_GetIndexerName (EmitContext ec)
639 if (Arguments == null || Arguments [0] == null){
640 Error_AttributeConstructorMismatch ();
643 ArrayList pos_args = (ArrayList) Arguments [0];
644 if (pos_args.Count != 1) {
645 Error_AttributeConstructorMismatch ();
649 Argument arg = (Argument) pos_args [0];
650 if (!arg.Resolve (ec, Location))
653 StringConstant sc = arg.Expr as StringConstant;
655 Error_AttributeConstructorMismatch ();
663 /// Returns condition of ConditionalAttribute
665 public string GetConditionalAttributeValue (DeclSpace ds)
667 if (pos_values == null) {
668 EmitContext ec = new EmitContext (ds, ds, Location, null, null, 0, false);
670 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
671 // But because a lot of attribute class code must be rewritten will be better to wait...
675 // Some error occurred
676 if (pos_values [0] == null)
679 return (string)pos_values [0];
683 /// Creates the instance of ObsoleteAttribute from this attribute instance
685 public ObsoleteAttribute GetObsoleteAttribute (DeclSpace ds)
687 if (pos_values == null) {
688 EmitContext ec = new EmitContext (ds, ds, Location, null, null, 0, false);
690 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
691 // But because a lot of attribute class code must be rewritten will be better to wait...
695 // Some error occurred
696 if (pos_values == null)
699 if (pos_values.Length == 0)
700 return new ObsoleteAttribute ();
702 if (pos_values.Length == 1)
703 return new ObsoleteAttribute ((string)pos_values [0]);
705 return new ObsoleteAttribute ((string)pos_values [0], (bool)pos_values [1]);
709 /// Returns value of CLSCompliantAttribute contructor parameter but because the method can be called
710 /// before ApplyAttribute. We need to resolve the arguments.
711 /// This situation occurs when class deps is differs from Emit order.
713 public bool GetClsCompliantAttributeValue (DeclSpace ds)
715 if (pos_values == null) {
716 EmitContext ec = new EmitContext (ds, ds, Location, null, null, 0, false);
718 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
719 // But because a lot of attribute class code must be rewritten will be better to wait...
723 // Some error occurred
724 if (pos_values [0] == null)
727 return (bool)pos_values [0];
730 public object GetPositionalValue (int i)
732 return (pos_values == null) ? null : pos_values[i];
735 object GetFieldValue (string name)
738 if (field_info_arr == null)
741 foreach (FieldInfo fi in field_info_arr) {
743 return field_values_arr [i];
749 public UnmanagedMarshal GetMarshal ()
751 object o = GetFieldValue ("ArraySubType");
752 UnmanagedType array_sub_type = o == null ? UnmanagedType.I4 : (UnmanagedType) o;
754 switch (UnmanagedType) {
755 case UnmanagedType.CustomMarshaler:
756 MethodInfo define_custom = typeof (UnmanagedMarshal).GetMethod ("DefineCustom",
757 BindingFlags.Static | BindingFlags.Public);
758 if (define_custom == null)
761 object [] args = new object [4];
762 args [0] = GetFieldValue ("MarshalTypeRef");
763 args [1] = GetFieldValue ("MarshalCookie");
764 args [2] = GetFieldValue ("MarshalType");
765 args [3] = Guid.Empty;
766 return (UnmanagedMarshal) define_custom.Invoke (null, args);
768 case UnmanagedType.LPArray:
769 return UnmanagedMarshal.DefineLPArray (array_sub_type);
771 case UnmanagedType.SafeArray:
772 return UnmanagedMarshal.DefineSafeArray (array_sub_type);
774 case UnmanagedType.ByValArray:
775 return UnmanagedMarshal.DefineByValArray ((int) GetFieldValue ("SizeConst"));
777 case UnmanagedType.ByValTStr:
778 return UnmanagedMarshal.DefineByValTStr ((int) GetFieldValue ("SizeConst"));
781 return UnmanagedMarshal.DefineUnmanagedMarshal (UnmanagedType);
785 public bool IsInternalCall
787 get { return ImplOptions == MethodImplOptions.InternalCall; }
791 /// Emit attribute for Attributable symbol
793 public void Emit (EmitContext ec, Attributable ias, ListDictionary emitted_attr)
795 CustomAttributeBuilder cb = Resolve (ec);
799 AttributeUsageAttribute usage_attr = GetAttributeUsage ();
800 if ((usage_attr.ValidOn & ias.AttributeTargets) == 0) {
801 // "Attribute '{0}' is not valid on this declaration type. It is valid on {1} declarations only.";
802 Report.Error_T (592, Location, Name, GetValidTargets ());
806 ias.ApplyAttributeBuilder (this, cb);
808 if (!usage_attr.AllowMultiple && emitted_attr.Contains (Target)) {
809 Report.Error (579, Location, "Duplicate '" + Name + "' attribute");
812 emitted_attr [Type] = Target;
814 // Here we are testing attribute arguments for array usage (error 3016)
815 if (ias.IsClsCompliaceRequired (ec.DeclSpace)) {
816 if (Arguments == null)
819 ArrayList pos_args = (ArrayList) Arguments [0];
820 if (pos_args != null) {
821 foreach (Argument arg in pos_args) {
822 // Type is undefined (was error 246)
823 if (arg.Type == null)
826 if (arg.Type.IsArray) {
827 Report.Error_T (3016, Location);
833 if (Arguments.Count < 2)
836 ArrayList named_args = (ArrayList) Arguments [1];
837 foreach (DictionaryEntry de in named_args) {
838 Argument arg = (Argument) de.Value;
840 // Type is undefined (was error 246)
841 if (arg.Type == null)
844 if (arg.Type.IsArray) {
845 Report.Error_T (3016, Location);
852 public object GetValue (EmitContext ec, Constant c, Type target)
854 if (Convert.ImplicitConversionExists (ec, c, target))
855 return c.GetValue ();
857 Convert.Error_CannotImplicitConversion (Location, c.Type, target);
861 public MethodBuilder DefinePInvokeMethod (EmitContext ec, TypeBuilder builder, string name,
862 MethodAttributes flags, Type ret_type, Type [] param_types)
865 // We extract from the attribute the information we need
868 if (Arguments == null) {
869 Console.WriteLine ("Internal error : this is not supposed to happen !");
873 ResolveType (ec, true);
877 ArrayList named_args = new ArrayList ();
879 ArrayList pos_args = (ArrayList) Arguments [0];
880 if (Arguments.Count > 1)
881 named_args = (ArrayList) Arguments [1];
884 string dll_name = null;
886 Argument tmp = (Argument) pos_args [0];
888 if (!tmp.Resolve (ec, Location))
891 if (tmp.Expr is Constant)
892 dll_name = (string) ((Constant) tmp.Expr).GetValue ();
894 Error_AttributeArgumentNotValid (Location);
898 // Now we process the named arguments
899 CallingConvention cc = CallingConvention.Winapi;
900 CharSet charset = CharSet.Ansi;
901 bool preserve_sig = true;
903 bool exact_spelling = false;
905 bool set_last_err = false;
906 string entry_point = null;
908 for (int i = 0; i < named_args.Count; i++) {
910 DictionaryEntry de = (DictionaryEntry) named_args [i];
912 string member_name = (string) de.Key;
913 Argument a = (Argument) de.Value;
915 if (!a.Resolve (ec, Location))
918 Expression member = Expression.MemberLookup (
919 ec, Type, member_name,
920 MemberTypes.Field | MemberTypes.Property,
921 BindingFlags.Public | BindingFlags.Instance,
924 if (member == null || !(member is FieldExpr)) {
925 Error_InvalidNamedArgument (member_name);
929 if (member is FieldExpr) {
930 FieldExpr fe = (FieldExpr) member;
931 FieldInfo fi = fe.FieldInfo;
934 Error_InvalidNamedArgument (member_name);
938 if (a.Expr is Constant) {
939 Constant c = (Constant) a.Expr;
942 if (member_name == "CallingConvention"){
943 object val = GetValue (ec, c, typeof (CallingConvention));
946 cc = (CallingConvention) val;
947 } else if (member_name == "CharSet"){
948 charset = (CharSet) c.GetValue ();
949 } else if (member_name == "EntryPoint")
950 entry_point = (string) c.GetValue ();
951 else if (member_name == "SetLastError")
952 set_last_err = (bool) c.GetValue ();
954 else if (member_name == "ExactSpelling")
955 exact_spelling = (bool) c.GetValue ();
957 else if (member_name == "PreserveSig")
958 preserve_sig = (bool) c.GetValue ();
959 } catch (InvalidCastException){
960 Error_InvalidNamedArgument (member_name);
961 Error_AttributeArgumentNotValid (Location);
964 Error_AttributeArgumentNotValid (Location);
971 if (entry_point == null)
974 charset = (CharSet)((int)charset | 0x40);
976 MethodBuilder mb = builder.DefinePInvokeMethod (
977 name, dll_name, entry_point, flags | MethodAttributes.HideBySig,
978 CallingConventions.Standard,
985 mb.SetImplementationFlags (MethodImplAttributes.PreserveSig);
990 private Expression GetValue ()
992 if ((Arguments == null) || (Arguments.Count < 1))
994 ArrayList al = (ArrayList) Arguments [0];
995 if ((al == null) || (al.Count < 1))
997 Argument arg = (Argument) al [0];
998 if ((arg == null) || (arg.Expr == null))
1003 public string GetString ()
1005 Expression e = GetValue ();
1006 if (e is StringLiteral)
1007 return (e as StringLiteral).Value;
1011 public bool GetBoolean ()
1013 Expression e = GetValue ();
1014 if (e is BoolLiteral)
1015 return (e as BoolLiteral).Value;
1022 /// For global attributes (assembly, module) we need special handling.
1023 /// Attributes can be located in the several files
1025 public class GlobalAttribute: Attribute
1027 public readonly NamespaceEntry ns;
1029 public GlobalAttribute (TypeContainer container, string target, string name, ArrayList args, Location loc):
1030 base (target, name, args, loc)
1032 ns = container.NamespaceEntry;
1035 protected override Type CheckAttributeType (EmitContext ec, bool complain)
1037 NamespaceEntry old = ec.DeclSpace.NamespaceEntry;
1038 if (old == null || old.NS == null || old.NS == Namespace.Root)
1039 ec.DeclSpace.NamespaceEntry = ns;
1040 return base.CheckAttributeType (ec, complain);
1044 public class Attributes {
1045 public ArrayList Attrs;
1047 public Attributes (Attribute a)
1049 Attrs = new ArrayList ();
1053 public Attributes (ArrayList attrs)
1058 public void AddAttributes (ArrayList attrs)
1060 Attrs.AddRange (attrs);
1064 /// Checks whether attribute target is valid for the current element
1066 public void CheckTargets (string[] possible_targets)
1068 foreach (Attribute a in Attrs) {
1069 if (a.Target == null) {
1070 a.Target = possible_targets [0];
1074 if (((IList) possible_targets).Contains (a.Target))
1077 StringBuilder sb = new StringBuilder ();
1078 foreach (string s in possible_targets) {
1082 sb.Remove (sb.Length - 2, 2);
1083 Report.Error_T (657, a.Location, a.Target, sb.ToString ());
1087 private Attribute Search (Type t, EmitContext ec, bool complain)
1089 foreach (Attribute a in Attrs) {
1090 if (a.ResolveType (ec, false) == t)
1096 public Attribute Search (Type t, EmitContext ec)
1098 return Search (t, ec, true);
1102 /// Returns all attributes of type 't'. Use it when attribute is AllowMultiple = true
1104 public Attribute[] SearchMulti (Type t, EmitContext ec)
1106 ArrayList ar = null;
1108 foreach (Attribute a in Attrs) {
1109 if (a.ResolveType (ec, false) == t) {
1111 ar = new ArrayList ();
1116 return ar == null ? null : ar.ToArray (typeof (Attribute)) as Attribute[];
1119 public void Emit (EmitContext ec, Attributable ias)
1121 ListDictionary ld = new ListDictionary ();
1123 foreach (Attribute a in Attrs)
1124 a.Emit (ec, ias, ld);
1127 public bool Contains (Type t, EmitContext ec)
1129 return Search (t, ec) != null;
1132 public Attribute GetClsCompliantAttribute (EmitContext ec)
1134 return Search (TypeManager.cls_compliant_attribute_type, ec, false);
1138 /// Pulls the IndexerName attribute from an Indexer if it exists.
1140 public string ScanForIndexerName (EmitContext ec)
1142 Attribute a = Search (TypeManager.indexer_name_type, ec);
1146 // Remove the attribute from the list
1147 //TODO: It is very close to hack and it can crash here
1150 return a.IndexerName_GetIndexerName (ec);
1156 /// Helper class for attribute verification routine.
1158 sealed class AttributeTester
1160 static PtrHashtable analyzed_types = new PtrHashtable ();
1161 static PtrHashtable analyzed_types_obsolete = new PtrHashtable ();
1162 static PtrHashtable analyzed_member_obsolete = new PtrHashtable ();
1163 static PtrHashtable analyzed_method_excluded = new PtrHashtable ();
1165 private AttributeTester ()
1170 /// Returns true if parameters of two compared methods are CLS-Compliant.
1171 /// It tests differing only in ref or out, or in array rank.
1173 public static bool AreOverloadedMethodParamsClsCompliant (Type[] types_a, Type[] types_b)
1175 if (types_a == null || types_b == null)
1178 if (types_a.Length != types_b.Length)
1181 for (int i = 0; i < types_b.Length; ++i) {
1182 Type aType = types_a [i];
1183 Type bType = types_b [i];
1185 if (aType.IsArray && bType.IsArray && aType.GetArrayRank () != bType.GetArrayRank () && aType.GetElementType () == bType.GetElementType ()) {
1189 Type aBaseType = aType;
1190 bool is_either_ref_or_out = false;
1192 if (aType.IsByRef || aType.IsPointer) {
1193 aBaseType = aType.GetElementType ();
1194 is_either_ref_or_out = true;
1197 Type bBaseType = bType;
1198 if (bType.IsByRef || bType.IsPointer)
1200 bBaseType = bType.GetElementType ();
1201 is_either_ref_or_out = !is_either_ref_or_out;
1204 if (aBaseType != bBaseType)
1207 if (is_either_ref_or_out)
1214 /// Goes through all parameters and test if they are CLS-Compliant.
1216 public static bool AreParametersCompliant (Parameter[] fixedParameters, Location loc)
1218 if (fixedParameters == null)
1221 foreach (Parameter arg in fixedParameters) {
1222 if (!AttributeTester.IsClsCompliant (arg.ParameterType)) {
1223 Report.Error_T (3001, loc, arg.GetSignatureForError ());
1232 /// This method tests the CLS compliance of external types. It doesn't test type visibility.
1234 public static bool IsClsCompliant (Type type)
1239 object type_compliance = analyzed_types[type];
1240 if (type_compliance != null)
1241 return type_compliance == TRUE;
1243 if (type.IsPointer) {
1244 analyzed_types.Add (type, null);
1249 if (type.IsArray || type.IsByRef) {
1250 result = IsClsCompliant (TypeManager.GetElementType (type));
1252 result = AnalyzeTypeCompliance (type);
1254 analyzed_types.Add (type, result ? TRUE : FALSE);
1258 static object TRUE = new object ();
1259 static object FALSE = new object ();
1262 /// Non-hierarchical CLS Compliance analyzer
1264 public static bool IsComplianceRequired (MemberInfo mi, DeclSpace ds)
1266 DeclSpace temp_ds = TypeManager.LookupDeclSpace (mi.DeclaringType);
1268 // Type is external, we can get attribute directly
1269 if (temp_ds == null) {
1270 object[] cls_attribute = mi.GetCustomAttributes (TypeManager.cls_compliant_attribute_type, false);
1271 return (cls_attribute.Length == 1 && ((CLSCompliantAttribute)cls_attribute[0]).IsCompliant);
1275 // Interface doesn't store full name
1276 if (temp_ds is Interface)
1279 tmp_name = String.Concat (temp_ds.Name, ".", mi.Name);
1281 MemberCore mc = temp_ds.GetDefinition (tmp_name) as MemberCore;
1282 return mc.IsClsCompliaceRequired (ds);
1285 public static void VerifyModulesClsCompliance ()
1287 Module[] modules = TypeManager.Modules;
1288 if (modules == null)
1291 // The first module is generated assembly
1292 for (int i = 1; i < modules.Length; ++i) {
1293 Module module = modules [i];
1294 if (!IsClsCompliant (module)) {
1295 Report.Error_T (3013, module.Name);
1301 static bool IsClsCompliant (ICustomAttributeProvider attribute_provider)
1303 object[] CompliantAttribute = attribute_provider.GetCustomAttributes (TypeManager.cls_compliant_attribute_type, false);
1304 if (CompliantAttribute.Length == 0)
1307 return ((CLSCompliantAttribute)CompliantAttribute[0]).IsCompliant;
1310 static bool AnalyzeTypeCompliance (Type type)
1312 DeclSpace ds = TypeManager.LookupDeclSpace (type);
1314 return ds.IsClsCompliaceRequired (ds.Parent);
1317 object[] CompliantAttribute = type.GetCustomAttributes (TypeManager.cls_compliant_attribute_type, false);
1318 if (CompliantAttribute.Length == 0)
1319 return IsClsCompliant (type.Assembly);
1321 return ((CLSCompliantAttribute)CompliantAttribute[0]).IsCompliant;
1325 /// Returns instance of ObsoleteAttribute when type is obsolete
1327 public static ObsoleteAttribute GetObsoleteAttribute (Type type)
1329 object type_obsolete = analyzed_types_obsolete [type];
1330 if (type_obsolete == FALSE)
1333 if (type_obsolete != null)
1334 return (ObsoleteAttribute)type_obsolete;
1336 ObsoleteAttribute result = null;
1337 if (type.IsByRef || type.IsArray || type.IsPointer) {
1338 result = GetObsoleteAttribute (TypeManager.GetElementType (type));
1340 DeclSpace type_ds = TypeManager.LookupDeclSpace (type);
1342 // Type is external, we can get attribute directly
1343 if (type_ds == null) {
1344 object[] attribute = type.GetCustomAttributes (TypeManager.obsolete_attribute_type, false);
1345 if (attribute.Length == 1)
1346 result = (ObsoleteAttribute)attribute [0];
1348 result = type_ds.GetObsoleteAttribute (type_ds);
1352 analyzed_types_obsolete.Add (type, result == null ? FALSE : result);
1357 /// Returns instance of ObsoleteAttribute when method is obsolete
1359 public static ObsoleteAttribute GetMethodObsoleteAttribute (MethodBase mb)
1361 IMethodData mc = TypeManager.GetMethod (mb);
1363 return mc.GetObsoleteAttribute ();
1365 // TODO: remove after Constructor will be ready for IMethodData
1366 if (mb.DeclaringType is TypeBuilder)
1369 return GetMemberObsoleteAttribute (mb);
1373 /// Returns instance of ObsoleteAttribute when member is obsolete
1375 public static ObsoleteAttribute GetMemberObsoleteAttribute (MemberInfo mi)
1377 object type_obsolete = analyzed_member_obsolete [mi];
1378 if (type_obsolete == FALSE)
1381 if (type_obsolete != null)
1382 return (ObsoleteAttribute)type_obsolete;
1384 ObsoleteAttribute oa = System.Attribute.GetCustomAttribute (mi, TypeManager.obsolete_attribute_type, false) as ObsoleteAttribute;
1385 analyzed_member_obsolete.Add (mi, oa == null ? FALSE : oa);
1390 /// Common method for Obsolete error/warning reporting.
1392 public static void Report_ObsoleteMessage (ObsoleteAttribute oa, string member, Location loc)
1395 Report.Error_T (619, loc, member, oa.Message);
1399 if (oa.Message == null) {
1400 Report.Warning_T (612, loc, member);
1403 Report.Warning_T (618, loc, member, oa.Message);
1406 public static bool IsConditionalMethodExcluded (MethodBase mb)
1408 object excluded = analyzed_method_excluded [mb];
1409 if (excluded != null)
1410 return excluded == TRUE ? true : false;
1412 ConditionalAttribute[] attrs = mb.GetCustomAttributes (TypeManager.conditional_attribute_type, true) as ConditionalAttribute[];
1413 if (attrs.Length == 0) {
1414 analyzed_method_excluded.Add (mb, FALSE);
1418 foreach (ConditionalAttribute a in attrs) {
1419 if (RootContext.AllDefines.Contains (a.ConditionString)) {
1420 analyzed_method_excluded.Add (mb, FALSE);
1424 analyzed_method_excluded.Add (mb, TRUE);