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.Reflection;
16 using System.Reflection.Emit;
17 using System.Runtime.InteropServices;
18 using System.Runtime.CompilerServices;
21 namespace Mono.CSharp {
24 /// Base class for objects that can have Attributes applied to them.
26 public abstract class Attributable {
28 /// Attributes for this type
30 Attributes attributes;
32 public Attributable(Attributes attrs)
37 public Attributes OptAttributes
48 /// Use member-specific procedure to apply attribute @a in @cb to the entity being built in @builder
50 public abstract void ApplyAttributeBuilder (object builder, Attribute a, CustomAttributeBuilder cb);
53 public class Attribute {
54 public readonly string Name;
55 public readonly ArrayList Arguments;
57 public readonly Location Location;
62 // The following are only meaningful when the attribute
63 // being emitted is an AttributeUsage attribute
65 public AttributeTargets Targets;
66 public bool AllowMultiple;
67 public bool Inherited;
69 bool usage_attr = false;
71 public bool UsageAttr {
72 get { return usage_attr; }
75 MethodImplOptions ImplOptions;
76 UnmanagedType UnmanagedType;
77 CustomAttributeBuilder cb;
79 // non-null if named args present after Resolve () is called
80 PropertyInfo [] prop_info_arr;
81 FieldInfo [] field_info_arr;
82 object [] field_values_arr;
83 object [] prop_values_arr;
86 public Attribute (string name, ArrayList args, Location loc)
93 void Error_InvalidNamedArgument (string name)
95 Report.Error (617, Location, "'" + name + "' is not a valid named attribute " +
96 "argument. Named attribute arguments must be fields which are not " +
97 "readonly, static or const, or properties with a set accessor which "+
101 static void Error_AttributeArgumentNotValid (Location loc)
103 Report.Error (182, loc,
104 "An attribute argument must be a constant expression, typeof " +
105 "expression or array creation expression");
108 static void Error_AttributeConstructorMismatch (Location loc)
110 Report.Error (-6, loc,
111 "Could not find a constructor for this argument list.");
115 /// Tries to resolve the type of the attribute. Flags an error if it can't, and complain is true.
117 private Type CheckAttributeType (DeclSpace ds, bool complain) {
118 Type t1 = RootContext.LookupType (ds, Name, true, Location);
120 // FIXME: Shouldn't do this for quoted attributes: [@A]
121 Type t2 = RootContext.LookupType (ds, Name + "Attribute", true, Location);
123 String err0616 = null;
125 if (t1 != null && ! t1.IsSubclassOf (TypeManager.attribute_type)) {
127 err0616 = "'" + Name + "': is not an attribute class";
129 if (t2 != null && ! t2.IsSubclassOf (TypeManager.attribute_type)) {
131 err0616 = (err0616 != null)
132 ? "Neither '" + Name + "' nor '" + Name + "Attribute' is an attribute class"
133 : "'" + Name + "Attribute': is not an attribute class";
136 if (t1 != null && t2 != null) {
137 Report.Error(1614, Location, "'" + Name + "': is ambiguous; "
138 + " use either '@" + Name + "' or '" + Name + "Attribute'");
146 if (err0616 != null) {
147 Report.Error (616, Location, err0616);
152 Report.Error (246, Location,
153 "Could not find attribute '" + Name
154 + "' (are you missing a using directive or an assembly reference ?)");
158 public Type ResolveType (DeclSpace ds, bool complain)
161 Type = CheckAttributeType (ds, complain);
166 /// Validates the guid string
168 bool ValidateGuid (string guid)
174 Report.Error (647, Location, "Format of GUID is invalid: " + guid);
180 // Given an expression, if the expression is a valid attribute-argument-expression
181 // returns an object that can be used to encode it, or null on failure.
183 public static bool GetAttributeArgumentExpression (Expression e, Location loc, out object result)
186 result = ((Constant) e).GetValue ();
188 } else if (e is TypeOf) {
189 result = ((TypeOf) e).TypeArg;
191 } else if (e is ArrayCreation){
192 result = ((ArrayCreation) e).EncodeAsAttribute ();
195 } else if (e is EmptyCast) {
197 if (((EmptyCast) e).Child is Constant) {
198 result = ((Constant) ((EmptyCast)e).Child).GetValue();
204 Error_AttributeArgumentNotValid (loc);
208 public CustomAttributeBuilder Resolve (EmitContext ec)
213 Type = CheckAttributeType (ec.DeclSpace, true);
214 if (oldType == null && Type == null)
216 if (oldType != null && oldType != Type) {
217 Report.Error (-6, Location,
218 "Attribute {0} resolved to different types at different times: {1} vs. {2}",
219 Name, oldType, Type);
223 bool MethodImplAttr = false;
224 bool MarshalAsAttr = false;
225 bool GuidAttr = false;
228 bool DoCompares = true;
231 // If we are a certain special attribute, we
232 // set the information accordingly
235 if (Type == TypeManager.attribute_usage_type)
237 else if (Type == TypeManager.methodimpl_attr_type)
238 MethodImplAttr = true;
239 else if (Type == TypeManager.marshal_as_attr_type)
240 MarshalAsAttr = true;
241 else if (Type == TypeManager.guid_attr_type)
246 // Now we extract the positional and named arguments
248 ArrayList pos_args = new ArrayList ();
249 ArrayList named_args = new ArrayList ();
250 int pos_arg_count = 0;
252 if (Arguments != null) {
253 pos_args = (ArrayList) Arguments [0];
254 if (pos_args != null)
255 pos_arg_count = pos_args.Count;
256 if (Arguments.Count > 1)
257 named_args = (ArrayList) Arguments [1];
260 pos_values = new object [pos_arg_count];
263 // First process positional arguments
267 for (i = 0; i < pos_arg_count; i++) {
268 Argument a = (Argument) pos_args [i];
271 if (!a.Resolve (ec, Location))
277 if (!GetAttributeArgumentExpression (e, Location, out val))
280 pos_values [i] = val;
283 this.Targets = (AttributeTargets) pos_values [0];
284 else if (MethodImplAttr)
285 this.ImplOptions = (MethodImplOptions) pos_values [0];
288 // we will later check the validity of the type
290 if (pos_values [0] is string){
291 if (!ValidateGuid ((string) pos_values [0]))
295 } else if (MarshalAsAttr)
297 (System.Runtime.InteropServices.UnmanagedType) pos_values [0];
302 // Now process named arguments
305 ArrayList field_infos = null;
306 ArrayList prop_infos = null;
307 ArrayList field_values = null;
308 ArrayList prop_values = null;
310 if (named_args.Count > 0) {
311 field_infos = new ArrayList ();
312 prop_infos = new ArrayList ();
313 field_values = new ArrayList ();
314 prop_values = new ArrayList ();
317 Hashtable seen_names = new Hashtable();
319 for (i = 0; i < named_args.Count; i++) {
320 DictionaryEntry de = (DictionaryEntry) named_args [i];
321 string member_name = (string) de.Key;
322 Argument a = (Argument) de.Value;
325 if (seen_names.Contains(member_name)) {
326 Report.Error(643, Location, "'" + member_name + "' duplicate named attribute argument");
329 seen_names.Add(member_name, 1);
331 if (!a.Resolve (ec, Location))
334 Expression member = Expression.MemberLookup (
335 ec, Type, member_name,
336 MemberTypes.Field | MemberTypes.Property,
337 BindingFlags.Public | BindingFlags.Instance,
340 if (member == null || !(member is PropertyExpr || member is FieldExpr)) {
341 Error_InvalidNamedArgument (member_name);
346 if (member is PropertyExpr) {
347 PropertyExpr pe = (PropertyExpr) member;
348 PropertyInfo pi = pe.PropertyInfo;
351 Error_InvalidNamedArgument (member_name);
358 if (e.Type != pi.PropertyType){
359 c = Const.ChangeType (Location, (Constant) e, pi.PropertyType);
365 object o = c.GetValue ();
369 if (member_name == "AllowMultiple")
370 this.AllowMultiple = (bool) o;
371 if (member_name == "Inherited")
372 this.Inherited = (bool) o;
375 } else if (e is TypeOf) {
376 prop_values.Add (((TypeOf) e).TypeArg);
377 } else if (e is ArrayCreation) {
378 prop_values.Add (((ArrayCreation) e).EncodeAsAttribute());
380 Error_AttributeArgumentNotValid (Location);
386 } else if (member is FieldExpr) {
387 FieldExpr fe = (FieldExpr) member;
388 FieldInfo fi = fe.FieldInfo;
391 Error_InvalidNamedArgument (member_name);
396 // Handle charset here, and set the TypeAttributes
399 Constant c = (Constant) e;;
401 if (c.Type != fi.FieldType){
402 c = Const.ChangeType (Location, (Constant) e, fi.FieldType);
407 object value = c.GetValue ();
408 field_values.Add (value);
409 } else if (e is TypeOf) {
410 field_values.Add (((TypeOf) e).TypeArg);
412 Error_AttributeArgumentNotValid (Location);
416 field_infos.Add (fi);
420 Expression mg = Expression.MemberLookup (
421 ec, Type, ".ctor", MemberTypes.Constructor,
422 BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly,
426 Error_AttributeConstructorMismatch (Location);
430 MethodBase constructor = Invocation.OverloadResolve (
431 ec, (MethodGroupExpr) mg, pos_args, Location);
433 if (constructor == null) {
434 Error_AttributeConstructorMismatch (Location);
439 // Now we perform some checks on the positional args as they
440 // cannot be null for a constructor which expects a parameter
444 ParameterData pd = Invocation.GetParameterData (constructor);
446 int group_in_params_array = Int32.MaxValue;
448 if (pc > 0 && pd.ParameterModifier (pc-1) == Parameter.Modifier.PARAMS)
449 group_in_params_array = pc-1;
451 for (int j = 0; j < pos_arg_count; ++j) {
452 Argument a = (Argument) pos_args [j];
454 if (a.Expr is NullLiteral && pd.ParameterType (j) == TypeManager.object_type) {
455 Error_AttributeArgumentNotValid (Location);
459 if (j < group_in_params_array)
462 if (j == group_in_params_array){
463 object v = pos_values [j];
464 int count = pos_arg_count - j;
466 object [] array = new object [count];
467 pos_values [j] = array;
470 object [] array = (object []) pos_values [group_in_params_array];
472 array [j - group_in_params_array] = pos_values [j];
477 // Adjust the size of the pos_values if it had params
479 if (group_in_params_array != Int32.MaxValue){
480 int argc = group_in_params_array+1;
481 object [] new_pos_values = new object [argc];
483 for (int p = 0; p < argc; p++)
484 new_pos_values [p] = pos_values [p];
485 pos_values = new_pos_values;
489 if (named_args.Count > 0) {
490 prop_info_arr = new PropertyInfo [prop_infos.Count];
491 field_info_arr = new FieldInfo [field_infos.Count];
492 field_values_arr = new object [field_values.Count];
493 prop_values_arr = new object [prop_values.Count];
495 field_infos.CopyTo (field_info_arr, 0);
496 field_values.CopyTo (field_values_arr, 0);
498 prop_values.CopyTo (prop_values_arr, 0);
499 prop_infos.CopyTo (prop_info_arr, 0);
501 cb = new CustomAttributeBuilder (
502 (ConstructorInfo) constructor, pos_values,
503 prop_info_arr, prop_values_arr,
504 field_info_arr, field_values_arr);
507 cb = new CustomAttributeBuilder (
508 (ConstructorInfo) constructor, pos_values);
509 } catch (NullReferenceException) {
511 // Don't know what to do here
514 -101, Location, "NullReferenceException while trying to create attribute." +
515 "Something's wrong!");
516 } catch (Exception e) {
519 // using System.ComponentModel;
520 // [DefaultValue (CollectionChangeAction.Add)]
521 // class X { static void Main () {} }
525 "The compiler can not encode this attribute in .NET due to\n" +
526 "\ta bug in the .NET runtime. Try the Mono runtime.\nThe error was: " + e.Message);
533 /// Get a string containing a list of valid targets for the attribute 'attr'
535 static string GetValidTargets (Attribute attr)
537 StringBuilder sb = new StringBuilder ();
538 AttributeTargets targets = 0;
540 TypeContainer a = TypeManager.LookupAttr (attr.Type);
544 System.Attribute [] attrs = null;
547 attrs = System.Attribute.GetCustomAttributes (attr.Type);
550 Report.Error (-20, attr.Location, "Cannot find attribute type " + attr.Name +
551 " (maybe you forgot to set the usage using the" +
552 " AttributeUsage attribute ?).");
556 foreach (System.Attribute tmp in attrs)
557 if (tmp is AttributeUsageAttribute) {
558 targets = ((AttributeUsageAttribute) tmp).ValidOn;
565 if ((targets & AttributeTargets.Assembly) != 0)
566 sb.Append ("'assembly' ");
568 if ((targets & AttributeTargets.Class) != 0)
569 sb.Append ("'class' ");
571 if ((targets & AttributeTargets.Constructor) != 0)
572 sb.Append ("'constructor' ");
574 if ((targets & AttributeTargets.Delegate) != 0)
575 sb.Append ("'delegate' ");
577 if ((targets & AttributeTargets.Enum) != 0)
578 sb.Append ("'enum' ");
580 if ((targets & AttributeTargets.Event) != 0)
581 sb.Append ("'event' ");
583 if ((targets & AttributeTargets.Field) != 0)
584 sb.Append ("'field' ");
586 if ((targets & AttributeTargets.Interface) != 0)
587 sb.Append ("'interface' ");
589 if ((targets & AttributeTargets.Method) != 0)
590 sb.Append ("'method' ");
592 if ((targets & AttributeTargets.Module) != 0)
593 sb.Append ("'module' ");
595 if ((targets & AttributeTargets.Parameter) != 0)
596 sb.Append ("'parameter' ");
598 if ((targets & AttributeTargets.Property) != 0)
599 sb.Append ("'property' ");
601 if ((targets & AttributeTargets.ReturnValue) != 0)
602 sb.Append ("'return value' ");
604 if ((targets & AttributeTargets.Struct) != 0)
605 sb.Append ("'struct' ");
607 return sb.ToString ();
611 public static void Error_AttributeNotValidForElement (Attribute a, Location loc)
614 592, loc, "Attribute '" + a.Name +
615 "' is not valid on this declaration type. " +
616 "It is valid on " + GetValidTargets (a) + "declarations only.");
620 /// Ensure that Attribute 'a' is being applied to the right language element (target)
622 public static bool CheckAttributeTarget (Attribute a, object element)
624 TypeContainer attr = TypeManager.LookupAttr (a.Type);
625 AttributeTargets targets = 0;
628 System.Attribute [] attrs = null;
631 attrs = System.Attribute.GetCustomAttributes (a.Type);
634 Report.Error (-20, a.Location, "Cannot find attribute type " + a.Name +
635 " (maybe you forgot to set the usage using the" +
636 " AttributeUsage attribute ?).");
640 foreach (System.Attribute tmp in attrs)
641 if (tmp is AttributeUsageAttribute) {
642 targets = ((AttributeUsageAttribute) tmp).ValidOn;
646 targets = attr.Targets;
649 if (element is Class) return ((targets & AttributeTargets.Class) != 0);
650 if (element is Struct) return ((targets & AttributeTargets.Struct) != 0);
651 if (element is Constructor) return ((targets & AttributeTargets.Constructor) != 0);
652 if (element is Delegate) return ((targets & AttributeTargets.Delegate) != 0);
653 if (element is Enum) return ((targets & AttributeTargets.Enum) != 0);
654 if (element is Event) return ((targets & AttributeTargets.Event) != 0);
656 || element is FieldBuilder) return ((targets & AttributeTargets.Field) != 0);
657 if (element is Interface) return ((targets & AttributeTargets.Interface) != 0);
658 if (element is Method
659 || element is Operator
660 || element is Accessor) return ((targets & AttributeTargets.Method) != 0);
661 if (element is ParameterBase) return ((targets & (AttributeTargets.Parameter
662 | AttributeTargets.ReturnValue)) != 0);
663 if (element is Property
664 || element is Indexer
665 || element is Accessor) return ((targets & AttributeTargets.Property) != 0);
666 if (element is AssemblyClass) return ((targets & AttributeTargets.Assembly) != 0);
667 if (element is ModuleClass) return ((targets & AttributeTargets.Module) != 0);
672 // This method should be invoked to pull the IndexerName attribute from an
673 // Indexer if it exists.
675 public static string ScanForIndexerName (EmitContext ec, Attributes opt_attrs)
677 if (opt_attrs == null)
679 if (opt_attrs.AttributeSections == null)
682 foreach (AttributeSection asec in opt_attrs.AttributeSections) {
683 if (asec.Attributes == null)
686 foreach (Attribute a in asec.Attributes){
687 if (a.ResolveType (ec.DeclSpace, true) == null)
690 if (a.Type != TypeManager.indexer_name_type)
694 // So we have found an IndexerName, pull the data out.
696 if (a.Arguments == null || a.Arguments [0] == null){
697 Error_AttributeConstructorMismatch (a.Location);
700 ArrayList pos_args = (ArrayList) a.Arguments [0];
701 if (pos_args.Count == 0){
702 Error_AttributeConstructorMismatch (a.Location);
706 Argument arg = (Argument) pos_args [0];
707 if (!arg.Resolve (ec, a.Location))
710 Expression e = arg.Expr;
711 if (!(e is StringConstant)){
712 Error_AttributeConstructorMismatch (a.Location);
717 // Remove the attribute from the list
719 asec.Attributes.Remove (a);
721 return (((StringConstant) e).Value);
728 // This pulls the condition name out of a Conditional attribute
730 public string Conditional_GetConditionName ()
733 // So we have a Conditional, pull the data out.
735 if (Arguments == null || Arguments [0] == null){
736 Error_AttributeConstructorMismatch (Location);
740 ArrayList pos_args = (ArrayList) Arguments [0];
741 if (pos_args.Count != 1){
742 Error_AttributeConstructorMismatch (Location);
746 Argument arg = (Argument) pos_args [0];
747 if (!(arg.Expr is StringConstant)){
748 Error_AttributeConstructorMismatch (Location);
752 return ((StringConstant) arg.Expr).Value;
756 // This pulls the obsolete message and error flag out of an Obsolete attribute
758 public string Obsolete_GetObsoleteMessage (out bool is_error)
762 // So we have an Obsolete, pull the data out.
764 if (Arguments == null || Arguments [0] == null)
767 ArrayList pos_args = (ArrayList) Arguments [0];
768 if (pos_args.Count == 0)
770 else if (pos_args.Count > 2){
771 Error_AttributeConstructorMismatch (Location);
775 Argument arg = (Argument) pos_args [0];
776 if (!(arg.Expr is StringConstant)){
777 Error_AttributeConstructorMismatch (Location);
781 if (pos_args.Count == 2){
782 Argument arg2 = (Argument) pos_args [1];
783 if (!(arg2.Expr is BoolConstant)){
784 Error_AttributeConstructorMismatch (Location);
787 is_error = ((BoolConstant) arg2.Expr).Value;
790 return ((StringConstant) arg.Expr).Value;
794 /// Returns value of CLSCompliantAttribute contructor parameter but because the method can be called
795 /// before ApplyAttribute. We need to resolve the arguments.
796 /// This situation occurs when class deps is differs from Emit order.
798 public bool GetClsCompliantAttributeValue (DeclSpace ds)
800 if (pos_values == null) {
801 EmitContext ec = new EmitContext (ds, ds, Location, null, null, 0, false);
803 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
804 // But because a lot of attribute class code must be rewritten will be better to wait...
808 // Some error occurred
809 if (pos_values [0] == null)
812 return (bool)pos_values [0];
815 object GetFieldValue (string name)
818 if (field_info_arr == null)
821 foreach (FieldInfo fi in field_info_arr) {
823 return field_values_arr [i];
829 public UnmanagedMarshal GetMarshal ()
831 object o = GetFieldValue ("ArraySubType");
832 UnmanagedType array_sub_type = o == null ? UnmanagedType.I4 : (UnmanagedType) o;
834 switch (UnmanagedType) {
835 case UnmanagedType.CustomMarshaler:
836 MethodInfo define_custom = typeof (UnmanagedMarshal).GetMethod ("DefineCustom",
837 BindingFlags.Static | BindingFlags.Public);
838 if (define_custom == null)
841 object [] args = new object [4];
842 args [0] = GetFieldValue ("MarshalTypeRef");
843 args [1] = GetFieldValue ("MarshalCookie");
844 args [2] = GetFieldValue ("MarshalType");
845 args [3] = Guid.Empty;
846 return (UnmanagedMarshal) define_custom.Invoke (null, args);
848 case UnmanagedType.LPArray:
849 return UnmanagedMarshal.DefineLPArray (array_sub_type);
851 case UnmanagedType.SafeArray:
852 return UnmanagedMarshal.DefineSafeArray (array_sub_type);
854 case UnmanagedType.ByValArray:
855 return UnmanagedMarshal.DefineByValArray ((int) GetFieldValue ("SizeConst"));
857 case UnmanagedType.ByValTStr:
858 return UnmanagedMarshal.DefineByValTStr ((int) GetFieldValue ("SizeConst"));
861 return UnmanagedMarshal.DefineUnmanagedMarshal (UnmanagedType);
865 public bool IsInternalCall
867 get { return ImplOptions == MethodImplOptions.InternalCall; }
871 /// Applies the attributes specified on target 'kind' to the `builder'.
873 public static void ApplyAttributes (EmitContext ec, object builder, object kind,
874 Attributes opt_attrs)
876 Type attr_type = null;
878 if (opt_attrs == null)
880 if (opt_attrs.AttributeSections == null)
883 ArrayList emitted_attrs = new ArrayList ();
884 ArrayList emitted_targets = new ArrayList ();
886 foreach (AttributeSection asec in opt_attrs.AttributeSections) {
887 string attr_target = asec.Target;
889 if (asec.Attributes == null)
892 if (attr_target == "return" && !(builder is ParameterBuilder))
895 foreach (Attribute a in asec.Attributes) {
896 Location loc = a.Location;
897 CustomAttributeBuilder cb = a.Resolve (ec);
904 // Perform the check for duplicate attributes
906 if (emitted_attrs.Contains (attr_type) &&
907 emitted_targets.Contains (attr_target) &&
908 !TypeManager.AreMultipleAllowed (attr_type)) {
909 Report.Error (579, loc, "Duplicate '" + a.Name + "' attribute");
913 if (!CheckAttributeTarget (a, kind)) {
914 Error_AttributeNotValidForElement (a, loc);
918 if (kind is Attributable) {
919 Attributable able = kind as Attributable;
920 able.ApplyAttributeBuilder (builder, a, cb);
922 else if (kind is IAttributeSupport) {
923 IAttributeSupport attributeSupport = kind as IAttributeSupport;
924 attributeSupport.SetCustomAttribute (cb);
926 else if (kind is FieldBuilder) {
927 // This is used only for enumerated constants
929 if (attr_type == TypeManager.marshal_as_attr_type) {
930 UnmanagedMarshal marshal = a.GetMarshal ();
931 if (marshal == null) {
932 Report.Warning (-24, loc,
933 "The Microsoft Runtime cannot set this marshal info. " +
934 "Please use the Mono runtime instead.");
936 ((FieldBuilder) builder).SetMarshal (marshal);
939 ((FieldBuilder) builder).SetCustomAttribute (cb);
943 throw new Exception ("" + loc + ": Error applying Attribute " + a.Type
944 + " to unknown kind " + kind);
949 // Once an attribute type has been emitted once we
950 // keep track of the info to prevent multiple occurences
951 // for attributes which do not explicitly allow it
953 if (!emitted_attrs.Contains (attr_type))
954 emitted_attrs.Add (attr_type);
957 // We keep of this target-wise and so emitted targets
960 if (!emitted_targets.Contains (attr_target))
961 emitted_targets.Add (attr_target);
965 // Here we are testing attribute arguments for array usage (error 3016)
966 DeclSpace ds = kind as DeclSpace;
967 if ((ds != null && ds.IsClsCompliaceRequired (ds)) ||
968 (kind is AssemblyClass && CodeGen.Assembly.IsClsCompliant)) {
970 foreach (AttributeSection asec in opt_attrs.AttributeSections) {
971 foreach (Attribute a in asec.Attributes) {
972 if (a.Arguments == null)
975 ArrayList pos_args = (ArrayList) a.Arguments [0];
976 if (pos_args != null) {
977 foreach (Argument arg in pos_args) {
978 // Type is undefined (was error 246)
979 if (arg.Type == null)
982 if (arg.Type.IsArray) {
983 Report.Error_T (3016, a.Location);
989 if (a.Arguments.Count < 2)
992 ArrayList named_args = (ArrayList) a.Arguments [1];
993 foreach (DictionaryEntry de in named_args) {
994 Argument arg = (Argument) de.Value;
996 // Type is undefined (was error 246)
997 if (arg.Type == null)
1000 if (arg.Type.IsArray)
1002 Report.Error_T (3016, a.Location);
1012 public object GetValue (EmitContext ec, Constant c, Type target)
1014 if (Convert.ImplicitConversionExists (ec, c, target))
1015 return c.GetValue ();
1017 Convert.Error_CannotImplicitConversion (Location, c.Type, target);
1021 public MethodBuilder DefinePInvokeMethod (EmitContext ec, TypeBuilder builder, string name,
1022 MethodAttributes flags, Type ret_type, Type [] param_types)
1025 // We extract from the attribute the information we need
1028 if (Arguments == null) {
1029 Console.WriteLine ("Internal error : this is not supposed to happen !");
1033 ResolveType (ec.DeclSpace, true);
1037 ArrayList named_args = new ArrayList ();
1039 ArrayList pos_args = (ArrayList) Arguments [0];
1040 if (Arguments.Count > 1)
1041 named_args = (ArrayList) Arguments [1];
1044 string dll_name = null;
1046 Argument tmp = (Argument) pos_args [0];
1048 if (!tmp.Resolve (ec, Location))
1051 if (tmp.Expr is Constant)
1052 dll_name = (string) ((Constant) tmp.Expr).GetValue ();
1054 Error_AttributeArgumentNotValid (Location);
1058 // Now we process the named arguments
1059 CallingConvention cc = CallingConvention.Winapi;
1060 CharSet charset = CharSet.Ansi;
1061 bool preserve_sig = true;
1063 bool exact_spelling = false;
1065 bool set_last_err = false;
1066 string entry_point = null;
1068 for (int i = 0; i < named_args.Count; i++) {
1070 DictionaryEntry de = (DictionaryEntry) named_args [i];
1072 string member_name = (string) de.Key;
1073 Argument a = (Argument) de.Value;
1075 if (!a.Resolve (ec, Location))
1078 Expression member = Expression.MemberLookup (
1079 ec, Type, member_name,
1080 MemberTypes.Field | MemberTypes.Property,
1081 BindingFlags.Public | BindingFlags.Instance,
1084 if (member == null || !(member is FieldExpr)) {
1085 Error_InvalidNamedArgument (member_name);
1089 if (member is FieldExpr) {
1090 FieldExpr fe = (FieldExpr) member;
1091 FieldInfo fi = fe.FieldInfo;
1093 if (fi.IsInitOnly) {
1094 Error_InvalidNamedArgument (member_name);
1098 if (a.Expr is Constant) {
1099 Constant c = (Constant) a.Expr;
1102 if (member_name == "CallingConvention"){
1103 object val = GetValue (ec, c, typeof (CallingConvention));
1106 cc = (CallingConvention) val;
1107 } else if (member_name == "CharSet"){
1108 charset = (CharSet) c.GetValue ();
1109 } else if (member_name == "EntryPoint")
1110 entry_point = (string) c.GetValue ();
1111 else if (member_name == "SetLastError")
1112 set_last_err = (bool) c.GetValue ();
1114 else if (member_name == "ExactSpelling")
1115 exact_spelling = (bool) c.GetValue ();
1117 else if (member_name == "PreserveSig")
1118 preserve_sig = (bool) c.GetValue ();
1119 } catch (InvalidCastException){
1120 Error_InvalidNamedArgument (member_name);
1121 Error_AttributeArgumentNotValid (Location);
1124 Error_AttributeArgumentNotValid (Location);
1131 if (entry_point == null)
1134 charset = (CharSet)((int)charset | 0x40);
1136 MethodBuilder mb = builder.DefinePInvokeMethod (
1137 name, dll_name, entry_point, flags | MethodAttributes.HideBySig,
1138 CallingConventions.Standard,
1145 mb.SetImplementationFlags (MethodImplAttributes.PreserveSig);
1150 private Expression GetValue ()
1152 if ((Arguments == null) || (Arguments.Count < 1))
1154 ArrayList al = (ArrayList) Arguments [0];
1155 if ((al == null) || (al.Count < 1))
1157 Argument arg = (Argument) al [0];
1158 if ((arg == null) || (arg.Expr == null))
1163 public string GetString ()
1165 Expression e = GetValue ();
1166 if (e is StringLiteral)
1167 return (e as StringLiteral).Value;
1171 public bool GetBoolean ()
1173 Expression e = GetValue ();
1174 if (e is BoolLiteral)
1175 return (e as BoolLiteral).Value;
1180 public class AttributeSection {
1181 public readonly string Target;
1182 public readonly ArrayList Attributes;
1184 public AttributeSection (string target, ArrayList attrs)
1192 public class Attributes {
1193 public ArrayList AttributeSections;
1195 public Attributes (AttributeSection a)
1197 AttributeSections = new ArrayList ();
1198 AttributeSections.Add (a);
1202 public void AddAttributeSection (AttributeSection a)
1204 if (a != null && !AttributeSections.Contains (a))
1205 AttributeSections.Add (a);
1208 public Attribute Search (Type t, DeclSpace ds)
1210 foreach (AttributeSection attr_section in AttributeSections){
1211 foreach (Attribute a in attr_section.Attributes){
1212 if (a.ResolveType (ds, false) == t)
1219 public bool Contains (Type t, DeclSpace ds)
1221 return Search (t, ds) != null;
1224 public Attribute GetClsCompliantAttribute (DeclSpace ds)
1226 return Search (TypeManager.cls_compliant_attribute_type, ds);
1230 public interface IAttributeSupport
1232 void SetCustomAttribute (CustomAttributeBuilder customBuilder);
1236 /// Helper class for attribute verification routine.
1238 sealed class AttributeTester
1240 static PtrHashtable analyzed_types = new PtrHashtable ();
1242 private AttributeTester ()
1247 /// Returns true if parameters of two compared methods are CLS-Compliant.
1248 /// It tests differing only in ref or out, or in array rank.
1250 public static bool AreOverloadedMethodParamsClsCompliant (Type[] types_a, Type[] types_b)
1252 if (types_a == null || types_b == null)
1255 if (types_a.Length != types_b.Length)
1258 for (int i = 0; i < types_b.Length; ++i) {
1259 Type aType = types_a [i];
1260 Type bType = types_b [i];
1262 if (aType.IsArray && bType.IsArray && aType.GetArrayRank () != bType.GetArrayRank () && aType.GetElementType () == bType.GetElementType ()) {
1266 Type aBaseType = aType;
1267 bool is_either_ref_or_out = false;
1269 if (aType.IsByRef || aType.IsPointer) {
1270 aBaseType = aType.GetElementType ();
1271 is_either_ref_or_out = true;
1274 Type bBaseType = bType;
1275 if (bType.IsByRef || bType.IsPointer)
1277 bBaseType = bType.GetElementType ();
1278 is_either_ref_or_out = !is_either_ref_or_out;
1281 if (aBaseType != bBaseType)
1284 if (is_either_ref_or_out)
1291 /// Goes through all parameters and test if they are CLS-Compliant.
1293 public static bool AreParametersCompliant (Parameter[] fixedParameters, Location loc)
1295 if (fixedParameters == null)
1298 foreach (Parameter arg in fixedParameters) {
1299 if (!AttributeTester.IsClsCompliant (arg.ParameterType)) {
1300 Report.Error_T (3001, loc, arg.GetSignatureForError ());
1309 /// This method tests the CLS compliance of external types. It doesn't test type visibility.
1311 public static bool IsClsCompliant (Type type)
1316 object type_compliance = analyzed_types[type];
1317 if (type_compliance != null)
1318 return type_compliance == TRUE;
1320 if (type.IsPointer) {
1321 analyzed_types.Add (type, null);
1326 if (type.IsArray || type.IsByRef) {
1327 result = IsClsCompliant (TypeManager.GetElementType (type));
1329 result = AnalyzeTypeCompliance (type);
1331 analyzed_types.Add (type, result ? TRUE : FALSE);
1335 static object TRUE = new object ();
1336 static object FALSE = new object ();
1339 /// Non-hierarchical CLS Compliance analyzer
1341 public static bool IsComplianceRequired (MemberInfo mi, DeclSpace ds)
1343 DeclSpace temp_ds = TypeManager.LookupDeclSpace (mi.DeclaringType);
1345 // Type is external, we can get attribute directly
1346 if (temp_ds == null) {
1347 object[] cls_attribute = mi.GetCustomAttributes (TypeManager.cls_compliant_attribute_type, false);
1348 return (cls_attribute.Length == 1 && ((CLSCompliantAttribute)cls_attribute[0]).IsCompliant);
1352 // Interface doesn't store full name
1353 if (temp_ds is Interface)
1356 tmp_name = String.Concat (temp_ds.Name, ".", mi.Name);
1358 MemberCore mc = temp_ds.GetDefinition (tmp_name) as MemberCore;
1359 return mc.IsClsCompliaceRequired (ds);
1362 public static void VerifyModulesClsCompliance ()
1364 Module[] modules = TypeManager.Modules;
1365 if (modules == null)
1368 // The first module is generated assembly
1369 for (int i = 1; i < modules.Length; ++i) {
1370 Module module = modules [i];
1371 if (!IsClsCompliant (module)) {
1372 Report.Error_T (3013, module.Name);
1378 static bool IsClsCompliant (ICustomAttributeProvider attribute_provider)
1380 object[] CompliantAttribute = attribute_provider.GetCustomAttributes (TypeManager.cls_compliant_attribute_type, false);
1381 if (CompliantAttribute.Length == 0)
1384 return ((CLSCompliantAttribute)CompliantAttribute[0]).IsCompliant;
1387 static bool AnalyzeTypeCompliance (Type type)
1389 DeclSpace ds = TypeManager.LookupDeclSpace (type);
1391 return ds.IsClsCompliaceRequired (ds.Parent);
1394 object[] CompliantAttribute = type.GetCustomAttributes (TypeManager.cls_compliant_attribute_type, false);
1395 if (CompliantAttribute.Length == 0)
1396 return IsClsCompliant (type.Assembly);
1398 return ((CLSCompliantAttribute)CompliantAttribute[0]).IsCompliant;