2 // attribute.cs: Attribute Handler
4 // Author: Ravi Pratap (ravi@ximian.com)
6 // Licensed under the terms of the GNU GPL
8 // (C) 2001 Ximian, Inc (http://www.ximian.com)
13 using System.Diagnostics;
14 using System.Collections;
15 using System.Collections.Specialized;
16 using System.Reflection;
17 using System.Reflection.Emit;
18 using System.Runtime.InteropServices;
19 using System.Runtime.CompilerServices;
22 namespace Mono.CSharp {
25 /// Base class for objects that can have Attributes applied to them.
27 public abstract class Attributable {
29 /// Attributes for this type
31 Attributes attributes;
33 public Attributable(Attributes attrs)
36 if (attributes != null)
37 attributes.CheckTargets (ValidAttributeTargets);
40 public Attributes OptAttributes
47 if (attributes != null)
48 attributes.CheckTargets (ValidAttributeTargets);
53 /// Use member-specific procedure to apply attribute @a in @cb to the entity being built in @builder
55 public abstract void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb);
58 /// Returns combination of enabled AttributeTargets
60 public abstract AttributeTargets AttributeTargets { get; }
62 public abstract bool IsClsCompliaceRequired (DeclSpace ds);
65 /// Gets list of valid attribute targets for explicit target declaration.
66 /// The first array item is default target. Don't break this rule.
68 protected abstract string[] ValidAttributeTargets { get; }
71 public class Attribute {
73 public readonly string Name;
74 public readonly ArrayList Arguments;
76 public readonly Location Location;
80 // Is non-null if type is AttributeUsageAttribute
81 AttributeUsageAttribute usage_attribute;
83 public AttributeUsageAttribute UsageAttribute {
85 return usage_attribute;
89 MethodImplOptions ImplOptions;
90 UnmanagedType UnmanagedType;
91 CustomAttributeBuilder cb;
93 // non-null if named args present after Resolve () is called
94 PropertyInfo [] prop_info_arr;
95 FieldInfo [] field_info_arr;
96 object [] field_values_arr;
97 object [] prop_values_arr;
100 static PtrHashtable usage_attr_cache = new PtrHashtable ();
102 public Attribute (string target, string name, ArrayList args, Location loc)
110 void Error_InvalidNamedArgument (string name)
112 Report.Error (617, Location, "'" + name + "' is not a valid named attribute " +
113 "argument. Named attribute arguments must be fields which are not " +
114 "readonly, static or const, or properties with a set accessor which "+
118 static void Error_AttributeArgumentNotValid (Location loc)
120 Report.Error (182, loc,
121 "An attribute argument must be a constant expression, typeof " +
122 "expression or array creation expression");
125 void Error_AttributeConstructorMismatch ()
127 Report.Error (-6, Location,
128 "Could not find a constructor for this argument list.");
132 /// Tries to resolve the type of the attribute. Flags an error if it can't, and complain is true.
134 protected virtual Type CheckAttributeType (EmitContext ec, bool complain)
136 Type t1 = RootContext.LookupType (ec.DeclSpace, Name, true, Location);
138 // FIXME: Shouldn't do this for quoted attributes: [@A]
139 Type t2 = RootContext.LookupType (ec.DeclSpace, Name + "Attribute", true, Location);
141 String err0616 = null;
143 if (t1 != null && ! t1.IsSubclassOf (TypeManager.attribute_type)) {
145 err0616 = "'" + Name + "': is not an attribute class";
147 if (t2 != null && ! t2.IsSubclassOf (TypeManager.attribute_type)) {
149 err0616 = (err0616 != null)
150 ? "Neither '" + Name + "' nor '" + Name + "Attribute' is an attribute class"
151 : "'" + Name + "Attribute': is not an attribute class";
154 if (t1 != null && t2 != null) {
155 Report.Error(1614, Location, "'" + Name + "': is ambiguous; "
156 + " use either '@" + Name + "' or '" + Name + "Attribute'");
164 if (err0616 != null) {
165 Report.Error (616, Location, err0616);
170 Report.Error (246, Location,
171 "Could not find attribute '" + Name
172 + "' (are you missing a using directive or an assembly reference ?)");
176 public Type ResolveType (EmitContext ec, bool complain)
179 Type = CheckAttributeType (ec, complain);
184 /// Validates the guid string
186 bool ValidateGuid (string guid)
192 Report.Error (647, Location, "Format of GUID is invalid: " + guid);
197 string GetFullMemberName (string member)
199 return Type.FullName + '.' + member;
203 // Given an expression, if the expression is a valid attribute-argument-expression
204 // returns an object that can be used to encode it, or null on failure.
206 public static bool GetAttributeArgumentExpression (Expression e, Location loc, out object result)
209 result = ((Constant) e).GetValue ();
211 } else if (e is TypeOf) {
212 result = ((TypeOf) e).TypeArg;
214 } else if (e is ArrayCreation){
215 result = ((ArrayCreation) e).EncodeAsAttribute ();
218 } else if (e is EmptyCast) {
220 if (((EmptyCast) e).Child is Constant) {
221 result = ((Constant) ((EmptyCast)e).Child).GetValue();
227 Error_AttributeArgumentNotValid (loc);
231 public CustomAttributeBuilder Resolve (EmitContext ec)
236 Type = CheckAttributeType (ec, true);
237 if (oldType == null && Type == null)
239 if (oldType != null && oldType != Type) {
240 Report.Error (-6, Location,
241 "Attribute {0} resolved to different types at different times: {1} vs. {2}",
242 Name, oldType, Type);
246 bool MethodImplAttr = false;
247 bool MarshalAsAttr = false;
248 bool GuidAttr = false;
249 bool usage_attr = false;
251 bool DoCompares = true;
254 // If we are a certain special attribute, we
255 // set the information accordingly
258 if (Type == TypeManager.attribute_usage_type)
260 else if (Type == TypeManager.methodimpl_attr_type)
261 MethodImplAttr = true;
262 else if (Type == TypeManager.marshal_as_attr_type)
263 MarshalAsAttr = true;
264 else if (Type == TypeManager.guid_attr_type)
269 // Now we extract the positional and named arguments
271 ArrayList pos_args = new ArrayList ();
272 ArrayList named_args = new ArrayList ();
273 int pos_arg_count = 0;
275 if (Arguments != null) {
276 pos_args = (ArrayList) Arguments [0];
277 if (pos_args != null)
278 pos_arg_count = pos_args.Count;
279 if (Arguments.Count > 1)
280 named_args = (ArrayList) Arguments [1];
283 pos_values = new object [pos_arg_count];
286 // First process positional arguments
290 for (i = 0; i < pos_arg_count; i++) {
291 Argument a = (Argument) pos_args [i];
294 if (!a.Resolve (ec, Location))
300 if (!GetAttributeArgumentExpression (e, Location, out val))
303 pos_values [i] = val;
306 usage_attribute = new AttributeUsageAttribute ((AttributeTargets) pos_values [0]);
307 else if (MethodImplAttr)
308 this.ImplOptions = (MethodImplOptions) pos_values [0];
311 // we will later check the validity of the type
313 if (pos_values [0] is string){
314 if (!ValidateGuid ((string) pos_values [0]))
318 } else if (MarshalAsAttr)
320 (System.Runtime.InteropServices.UnmanagedType) pos_values [0];
325 // Now process named arguments
328 ArrayList field_infos = null;
329 ArrayList prop_infos = null;
330 ArrayList field_values = null;
331 ArrayList prop_values = null;
333 if (named_args.Count > 0) {
334 field_infos = new ArrayList ();
335 prop_infos = new ArrayList ();
336 field_values = new ArrayList ();
337 prop_values = new ArrayList ();
340 Hashtable seen_names = new Hashtable();
342 for (i = 0; i < named_args.Count; i++) {
343 DictionaryEntry de = (DictionaryEntry) named_args [i];
344 string member_name = (string) de.Key;
345 Argument a = (Argument) de.Value;
348 if (seen_names.Contains(member_name)) {
349 Report.Error(643, Location, "'" + member_name + "' duplicate named attribute argument");
352 seen_names.Add(member_name, 1);
354 if (!a.Resolve (ec, Location))
357 Expression member = Expression.MemberLookup (
358 ec, Type, member_name,
359 MemberTypes.Field | MemberTypes.Property,
360 BindingFlags.Public | BindingFlags.Instance,
363 if (member == null) {
364 member = Expression.MemberLookup (ec, Type, member_name,
365 MemberTypes.Field | MemberTypes.Property, BindingFlags.NonPublic | BindingFlags.Instance,
368 if (member != null) {
369 Report.Error_T (122, Location, GetFullMemberName (member_name));
374 if (member == null || !(member is PropertyExpr || member is FieldExpr)) {
375 Error_InvalidNamedArgument (member_name);
380 if (member is PropertyExpr) {
381 PropertyExpr pe = (PropertyExpr) member;
382 PropertyInfo pi = pe.PropertyInfo;
385 Error_InvalidNamedArgument (member_name);
389 Constant c = e as Constant;
391 if (c.Type != pi.PropertyType) {
392 c = Const.ChangeType (Location, c, pi.PropertyType);
397 object o = c.GetValue ();
400 if (usage_attribute != null) {
401 if (member_name == "AllowMultiple")
402 usage_attribute.AllowMultiple = (bool) o;
403 if (member_name == "Inherited")
404 usage_attribute.Inherited = (bool) o;
407 } else if (e is TypeOf) {
408 prop_values.Add (((TypeOf) e).TypeArg);
409 } else if (e is ArrayCreation) {
410 prop_values.Add (((ArrayCreation) e).EncodeAsAttribute());
412 Error_AttributeArgumentNotValid (Location);
418 } else if (member is FieldExpr) {
419 FieldExpr fe = (FieldExpr) member;
420 FieldInfo fi = fe.FieldInfo;
423 Error_InvalidNamedArgument (member_name);
428 // Handle charset here, and set the TypeAttributes
430 Constant c = e as Constant;
432 if (c.Type != fi.FieldType) {
433 c = Const.ChangeType (Location, c, fi.FieldType);
438 object value = c.GetValue ();
439 field_values.Add (value);
440 } else if (e is TypeOf) {
441 field_values.Add (((TypeOf) e).TypeArg);
443 Error_AttributeArgumentNotValid (Location);
447 field_infos.Add (fi);
451 Expression mg = Expression.MemberLookup (
452 ec, Type, ".ctor", MemberTypes.Constructor,
453 BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly,
457 Error_AttributeConstructorMismatch ();
461 MethodBase constructor = Invocation.OverloadResolve (
462 ec, (MethodGroupExpr) mg, pos_args, Location);
464 if (constructor == null) {
465 Error_AttributeConstructorMismatch ();
470 // Now we perform some checks on the positional args as they
471 // cannot be null for a constructor which expects a parameter
475 ParameterData pd = Invocation.GetParameterData (constructor);
477 int group_in_params_array = Int32.MaxValue;
479 if (pc > 0 && pd.ParameterModifier (pc-1) == Parameter.Modifier.PARAMS)
480 group_in_params_array = pc-1;
482 for (int j = 0; j < pos_arg_count; ++j) {
483 Argument a = (Argument) pos_args [j];
485 if (a.Expr is NullLiteral && pd.ParameterType (j) == TypeManager.object_type) {
486 Error_AttributeArgumentNotValid (Location);
490 if (j < group_in_params_array)
493 if (j == group_in_params_array){
494 object v = pos_values [j];
495 int count = pos_arg_count - j;
497 object [] array = new object [count];
498 pos_values [j] = array;
501 object [] array = (object []) pos_values [group_in_params_array];
503 array [j - group_in_params_array] = pos_values [j];
508 // Adjust the size of the pos_values if it had params
510 if (group_in_params_array != Int32.MaxValue){
511 int argc = group_in_params_array+1;
512 object [] new_pos_values = new object [argc];
514 for (int p = 0; p < argc; p++)
515 new_pos_values [p] = pos_values [p];
516 pos_values = new_pos_values;
520 if (named_args.Count > 0) {
521 prop_info_arr = new PropertyInfo [prop_infos.Count];
522 field_info_arr = new FieldInfo [field_infos.Count];
523 field_values_arr = new object [field_values.Count];
524 prop_values_arr = new object [prop_values.Count];
526 field_infos.CopyTo (field_info_arr, 0);
527 field_values.CopyTo (field_values_arr, 0);
529 prop_values.CopyTo (prop_values_arr, 0);
530 prop_infos.CopyTo (prop_info_arr, 0);
532 cb = new CustomAttributeBuilder (
533 (ConstructorInfo) constructor, pos_values,
534 prop_info_arr, prop_values_arr,
535 field_info_arr, field_values_arr);
538 cb = new CustomAttributeBuilder (
539 (ConstructorInfo) constructor, pos_values);
540 } catch (NullReferenceException) {
542 // Don't know what to do here
545 -101, Location, "NullReferenceException while trying to create attribute." +
546 "Something's wrong!");
547 } catch (Exception e) {
550 // using System.ComponentModel;
551 // [DefaultValue (CollectionChangeAction.Add)]
552 // class X { static void Main () {} }
555 -23, Location, "The compiler can not encode this attribute in .NET due to a bug in the .NET runtime. Try the Mono runtime. The exception was: " + e.Message);
562 /// Get a string containing a list of valid targets for the attribute 'attr'
564 static string GetValidTargets (Attribute attr)
566 StringBuilder sb = new StringBuilder ();
567 AttributeTargets targets = attr.GetAttributeUsage ().ValidOn;
569 if ((targets & AttributeTargets.Assembly) != 0)
570 sb.Append ("'assembly' ");
572 if ((targets & AttributeTargets.Class) != 0)
573 sb.Append ("'class' ");
575 if ((targets & AttributeTargets.Constructor) != 0)
576 sb.Append ("'constructor' ");
578 if ((targets & AttributeTargets.Delegate) != 0)
579 sb.Append ("'delegate' ");
581 if ((targets & AttributeTargets.Enum) != 0)
582 sb.Append ("'enum' ");
584 if ((targets & AttributeTargets.Event) != 0)
585 sb.Append ("'event' ");
587 if ((targets & AttributeTargets.Field) != 0)
588 sb.Append ("'field' ");
590 if ((targets & AttributeTargets.Interface) != 0)
591 sb.Append ("'interface' ");
593 if ((targets & AttributeTargets.Method) != 0)
594 sb.Append ("'method' ");
596 if ((targets & AttributeTargets.Module) != 0)
597 sb.Append ("'module' ");
599 if ((targets & AttributeTargets.Parameter) != 0)
600 sb.Append ("'parameter' ");
602 if ((targets & AttributeTargets.Property) != 0)
603 sb.Append ("'property' ");
605 if ((targets & AttributeTargets.ReturnValue) != 0)
606 sb.Append ("'return' ");
608 if ((targets & AttributeTargets.Struct) != 0)
609 sb.Append ("'struct' ");
611 return sb.ToString ();
615 public static void Error_AttributeNotValidForElement (Attribute a, Location loc)
618 592, loc, "Attribute '" + a.Name +
619 "' is not valid on this declaration type. " +
620 "It is valid on " + GetValidTargets (a) + "declarations only.");
625 /// Returns AttributeUsage attribute for this type
627 public AttributeUsageAttribute GetAttributeUsage ()
629 AttributeUsageAttribute ua = usage_attr_cache [Type] as AttributeUsageAttribute;
633 Class attr_class = TypeManager.LookupClass (Type);
635 if (attr_class == null) {
636 object[] usage_attr = Type.GetCustomAttributes (TypeManager.attribute_usage_type, true);
637 ua = (AttributeUsageAttribute)usage_attr [0];
638 usage_attr_cache.Add (Type, ua);
642 return attr_class.AttributeUsage;
647 // This pulls the condition name out of a Conditional attribute
649 public string Conditional_GetConditionName ()
652 // So we have a Conditional, pull the data out.
654 if (Arguments == null || Arguments [0] == null){
655 Error_AttributeConstructorMismatch ();
659 ArrayList pos_args = (ArrayList) Arguments [0];
660 if (pos_args.Count != 1){
661 Error_AttributeConstructorMismatch ();
665 Argument arg = (Argument) pos_args [0];
666 if (!(arg.Expr is StringConstant)){
667 Error_AttributeConstructorMismatch ();
671 return ((StringConstant) arg.Expr).Value;
675 // This pulls the obsolete message and error flag out of an Obsolete attribute
677 public string Obsolete_GetObsoleteMessage (out bool is_error)
681 // So we have an Obsolete, pull the data out.
683 if (Arguments == null || Arguments [0] == null)
686 ArrayList pos_args = (ArrayList) Arguments [0];
687 if (pos_args.Count == 0)
689 else if (pos_args.Count > 2){
690 Error_AttributeConstructorMismatch ();
694 Argument arg = (Argument) pos_args [0];
695 if (!(arg.Expr is StringConstant)){
696 Error_AttributeConstructorMismatch ();
700 if (pos_args.Count == 2){
701 Argument arg2 = (Argument) pos_args [1];
702 if (!(arg2.Expr is BoolConstant)){
703 Error_AttributeConstructorMismatch ();
706 is_error = ((BoolConstant) arg2.Expr).Value;
709 return ((StringConstant) arg.Expr).Value;
712 public string IndexerName_GetIndexerName (EmitContext ec)
714 if (Arguments == null || Arguments [0] == null){
715 Error_AttributeConstructorMismatch ();
718 ArrayList pos_args = (ArrayList) Arguments [0];
719 if (pos_args.Count != 1) {
720 Error_AttributeConstructorMismatch ();
724 Argument arg = (Argument) pos_args [0];
725 if (!arg.Resolve (ec, Location))
728 StringConstant sc = arg.Expr as StringConstant;
730 Error_AttributeConstructorMismatch ();
738 /// Creates the instance of ObsoleteAttribute from this attribute instance
740 public ObsoleteAttribute GetObsoleteAttribute (DeclSpace ds)
742 if (pos_values == null) {
743 EmitContext ec = new EmitContext (ds, ds, Location, null, null, 0, false);
745 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
746 // But because a lot of attribute class code must be rewritten will be better to wait...
750 // Some error occurred
751 if (pos_values == null)
754 if (pos_values.Length == 0)
755 return new ObsoleteAttribute ();
757 if (pos_values.Length == 1)
758 return new ObsoleteAttribute ((string)pos_values [0]);
760 return new ObsoleteAttribute ((string)pos_values [0], (bool)pos_values [1]);
764 /// Returns value of CLSCompliantAttribute contructor parameter but because the method can be called
765 /// before ApplyAttribute. We need to resolve the arguments.
766 /// This situation occurs when class deps is differs from Emit order.
768 public bool GetClsCompliantAttributeValue (DeclSpace ds)
770 if (pos_values == null) {
771 EmitContext ec = new EmitContext (ds, ds, Location, null, null, 0, false);
773 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
774 // But because a lot of attribute class code must be rewritten will be better to wait...
778 // Some error occurred
779 if (pos_values [0] == null)
782 return (bool)pos_values [0];
785 public object GetPositionalValue (int i)
787 return (pos_values == null) ? null : pos_values[i];
790 object GetFieldValue (string name)
793 if (field_info_arr == null)
796 foreach (FieldInfo fi in field_info_arr) {
798 return field_values_arr [i];
804 public UnmanagedMarshal GetMarshal ()
806 object o = GetFieldValue ("ArraySubType");
807 UnmanagedType array_sub_type = o == null ? UnmanagedType.I4 : (UnmanagedType) o;
809 switch (UnmanagedType) {
810 case UnmanagedType.CustomMarshaler:
811 MethodInfo define_custom = typeof (UnmanagedMarshal).GetMethod ("DefineCustom",
812 BindingFlags.Static | BindingFlags.Public);
813 if (define_custom == null)
816 object [] args = new object [4];
817 args [0] = GetFieldValue ("MarshalTypeRef");
818 args [1] = GetFieldValue ("MarshalCookie");
819 args [2] = GetFieldValue ("MarshalType");
820 args [3] = Guid.Empty;
821 return (UnmanagedMarshal) define_custom.Invoke (null, args);
823 case UnmanagedType.LPArray:
824 return UnmanagedMarshal.DefineLPArray (array_sub_type);
826 case UnmanagedType.SafeArray:
827 return UnmanagedMarshal.DefineSafeArray (array_sub_type);
829 case UnmanagedType.ByValArray:
830 return UnmanagedMarshal.DefineByValArray ((int) GetFieldValue ("SizeConst"));
832 case UnmanagedType.ByValTStr:
833 return UnmanagedMarshal.DefineByValTStr ((int) GetFieldValue ("SizeConst"));
836 return UnmanagedMarshal.DefineUnmanagedMarshal (UnmanagedType);
840 public bool IsInternalCall
842 get { return ImplOptions == MethodImplOptions.InternalCall; }
846 /// Emit attribute for Attributable symbol
848 public void Emit (EmitContext ec, Attributable ias, ListDictionary emitted_attr)
850 CustomAttributeBuilder cb = Resolve (ec);
854 AttributeUsageAttribute usage_attr = GetAttributeUsage ();
855 if ((usage_attr.ValidOn & ias.AttributeTargets) == 0) {
856 Error_AttributeNotValidForElement (this, Location);
860 ias.ApplyAttributeBuilder (this, cb);
862 if (!usage_attr.AllowMultiple && emitted_attr.Contains (Target)) {
863 Report.Error (579, Location, "Duplicate '" + Name + "' attribute");
866 emitted_attr [Type] = Target;
868 // Here we are testing attribute arguments for array usage (error 3016)
869 if (ias.IsClsCompliaceRequired (ec.DeclSpace)) {
870 if (Arguments == null)
873 ArrayList pos_args = (ArrayList) Arguments [0];
874 if (pos_args != null) {
875 foreach (Argument arg in pos_args) {
876 // Type is undefined (was error 246)
877 if (arg.Type == null)
880 if (arg.Type.IsArray) {
881 Report.Error_T (3016, Location);
887 if (Arguments.Count < 2)
890 ArrayList named_args = (ArrayList) Arguments [1];
891 foreach (DictionaryEntry de in named_args) {
892 Argument arg = (Argument) de.Value;
894 // Type is undefined (was error 246)
895 if (arg.Type == null)
898 if (arg.Type.IsArray) {
899 Report.Error_T (3016, Location);
906 public object GetValue (EmitContext ec, Constant c, Type target)
908 if (Convert.ImplicitConversionExists (ec, c, target))
909 return c.GetValue ();
911 Convert.Error_CannotImplicitConversion (Location, c.Type, target);
915 public MethodBuilder DefinePInvokeMethod (EmitContext ec, TypeBuilder builder, string name,
916 MethodAttributes flags, Type ret_type, Type [] param_types)
919 // We extract from the attribute the information we need
922 if (Arguments == null) {
923 Console.WriteLine ("Internal error : this is not supposed to happen !");
927 ResolveType (ec, true);
931 ArrayList named_args = new ArrayList ();
933 ArrayList pos_args = (ArrayList) Arguments [0];
934 if (Arguments.Count > 1)
935 named_args = (ArrayList) Arguments [1];
938 string dll_name = null;
940 Argument tmp = (Argument) pos_args [0];
942 if (!tmp.Resolve (ec, Location))
945 if (tmp.Expr is Constant)
946 dll_name = (string) ((Constant) tmp.Expr).GetValue ();
948 Error_AttributeArgumentNotValid (Location);
952 // Now we process the named arguments
953 CallingConvention cc = CallingConvention.Winapi;
954 CharSet charset = CharSet.Ansi;
955 bool preserve_sig = true;
957 bool exact_spelling = false;
959 bool set_last_err = false;
960 string entry_point = null;
962 for (int i = 0; i < named_args.Count; i++) {
964 DictionaryEntry de = (DictionaryEntry) named_args [i];
966 string member_name = (string) de.Key;
967 Argument a = (Argument) de.Value;
969 if (!a.Resolve (ec, Location))
972 Expression member = Expression.MemberLookup (
973 ec, Type, member_name,
974 MemberTypes.Field | MemberTypes.Property,
975 BindingFlags.Public | BindingFlags.Instance,
978 if (member == null || !(member is FieldExpr)) {
979 Error_InvalidNamedArgument (member_name);
983 if (member is FieldExpr) {
984 FieldExpr fe = (FieldExpr) member;
985 FieldInfo fi = fe.FieldInfo;
988 Error_InvalidNamedArgument (member_name);
992 if (a.Expr is Constant) {
993 Constant c = (Constant) a.Expr;
996 if (member_name == "CallingConvention"){
997 object val = GetValue (ec, c, typeof (CallingConvention));
1000 cc = (CallingConvention) val;
1001 } else if (member_name == "CharSet"){
1002 charset = (CharSet) c.GetValue ();
1003 } else if (member_name == "EntryPoint")
1004 entry_point = (string) c.GetValue ();
1005 else if (member_name == "SetLastError")
1006 set_last_err = (bool) c.GetValue ();
1008 else if (member_name == "ExactSpelling")
1009 exact_spelling = (bool) c.GetValue ();
1011 else if (member_name == "PreserveSig")
1012 preserve_sig = (bool) c.GetValue ();
1013 } catch (InvalidCastException){
1014 Error_InvalidNamedArgument (member_name);
1015 Error_AttributeArgumentNotValid (Location);
1018 Error_AttributeArgumentNotValid (Location);
1025 if (entry_point == null)
1028 charset = (CharSet)((int)charset | 0x40);
1030 MethodBuilder mb = builder.DefinePInvokeMethod (
1031 name, dll_name, entry_point, flags | MethodAttributes.HideBySig,
1032 CallingConventions.Standard,
1039 mb.SetImplementationFlags (MethodImplAttributes.PreserveSig);
1044 private Expression GetValue ()
1046 if ((Arguments == null) || (Arguments.Count < 1))
1048 ArrayList al = (ArrayList) Arguments [0];
1049 if ((al == null) || (al.Count < 1))
1051 Argument arg = (Argument) al [0];
1052 if ((arg == null) || (arg.Expr == null))
1057 public string GetString ()
1059 Expression e = GetValue ();
1060 if (e is StringLiteral)
1061 return (e as StringLiteral).Value;
1065 public bool GetBoolean ()
1067 Expression e = GetValue ();
1068 if (e is BoolLiteral)
1069 return (e as BoolLiteral).Value;
1076 /// For global attributes (assembly, module) we need special handling.
1077 /// Attributes can be located in the several files
1079 public class GlobalAttribute: Attribute
1081 public readonly NamespaceEntry ns;
1083 public GlobalAttribute (TypeContainer container, string target, string name, ArrayList args, Location loc):
1084 base (target, name, args, loc)
1086 ns = container.NamespaceEntry;
1089 protected override Type CheckAttributeType (EmitContext ec, bool complain)
1091 NamespaceEntry old = ec.DeclSpace.NamespaceEntry;
1092 if (old == null || old.NS == null || old.NS == Namespace.Root)
1093 ec.DeclSpace.NamespaceEntry = ns;
1094 return base.CheckAttributeType (ec, complain);
1098 public class Attributes {
1099 public ArrayList Attrs;
1101 public Attributes (Attribute a)
1103 Attrs = new ArrayList ();
1107 public Attributes (ArrayList attrs)
1112 public void AddAttributes (ArrayList attrs)
1114 Attrs.AddRange (attrs);
1118 /// Checks whether attribute target is valid for the current element
1120 public void CheckTargets (string[] possible_targets)
1122 foreach (Attribute a in Attrs) {
1123 if (a.Target == null) {
1124 a.Target = possible_targets [0];
1128 if (((IList) possible_targets).Contains (a.Target))
1131 StringBuilder sb = new StringBuilder ();
1132 foreach (string s in possible_targets) {
1136 sb.Remove (sb.Length - 2, 2);
1137 Report.Error_T (657, a.Location, a.Target, sb.ToString ());
1141 private Attribute Search (Type t, EmitContext ec, bool complain)
1143 foreach (Attribute a in Attrs) {
1144 if (a.ResolveType (ec, false) == t)
1150 public Attribute Search (Type t, EmitContext ec)
1152 return Search (t, ec, true);
1155 public void Emit (EmitContext ec, Attributable ias)
1157 ListDictionary ld = new ListDictionary ();
1159 foreach (Attribute a in Attrs)
1160 a.Emit (ec, ias, ld);
1163 public bool Contains (Type t, EmitContext ec)
1165 return Search (t, ec) != null;
1168 public Attribute GetClsCompliantAttribute (EmitContext ec)
1170 return Search (TypeManager.cls_compliant_attribute_type, ec, false);
1174 /// Pulls the IndexerName attribute from an Indexer if it exists.
1176 public string ScanForIndexerName (EmitContext ec)
1178 Attribute a = Search (TypeManager.indexer_name_type, ec);
1182 // Remove the attribute from the list
1183 //TODO: It is very close to hack and it can crash here
1186 return a.IndexerName_GetIndexerName (ec);
1192 /// Helper class for attribute verification routine.
1194 sealed class AttributeTester
1196 static PtrHashtable analyzed_types = new PtrHashtable ();
1197 static PtrHashtable analyzed_member_obsolete = new PtrHashtable ();
1199 private AttributeTester ()
1204 /// Returns true if parameters of two compared methods are CLS-Compliant.
1205 /// It tests differing only in ref or out, or in array rank.
1207 public static bool AreOverloadedMethodParamsClsCompliant (Type[] types_a, Type[] types_b)
1209 if (types_a == null || types_b == null)
1212 if (types_a.Length != types_b.Length)
1215 for (int i = 0; i < types_b.Length; ++i) {
1216 Type aType = types_a [i];
1217 Type bType = types_b [i];
1219 if (aType.IsArray && bType.IsArray && aType.GetArrayRank () != bType.GetArrayRank () && aType.GetElementType () == bType.GetElementType ()) {
1223 Type aBaseType = aType;
1224 bool is_either_ref_or_out = false;
1226 if (aType.IsByRef || aType.IsPointer) {
1227 aBaseType = aType.GetElementType ();
1228 is_either_ref_or_out = true;
1231 Type bBaseType = bType;
1232 if (bType.IsByRef || bType.IsPointer)
1234 bBaseType = bType.GetElementType ();
1235 is_either_ref_or_out = !is_either_ref_or_out;
1238 if (aBaseType != bBaseType)
1241 if (is_either_ref_or_out)
1248 /// Goes through all parameters and test if they are CLS-Compliant.
1250 public static bool AreParametersCompliant (Parameter[] fixedParameters, Location loc)
1252 if (fixedParameters == null)
1255 foreach (Parameter arg in fixedParameters) {
1256 if (!AttributeTester.IsClsCompliant (arg.ParameterType)) {
1257 Report.Error_T (3001, loc, arg.GetSignatureForError ());
1266 /// This method tests the CLS compliance of external types. It doesn't test type visibility.
1268 public static bool IsClsCompliant (Type type)
1273 object type_compliance = analyzed_types[type];
1274 if (type_compliance != null)
1275 return type_compliance == TRUE;
1277 if (type.IsPointer) {
1278 analyzed_types.Add (type, null);
1283 if (type.IsArray || type.IsByRef) {
1284 result = IsClsCompliant (TypeManager.GetElementType (type));
1286 result = AnalyzeTypeCompliance (type);
1288 analyzed_types.Add (type, result ? TRUE : FALSE);
1292 static object TRUE = new object ();
1293 static object FALSE = new object ();
1296 /// Non-hierarchical CLS Compliance analyzer
1298 public static bool IsComplianceRequired (MemberInfo mi, DeclSpace ds)
1300 DeclSpace temp_ds = TypeManager.LookupDeclSpace (mi.DeclaringType);
1302 // Type is external, we can get attribute directly
1303 if (temp_ds == null) {
1304 object[] cls_attribute = mi.GetCustomAttributes (TypeManager.cls_compliant_attribute_type, false);
1305 return (cls_attribute.Length == 1 && ((CLSCompliantAttribute)cls_attribute[0]).IsCompliant);
1309 // Interface doesn't store full name
1310 if (temp_ds is Interface)
1313 tmp_name = String.Concat (temp_ds.Name, ".", mi.Name);
1315 MemberCore mc = temp_ds.GetDefinition (tmp_name) as MemberCore;
1316 return mc.IsClsCompliaceRequired (ds);
1319 public static void VerifyModulesClsCompliance ()
1321 Module[] modules = TypeManager.Modules;
1322 if (modules == null)
1325 // The first module is generated assembly
1326 for (int i = 1; i < modules.Length; ++i) {
1327 Module module = modules [i];
1328 if (!IsClsCompliant (module)) {
1329 Report.Error_T (3013, module.Name);
1335 static bool IsClsCompliant (ICustomAttributeProvider attribute_provider)
1337 object[] CompliantAttribute = attribute_provider.GetCustomAttributes (TypeManager.cls_compliant_attribute_type, false);
1338 if (CompliantAttribute.Length == 0)
1341 return ((CLSCompliantAttribute)CompliantAttribute[0]).IsCompliant;
1344 static bool AnalyzeTypeCompliance (Type type)
1346 DeclSpace ds = TypeManager.LookupDeclSpace (type);
1348 return ds.IsClsCompliaceRequired (ds.Parent);
1351 object[] CompliantAttribute = type.GetCustomAttributes (TypeManager.cls_compliant_attribute_type, false);
1352 if (CompliantAttribute.Length == 0)
1353 return IsClsCompliant (type.Assembly);
1355 return ((CLSCompliantAttribute)CompliantAttribute[0]).IsCompliant;
1359 /// Returns instance of ObsoleteAttribute when member is obsolete
1361 public static ObsoleteAttribute GetMemberObsoleteAttribute (MemberInfo mi)
1363 object type_obsolete = analyzed_member_obsolete [mi];
1364 if (type_obsolete == FALSE)
1367 if (type_obsolete != null)
1368 return (ObsoleteAttribute)type_obsolete;
1370 ObsoleteAttribute oa = System.Attribute.GetCustomAttribute (mi, TypeManager.obsolete_attribute_type, false) as ObsoleteAttribute;
1371 analyzed_member_obsolete.Add (mi, oa == null ? FALSE : oa);
1376 /// Common method for Obsolete error/warning reporting.
1378 public static void Report_ObsoleteMessage (ObsoleteAttribute oa, string member, Location loc)
1381 Report.Error_T (619, loc, member, oa.Message);
1385 if (oa.Message == null) {
1386 Report.Warning_T (612, loc, member);
1389 Report.Warning_T (618, loc, member, oa.Message);