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.");
129 /// Tries to resolve the type of the attribute. Flags an error if it can't, and complain is true.
131 protected virtual Type CheckAttributeType (DeclSpace ds, bool complain)
133 Type t1 = RootContext.LookupType (ds, Name, true, Location);
135 // FIXME: Shouldn't do this for quoted attributes: [@A]
136 Type t2 = RootContext.LookupType (ds, Name + "Attribute", true, Location);
138 String err0616 = null;
140 if (t1 != null && ! t1.IsSubclassOf (TypeManager.attribute_type)) {
142 err0616 = "'" + Name + "': is not an attribute class";
144 if (t2 != null && ! t2.IsSubclassOf (TypeManager.attribute_type)) {
146 err0616 = (err0616 != null)
147 ? "Neither '" + Name + "' nor '" + Name + "Attribute' is an attribute class"
148 : "'" + Name + "Attribute': is not an attribute class";
151 if (t1 != null && t2 != null) {
152 Report.Error(1614, Location, "'" + Name + "': is ambiguous; "
153 + " use either '@" + Name + "' or '" + Name + "Attribute'");
161 if (err0616 != null) {
162 Report.Error (616, Location, err0616);
167 Report.Error (246, Location,
168 "Could not find attribute '" + Name
169 + "' (are you missing a using directive or an assembly reference ?)");
173 public Type ResolveType (DeclSpace ds, bool complain)
176 Type = CheckAttributeType (ds, complain);
181 /// Validates the guid string
183 bool ValidateGuid (string guid)
189 Report.Error (647, Location, "Format of GUID is invalid: " + guid);
195 // Given an expression, if the expression is a valid attribute-argument-expression
196 // returns an object that can be used to encode it, or null on failure.
198 public static bool GetAttributeArgumentExpression (Expression e, Location loc, out object result)
201 result = ((Constant) e).GetValue ();
203 } else if (e is TypeOf) {
204 result = ((TypeOf) e).TypeArg;
206 } else if (e is ArrayCreation){
207 result = ((ArrayCreation) e).EncodeAsAttribute ();
210 } else if (e is EmptyCast) {
212 if (((EmptyCast) e).Child is Constant) {
213 result = ((Constant) ((EmptyCast)e).Child).GetValue();
219 Error_AttributeArgumentNotValid (loc);
223 public CustomAttributeBuilder Resolve (EmitContext ec)
228 Type = CheckAttributeType (ec.DeclSpace, true);
229 if (oldType == null && Type == null)
231 if (oldType != null && oldType != Type) {
232 Report.Error (-6, Location,
233 "Attribute {0} resolved to different types at different times: {1} vs. {2}",
234 Name, oldType, Type);
238 bool MethodImplAttr = false;
239 bool MarshalAsAttr = false;
240 bool GuidAttr = false;
241 bool usage_attr = false;
243 bool DoCompares = true;
246 // If we are a certain special attribute, we
247 // set the information accordingly
250 if (Type == TypeManager.attribute_usage_type)
252 else if (Type == TypeManager.methodimpl_attr_type)
253 MethodImplAttr = true;
254 else if (Type == TypeManager.marshal_as_attr_type)
255 MarshalAsAttr = true;
256 else if (Type == TypeManager.guid_attr_type)
261 // Now we extract the positional and named arguments
263 ArrayList pos_args = new ArrayList ();
264 ArrayList named_args = new ArrayList ();
265 int pos_arg_count = 0;
267 if (Arguments != null) {
268 pos_args = (ArrayList) Arguments [0];
269 if (pos_args != null)
270 pos_arg_count = pos_args.Count;
271 if (Arguments.Count > 1)
272 named_args = (ArrayList) Arguments [1];
275 pos_values = new object [pos_arg_count];
278 // First process positional arguments
282 for (i = 0; i < pos_arg_count; i++) {
283 Argument a = (Argument) pos_args [i];
286 if (!a.Resolve (ec, Location))
292 if (!GetAttributeArgumentExpression (e, Location, out val))
295 pos_values [i] = val;
298 usage_attribute = new AttributeUsageAttribute ((AttributeTargets) pos_values [0]);
299 else if (MethodImplAttr)
300 this.ImplOptions = (MethodImplOptions) pos_values [0];
303 // we will later check the validity of the type
305 if (pos_values [0] is string){
306 if (!ValidateGuid ((string) pos_values [0]))
310 } else if (MarshalAsAttr)
312 (System.Runtime.InteropServices.UnmanagedType) pos_values [0];
317 // Now process named arguments
320 ArrayList field_infos = null;
321 ArrayList prop_infos = null;
322 ArrayList field_values = null;
323 ArrayList prop_values = null;
325 if (named_args.Count > 0) {
326 field_infos = new ArrayList ();
327 prop_infos = new ArrayList ();
328 field_values = new ArrayList ();
329 prop_values = new ArrayList ();
332 Hashtable seen_names = new Hashtable();
334 for (i = 0; i < named_args.Count; i++) {
335 DictionaryEntry de = (DictionaryEntry) named_args [i];
336 string member_name = (string) de.Key;
337 Argument a = (Argument) de.Value;
340 if (seen_names.Contains(member_name)) {
341 Report.Error(643, Location, "'" + member_name + "' duplicate named attribute argument");
344 seen_names.Add(member_name, 1);
346 if (!a.Resolve (ec, Location))
349 Expression member = Expression.MemberLookup (
350 ec, Type, member_name,
351 MemberTypes.Field | MemberTypes.Property,
352 BindingFlags.Public | BindingFlags.Instance,
355 if (member == null || !(member is PropertyExpr || member is FieldExpr)) {
356 Error_InvalidNamedArgument (member_name);
361 if (member is PropertyExpr) {
362 PropertyExpr pe = (PropertyExpr) member;
363 PropertyInfo pi = pe.PropertyInfo;
366 Error_InvalidNamedArgument (member_name);
373 if (e.Type != pi.PropertyType){
374 c = Const.ChangeType (Location, (Constant) e, pi.PropertyType);
380 object o = c.GetValue ();
383 if (usage_attribute != null) {
384 if (member_name == "AllowMultiple")
385 usage_attribute.AllowMultiple = (bool) o;
386 if (member_name == "Inherited")
387 usage_attribute.Inherited = (bool) o;
390 } else if (e is TypeOf) {
391 prop_values.Add (((TypeOf) e).TypeArg);
392 } else if (e is ArrayCreation) {
393 prop_values.Add (((ArrayCreation) e).EncodeAsAttribute());
395 Error_AttributeArgumentNotValid (Location);
401 } else if (member is FieldExpr) {
402 FieldExpr fe = (FieldExpr) member;
403 FieldInfo fi = fe.FieldInfo;
406 Error_InvalidNamedArgument (member_name);
411 // Handle charset here, and set the TypeAttributes
414 Constant c = (Constant) e;;
416 if (c.Type != fi.FieldType){
417 c = Const.ChangeType (Location, (Constant) e, fi.FieldType);
422 object value = c.GetValue ();
423 field_values.Add (value);
424 } else if (e is TypeOf) {
425 field_values.Add (((TypeOf) e).TypeArg);
427 Error_AttributeArgumentNotValid (Location);
431 field_infos.Add (fi);
435 Expression mg = Expression.MemberLookup (
436 ec, Type, ".ctor", MemberTypes.Constructor,
437 BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly,
441 Error_AttributeConstructorMismatch ();
445 MethodBase constructor = Invocation.OverloadResolve (
446 ec, (MethodGroupExpr) mg, pos_args, Location);
448 if (constructor == null) {
449 Error_AttributeConstructorMismatch ();
454 // Now we perform some checks on the positional args as they
455 // cannot be null for a constructor which expects a parameter
459 ParameterData pd = Invocation.GetParameterData (constructor);
461 int group_in_params_array = Int32.MaxValue;
463 if (pc > 0 && pd.ParameterModifier (pc-1) == Parameter.Modifier.PARAMS)
464 group_in_params_array = pc-1;
466 for (int j = 0; j < pos_arg_count; ++j) {
467 Argument a = (Argument) pos_args [j];
469 if (a.Expr is NullLiteral && pd.ParameterType (j) == TypeManager.object_type) {
470 Error_AttributeArgumentNotValid (Location);
474 if (j < group_in_params_array)
477 if (j == group_in_params_array){
478 object v = pos_values [j];
479 int count = pos_arg_count - j;
481 object [] array = new object [count];
482 pos_values [j] = array;
485 object [] array = (object []) pos_values [group_in_params_array];
487 array [j - group_in_params_array] = pos_values [j];
492 // Adjust the size of the pos_values if it had params
494 if (group_in_params_array != Int32.MaxValue){
495 int argc = group_in_params_array+1;
496 object [] new_pos_values = new object [argc];
498 for (int p = 0; p < argc; p++)
499 new_pos_values [p] = pos_values [p];
500 pos_values = new_pos_values;
504 if (named_args.Count > 0) {
505 prop_info_arr = new PropertyInfo [prop_infos.Count];
506 field_info_arr = new FieldInfo [field_infos.Count];
507 field_values_arr = new object [field_values.Count];
508 prop_values_arr = new object [prop_values.Count];
510 field_infos.CopyTo (field_info_arr, 0);
511 field_values.CopyTo (field_values_arr, 0);
513 prop_values.CopyTo (prop_values_arr, 0);
514 prop_infos.CopyTo (prop_info_arr, 0);
516 cb = new CustomAttributeBuilder (
517 (ConstructorInfo) constructor, pos_values,
518 prop_info_arr, prop_values_arr,
519 field_info_arr, field_values_arr);
522 cb = new CustomAttributeBuilder (
523 (ConstructorInfo) constructor, pos_values);
524 } catch (NullReferenceException) {
526 // Don't know what to do here
529 -101, Location, "NullReferenceException while trying to create attribute." +
530 "Something's wrong!");
531 } catch (Exception e) {
534 // using System.ComponentModel;
535 // [DefaultValue (CollectionChangeAction.Add)]
536 // class X { static void Main () {} }
540 "The compiler can not encode this attribute in .NET due to\n" +
541 "\ta bug in the .NET runtime. Try the Mono runtime.\nThe error was: " + e.Message);
548 /// Get a string containing a list of valid targets for the attribute 'attr'
550 static string GetValidTargets (Attribute attr)
552 StringBuilder sb = new StringBuilder ();
553 AttributeTargets targets = attr.GetAttributeUsage ().ValidOn;
555 if ((targets & AttributeTargets.Assembly) != 0)
556 sb.Append ("'assembly' ");
558 if ((targets & AttributeTargets.Class) != 0)
559 sb.Append ("'class' ");
561 if ((targets & AttributeTargets.Constructor) != 0)
562 sb.Append ("'constructor' ");
564 if ((targets & AttributeTargets.Delegate) != 0)
565 sb.Append ("'delegate' ");
567 if ((targets & AttributeTargets.Enum) != 0)
568 sb.Append ("'enum' ");
570 if ((targets & AttributeTargets.Event) != 0)
571 sb.Append ("'event' ");
573 if ((targets & AttributeTargets.Field) != 0)
574 sb.Append ("'field' ");
576 if ((targets & AttributeTargets.Interface) != 0)
577 sb.Append ("'interface' ");
579 if ((targets & AttributeTargets.Method) != 0)
580 sb.Append ("'method' ");
582 if ((targets & AttributeTargets.Module) != 0)
583 sb.Append ("'module' ");
585 if ((targets & AttributeTargets.Parameter) != 0)
586 sb.Append ("'parameter' ");
588 if ((targets & AttributeTargets.Property) != 0)
589 sb.Append ("'property' ");
591 if ((targets & AttributeTargets.ReturnValue) != 0)
592 sb.Append ("'return' ");
594 if ((targets & AttributeTargets.Struct) != 0)
595 sb.Append ("'struct' ");
597 return sb.ToString ();
601 public static void Error_AttributeNotValidForElement (Attribute a, Location loc)
604 592, loc, "Attribute '" + a.Name +
605 "' is not valid on this declaration type. " +
606 "It is valid on " + GetValidTargets (a) + "declarations only.");
611 /// Returns AttributeUsage attribute for this type
613 public AttributeUsageAttribute GetAttributeUsage ()
615 AttributeUsageAttribute ua = usage_attr_cache [Type] as AttributeUsageAttribute;
619 Class attr_class = TypeManager.LookupClass (Type);
621 if (attr_class == null) {
622 object[] usage_attr = Type.GetCustomAttributes (TypeManager.attribute_usage_type, true);
623 ua = (AttributeUsageAttribute)usage_attr [0];
624 usage_attr_cache.Add (Type, ua);
628 return attr_class.AttributeUsage;
633 // This pulls the condition name out of a Conditional attribute
635 public string Conditional_GetConditionName ()
638 // So we have a Conditional, pull the data out.
640 if (Arguments == null || Arguments [0] == null){
641 Error_AttributeConstructorMismatch ();
645 ArrayList pos_args = (ArrayList) Arguments [0];
646 if (pos_args.Count != 1){
647 Error_AttributeConstructorMismatch ();
651 Argument arg = (Argument) pos_args [0];
652 if (!(arg.Expr is StringConstant)){
653 Error_AttributeConstructorMismatch ();
657 return ((StringConstant) arg.Expr).Value;
661 // This pulls the obsolete message and error flag out of an Obsolete attribute
663 public string Obsolete_GetObsoleteMessage (out bool is_error)
667 // So we have an Obsolete, pull the data out.
669 if (Arguments == null || Arguments [0] == null)
672 ArrayList pos_args = (ArrayList) Arguments [0];
673 if (pos_args.Count == 0)
675 else if (pos_args.Count > 2){
676 Error_AttributeConstructorMismatch ();
680 Argument arg = (Argument) pos_args [0];
681 if (!(arg.Expr is StringConstant)){
682 Error_AttributeConstructorMismatch ();
686 if (pos_args.Count == 2){
687 Argument arg2 = (Argument) pos_args [1];
688 if (!(arg2.Expr is BoolConstant)){
689 Error_AttributeConstructorMismatch ();
692 is_error = ((BoolConstant) arg2.Expr).Value;
695 return ((StringConstant) arg.Expr).Value;
698 public string IndexerName_GetIndexerName (EmitContext ec)
700 if (Arguments == null || Arguments [0] == null){
701 Error_AttributeConstructorMismatch ();
704 ArrayList pos_args = (ArrayList) Arguments [0];
705 if (pos_args.Count != 1) {
706 Error_AttributeConstructorMismatch ();
710 Argument arg = (Argument) pos_args [0];
711 if (!arg.Resolve (ec, Location))
714 StringConstant sc = arg.Expr as StringConstant;
716 Error_AttributeConstructorMismatch ();
724 /// Returns value of CLSCompliantAttribute contructor parameter but because the method can be called
725 /// before ApplyAttribute. We need to resolve the arguments.
726 /// This situation occurs when class deps is differs from Emit order.
728 public bool GetClsCompliantAttributeValue (DeclSpace ds)
730 if (pos_values == null) {
731 EmitContext ec = new EmitContext (ds, ds, Location, null, null, 0, false);
733 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
734 // But because a lot of attribute class code must be rewritten will be better to wait...
738 // Some error occurred
739 if (pos_values [0] == null)
742 return (bool)pos_values [0];
745 public object GetPositionalValue (int i)
747 return (pos_values == null) ? null : pos_values[i];
750 object GetFieldValue (string name)
753 if (field_info_arr == null)
756 foreach (FieldInfo fi in field_info_arr) {
758 return field_values_arr [i];
764 public UnmanagedMarshal GetMarshal ()
766 object o = GetFieldValue ("ArraySubType");
767 UnmanagedType array_sub_type = o == null ? UnmanagedType.I4 : (UnmanagedType) o;
769 switch (UnmanagedType) {
770 case UnmanagedType.CustomMarshaler:
771 MethodInfo define_custom = typeof (UnmanagedMarshal).GetMethod ("DefineCustom",
772 BindingFlags.Static | BindingFlags.Public);
773 if (define_custom == null)
776 object [] args = new object [4];
777 args [0] = GetFieldValue ("MarshalTypeRef");
778 args [1] = GetFieldValue ("MarshalCookie");
779 args [2] = GetFieldValue ("MarshalType");
780 args [3] = Guid.Empty;
781 return (UnmanagedMarshal) define_custom.Invoke (null, args);
783 case UnmanagedType.LPArray:
784 return UnmanagedMarshal.DefineLPArray (array_sub_type);
786 case UnmanagedType.SafeArray:
787 return UnmanagedMarshal.DefineSafeArray (array_sub_type);
789 case UnmanagedType.ByValArray:
790 return UnmanagedMarshal.DefineByValArray ((int) GetFieldValue ("SizeConst"));
792 case UnmanagedType.ByValTStr:
793 return UnmanagedMarshal.DefineByValTStr ((int) GetFieldValue ("SizeConst"));
796 return UnmanagedMarshal.DefineUnmanagedMarshal (UnmanagedType);
800 public bool IsInternalCall
802 get { return ImplOptions == MethodImplOptions.InternalCall; }
805 protected virtual bool CanIgnoreInvalidAttribute (Attributable ias)
811 /// Emit attribute for Attributable symbol
813 public void Emit (EmitContext ec, Attributable ias, ListDictionary emitted_attr)
815 CustomAttributeBuilder cb = Resolve (ec);
819 AttributeUsageAttribute usage_attr = GetAttributeUsage ();
820 if ((usage_attr.ValidOn & ias.AttributeTargets) == 0) {
821 // The parser applies toplevel attributes both to the assembly and
822 // to a top-level class, if any. So, be silent about them.
823 if (! CanIgnoreInvalidAttribute (ias))
824 Error_AttributeNotValidForElement (this, Location);
828 ias.ApplyAttributeBuilder (this, cb);
830 string emitted = emitted_attr [Type] as string;
831 if (Target != null && emitted == Target && !usage_attr.AllowMultiple) {
832 Report.Error (579, Location, "Duplicate '" + Name + "' attribute");
835 emitted_attr [Type] = Target;
837 // Here we are testing attribute arguments for array usage (error 3016)
838 if (ias.IsClsCompliaceRequired (ec.DeclSpace)) {
839 if (Arguments == null)
842 ArrayList pos_args = (ArrayList) Arguments [0];
843 if (pos_args != null) {
844 foreach (Argument arg in pos_args) {
845 // Type is undefined (was error 246)
846 if (arg.Type == null)
849 if (arg.Type.IsArray) {
850 Report.Error_T (3016, Location);
856 if (Arguments.Count < 2)
859 ArrayList named_args = (ArrayList) Arguments [1];
860 foreach (DictionaryEntry de in named_args) {
861 Argument arg = (Argument) de.Value;
863 // Type is undefined (was error 246)
864 if (arg.Type == null)
867 if (arg.Type.IsArray) {
868 Report.Error_T (3016, Location);
875 public object GetValue (EmitContext ec, Constant c, Type target)
877 if (Convert.ImplicitConversionExists (ec, c, target))
878 return c.GetValue ();
880 Convert.Error_CannotImplicitConversion (Location, c.Type, target);
884 public MethodBuilder DefinePInvokeMethod (EmitContext ec, TypeBuilder builder, string name,
885 MethodAttributes flags, Type ret_type, Type [] param_types)
888 // We extract from the attribute the information we need
891 if (Arguments == null) {
892 Console.WriteLine ("Internal error : this is not supposed to happen !");
896 ResolveType (ec.DeclSpace, true);
900 ArrayList named_args = new ArrayList ();
902 ArrayList pos_args = (ArrayList) Arguments [0];
903 if (Arguments.Count > 1)
904 named_args = (ArrayList) Arguments [1];
907 string dll_name = null;
909 Argument tmp = (Argument) pos_args [0];
911 if (!tmp.Resolve (ec, Location))
914 if (tmp.Expr is Constant)
915 dll_name = (string) ((Constant) tmp.Expr).GetValue ();
917 Error_AttributeArgumentNotValid (Location);
921 // Now we process the named arguments
922 CallingConvention cc = CallingConvention.Winapi;
923 CharSet charset = CharSet.Ansi;
924 bool preserve_sig = true;
926 bool exact_spelling = false;
928 bool set_last_err = false;
929 string entry_point = null;
931 for (int i = 0; i < named_args.Count; i++) {
933 DictionaryEntry de = (DictionaryEntry) named_args [i];
935 string member_name = (string) de.Key;
936 Argument a = (Argument) de.Value;
938 if (!a.Resolve (ec, Location))
941 Expression member = Expression.MemberLookup (
942 ec, Type, member_name,
943 MemberTypes.Field | MemberTypes.Property,
944 BindingFlags.Public | BindingFlags.Instance,
947 if (member == null || !(member is FieldExpr)) {
948 Error_InvalidNamedArgument (member_name);
952 if (member is FieldExpr) {
953 FieldExpr fe = (FieldExpr) member;
954 FieldInfo fi = fe.FieldInfo;
957 Error_InvalidNamedArgument (member_name);
961 if (a.Expr is Constant) {
962 Constant c = (Constant) a.Expr;
965 if (member_name == "CallingConvention"){
966 object val = GetValue (ec, c, typeof (CallingConvention));
969 cc = (CallingConvention) val;
970 } else if (member_name == "CharSet"){
971 charset = (CharSet) c.GetValue ();
972 } else if (member_name == "EntryPoint")
973 entry_point = (string) c.GetValue ();
974 else if (member_name == "SetLastError")
975 set_last_err = (bool) c.GetValue ();
977 else if (member_name == "ExactSpelling")
978 exact_spelling = (bool) c.GetValue ();
980 else if (member_name == "PreserveSig")
981 preserve_sig = (bool) c.GetValue ();
982 } catch (InvalidCastException){
983 Error_InvalidNamedArgument (member_name);
984 Error_AttributeArgumentNotValid (Location);
987 Error_AttributeArgumentNotValid (Location);
994 if (entry_point == null)
997 charset = (CharSet)((int)charset | 0x40);
999 MethodBuilder mb = builder.DefinePInvokeMethod (
1000 name, dll_name, entry_point, flags | MethodAttributes.HideBySig,
1001 CallingConventions.Standard,
1008 mb.SetImplementationFlags (MethodImplAttributes.PreserveSig);
1013 private Expression GetValue ()
1015 if ((Arguments == null) || (Arguments.Count < 1))
1017 ArrayList al = (ArrayList) Arguments [0];
1018 if ((al == null) || (al.Count < 1))
1020 Argument arg = (Argument) al [0];
1021 if ((arg == null) || (arg.Expr == null))
1026 public string GetString ()
1028 Expression e = GetValue ();
1029 if (e is StringLiteral)
1030 return (e as StringLiteral).Value;
1034 public bool GetBoolean ()
1036 Expression e = GetValue ();
1037 if (e is BoolLiteral)
1038 return (e as BoolLiteral).Value;
1045 /// For global attributes (assembly, module) we need special handling.
1046 /// Attributes can be located in the several files
1048 public class GlobalAttribute: Attribute
1050 public readonly NamespaceEntry ns;
1052 public GlobalAttribute (TypeContainer container, string target, string name, ArrayList args, Location loc):
1053 base (target, name, args, loc)
1055 ns = container.NamespaceEntry;
1058 protected override Type CheckAttributeType (DeclSpace ds, bool complain)
1060 NamespaceEntry old = ds.NamespaceEntry;
1061 if (old == null || old.NS == null || old.NS == Namespace.Root)
1062 ds.NamespaceEntry = ns;
1063 return base.CheckAttributeType (ds, complain);
1066 protected override bool CanIgnoreInvalidAttribute (Attributable ias)
1068 // Ignore error if this attribute is shared between the Assembly
1069 // and a top-level class. The parser couldn't figure out which entity
1070 // this attribute belongs to. If this attribute is erroneous, it should
1071 // be caught when it is processed by the top-level class.
1073 return (Target == null && ias is CommonAssemblyModulClass);
1077 public class Attributes {
1078 public ArrayList Attrs;
1080 public Attributes (Attribute a)
1082 Attrs = new ArrayList ();
1086 public Attributes (ArrayList attrs)
1091 public void AddAttributes (ArrayList attrs)
1093 Attrs.AddRange (attrs);
1097 /// Checks whether attribute target is valid for the current element
1099 public void CheckTargets (string[] possible_targets)
1101 foreach (Attribute a in Attrs) {
1102 if (a.Target == null)
1105 if (((IList) possible_targets).Contains (a.Target))
1108 StringBuilder sb = new StringBuilder ();
1109 foreach (string s in possible_targets) {
1113 sb.Remove (sb.Length - 2, 2);
1114 Report.Error_T (657, a.Location, a.Target, sb.ToString ());
1118 private Attribute Search (Type t, DeclSpace ds, bool complain)
1120 foreach (Attribute a in Attrs) {
1121 if (a.ResolveType (ds, complain) == t)
1127 public Attribute Search (Type t, DeclSpace ds)
1129 return Search (t, ds, true);
1132 public void Emit (EmitContext ec, Attributable ias)
1134 ListDictionary ld = new ListDictionary ();
1136 foreach (Attribute a in Attrs)
1137 a.Emit (ec, ias, ld);
1140 public bool Contains (Type t, DeclSpace ds)
1142 return Search (t, ds) != null;
1145 public Attribute GetClsCompliantAttribute (DeclSpace ds)
1147 return Search (TypeManager.cls_compliant_attribute_type, ds, false);
1151 /// Pulls the IndexerName attribute from an Indexer if it exists.
1153 public string ScanForIndexerName (EmitContext ec)
1155 Attribute a = Search (TypeManager.indexer_name_type, ec.DeclSpace);
1159 // Remove the attribute from the list
1160 //TODO: It is very close to hack and it can crash here
1163 return a.IndexerName_GetIndexerName (ec);
1169 /// Helper class for attribute verification routine.
1171 sealed class AttributeTester
1173 static PtrHashtable analyzed_types = new PtrHashtable ();
1175 private AttributeTester ()
1180 /// Returns true if parameters of two compared methods are CLS-Compliant.
1181 /// It tests differing only in ref or out, or in array rank.
1183 public static bool AreOverloadedMethodParamsClsCompliant (Type[] types_a, Type[] types_b)
1185 if (types_a == null || types_b == null)
1188 if (types_a.Length != types_b.Length)
1191 for (int i = 0; i < types_b.Length; ++i) {
1192 Type aType = types_a [i];
1193 Type bType = types_b [i];
1195 if (aType.IsArray && bType.IsArray && aType.GetArrayRank () != bType.GetArrayRank () && aType.GetElementType () == bType.GetElementType ()) {
1199 Type aBaseType = aType;
1200 bool is_either_ref_or_out = false;
1202 if (aType.IsByRef || aType.IsPointer) {
1203 aBaseType = aType.GetElementType ();
1204 is_either_ref_or_out = true;
1207 Type bBaseType = bType;
1208 if (bType.IsByRef || bType.IsPointer)
1210 bBaseType = bType.GetElementType ();
1211 is_either_ref_or_out = !is_either_ref_or_out;
1214 if (aBaseType != bBaseType)
1217 if (is_either_ref_or_out)
1224 /// Goes through all parameters and test if they are CLS-Compliant.
1226 public static bool AreParametersCompliant (Parameter[] fixedParameters, Location loc)
1228 if (fixedParameters == null)
1231 foreach (Parameter arg in fixedParameters) {
1232 if (!AttributeTester.IsClsCompliant (arg.ParameterType)) {
1233 Report.Error_T (3001, loc, arg.GetSignatureForError ());
1242 /// This method tests the CLS compliance of external types. It doesn't test type visibility.
1244 public static bool IsClsCompliant (Type type)
1249 object type_compliance = analyzed_types[type];
1250 if (type_compliance != null)
1251 return type_compliance == TRUE;
1253 if (type.IsPointer) {
1254 analyzed_types.Add (type, null);
1259 if (type.IsArray || type.IsByRef) {
1260 result = IsClsCompliant (TypeManager.GetElementType (type));
1262 result = AnalyzeTypeCompliance (type);
1264 analyzed_types.Add (type, result ? TRUE : FALSE);
1268 static object TRUE = new object ();
1269 static object FALSE = new object ();
1272 /// Non-hierarchical CLS Compliance analyzer
1274 public static bool IsComplianceRequired (MemberInfo mi, DeclSpace ds)
1276 DeclSpace temp_ds = TypeManager.LookupDeclSpace (mi.DeclaringType);
1278 // Type is external, we can get attribute directly
1279 if (temp_ds == null) {
1280 object[] cls_attribute = mi.GetCustomAttributes (TypeManager.cls_compliant_attribute_type, false);
1281 return (cls_attribute.Length == 1 && ((CLSCompliantAttribute)cls_attribute[0]).IsCompliant);
1285 // Interface doesn't store full name
1286 if (temp_ds is Interface)
1289 tmp_name = String.Concat (temp_ds.Name, ".", mi.Name);
1291 MemberCore mc = temp_ds.GetDefinition (tmp_name) as MemberCore;
1292 return mc.IsClsCompliaceRequired (ds);
1295 public static void VerifyModulesClsCompliance ()
1297 Module[] modules = TypeManager.Modules;
1298 if (modules == null)
1301 // The first module is generated assembly
1302 for (int i = 1; i < modules.Length; ++i) {
1303 Module module = modules [i];
1304 if (!IsClsCompliant (module)) {
1305 Report.Error_T (3013, module.Name);
1311 static bool IsClsCompliant (ICustomAttributeProvider attribute_provider)
1313 object[] CompliantAttribute = attribute_provider.GetCustomAttributes (TypeManager.cls_compliant_attribute_type, false);
1314 if (CompliantAttribute.Length == 0)
1317 return ((CLSCompliantAttribute)CompliantAttribute[0]).IsCompliant;
1320 static bool AnalyzeTypeCompliance (Type type)
1322 DeclSpace ds = TypeManager.LookupDeclSpace (type);
1324 return ds.IsClsCompliaceRequired (ds.Parent);
1327 object[] CompliantAttribute = type.GetCustomAttributes (TypeManager.cls_compliant_attribute_type, false);
1328 if (CompliantAttribute.Length == 0)
1329 return IsClsCompliant (type.Assembly);
1331 return ((CLSCompliantAttribute)CompliantAttribute[0]).IsCompliant;