2 // attribute.cs: Attribute Handler
4 // Author: Ravi Pratap (ravi@ximian.com)
5 // Marek Safar (marek.safar@seznam.cz)
7 // Licensed under the terms of the GNU GPL
9 // (C) 2001 Ximian, Inc (http://www.ximian.com)
14 using System.Diagnostics;
15 using System.Collections;
16 using System.Collections.Specialized;
17 using System.Reflection;
18 using System.Reflection.Emit;
19 using System.Runtime.InteropServices;
20 using System.Runtime.CompilerServices;
23 namespace Mono.CSharp {
26 /// Base class for objects that can have Attributes applied to them.
28 public abstract class Attributable {
30 /// Attributes for this type
32 Attributes attributes;
34 public Attributable(Attributes attrs)
37 if (attributes != null)
38 attributes.CheckTargets (this);
41 public Attributes OptAttributes
48 if (attributes != null)
49 attributes.CheckTargets (this);
54 /// Use member-specific procedure to apply attribute @a in @cb to the entity being built in @builder
56 public abstract void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb);
59 /// Returns one AttributeTarget for this element.
61 public abstract AttributeTargets AttributeTargets { get; }
63 public abstract bool IsClsCompliaceRequired (DeclSpace ds);
66 /// Gets list of valid attribute targets for explicit target declaration.
67 /// The first array item is default target. Don't break this rule.
69 public abstract string[] ValidAttributeTargets { get; }
72 public class Attribute {
73 public readonly string ExplicitTarget;
74 public AttributeTargets Target;
76 public readonly string Name;
77 public readonly ArrayList Arguments;
79 public readonly Location Location;
83 // Is non-null if type is AttributeUsageAttribute
84 AttributeUsageAttribute usage_attribute;
86 public AttributeUsageAttribute UsageAttribute {
88 return usage_attribute;
92 MethodImplOptions ImplOptions;
93 UnmanagedType UnmanagedType;
94 CustomAttributeBuilder cb;
96 // non-null if named args present after Resolve () is called
97 PropertyInfo [] prop_info_arr;
98 FieldInfo [] field_info_arr;
99 object [] field_values_arr;
100 object [] prop_values_arr;
101 object [] pos_values;
103 static PtrHashtable usage_attr_cache = new PtrHashtable ();
105 public Attribute (string target, string name, ArrayList args, Location loc)
110 ExplicitTarget = target;
113 void Error_InvalidNamedArgument (string name)
115 Report.Error (617, Location, "'" + name + "' is not a valid named attribute " +
116 "argument. Named attribute arguments must be fields which are not " +
117 "readonly, static or const, or read-write properties which are not static.");
120 static void Error_AttributeArgumentNotValid (Location loc)
122 Report.Error (182, loc,
123 "An attribute argument must be a constant expression, typeof " +
124 "expression or array creation expression");
127 static void Error_TypeParameterInAttribute (Location loc)
130 -202, loc, "Can not use a type parameter in an attribute");
133 void Error_AttributeConstructorMismatch ()
135 Report.Error (-6, Location,
136 "Could not find a constructor for this argument list.");
140 /// Tries to resolve the type of the attribute. Flags an error if it can't, and complain is true.
142 protected virtual Type CheckAttributeType (EmitContext ec, bool complain)
144 TypeExpr t1 = RootContext.LookupType (ec.DeclSpace, Name, true, Location);
145 // FIXME: Shouldn't do this for quoted attributes: [@A]
146 TypeExpr t2 = RootContext.LookupType (ec.DeclSpace, Name + "Attribute", true, Location);
148 String err0616 = null;
149 if (t1 != null && ! t1.IsAttribute) {
151 err0616 = "'" + Name + "': is not an attribute class";
153 if (t2 != null && ! t2.IsAttribute) {
155 err0616 = (err0616 != null)
156 ? "Neither '" + Name + "' nor '" + Name + "Attribute' is an attribute class"
157 : "'" + Name + "Attribute': is not an attribute class";
160 if (t1 != null && t2 != null) {
161 Report.Error(1614, Location, "'" + Name + "': is ambiguous; "
162 + " use either '@" + Name + "' or '" + Name + "Attribute'");
166 return t1.ResolveType (ec);
168 return t2.ResolveType (ec);
169 if (err0616 != null) {
170 Report.Error (616, Location, err0616);
175 Report.Error (246, Location,
176 "Could not find attribute '" + Name
177 + "' (are you missing a using directive or an assembly reference ?)");
181 public Type ResolveType (EmitContext ec, bool complain)
184 Type = CheckAttributeType (ec, complain);
189 /// Validates the guid string
191 bool ValidateGuid (string guid)
197 Report.Error (647, Location, "Format of GUID is invalid: " + guid);
202 string GetFullMemberName (string member)
204 return Type.FullName + '.' + member;
208 // Given an expression, if the expression is a valid attribute-argument-expression
209 // returns an object that can be used to encode it, or null on failure.
211 public static bool GetAttributeArgumentExpression (Expression e, Location loc, Type arg_type, out object result)
213 if (e is EnumConstant) {
214 if (RootContext.StdLib)
215 result = ((EnumConstant)e).GetValueAsEnumType ();
217 result = ((EnumConstant)e).GetValue ();
222 Constant constant = e as Constant;
223 if (constant != null) {
224 if (e.Type != arg_type) {
225 constant = Const.ChangeType (loc, constant, arg_type);
226 if (constant == null) {
228 Error_AttributeArgumentNotValid (loc);
232 result = constant.GetValue ();
234 } else if (e is TypeOf) {
235 result = ((TypeOf) e).TypeArg;
237 } else if (e is ArrayCreation){
238 result = ((ArrayCreation) e).EncodeAsAttribute ();
241 } else if (e is EmptyCast) {
242 Expression child = ((EmptyCast)e).Child;
243 return GetAttributeArgumentExpression (child, loc, child.Type, out result);
247 Error_AttributeArgumentNotValid (loc);
251 public CustomAttributeBuilder Resolve (EmitContext ec)
256 Type = CheckAttributeType (ec, true);
258 if (oldType == null && Type == null)
260 if (oldType != null && oldType != Type){
261 Report.Error (-27, Location,
262 "Attribute {0} resolved to different types at different times: {1} vs. {2}",
263 Name, oldType, Type);
267 if (Type.IsAbstract) {
268 Report.Error (653, Location, "Cannot apply attribute class '{0}' because it is abstract", Name);
272 bool MethodImplAttr = false;
273 bool MarshalAsAttr = false;
274 bool GuidAttr = false;
275 bool usage_attr = false;
277 bool DoCompares = true;
280 // If we are a certain special attribute, we
281 // set the information accordingly
284 if (Type == TypeManager.attribute_usage_type)
286 else if (Type == TypeManager.methodimpl_attr_type)
287 MethodImplAttr = true;
288 else if (Type == TypeManager.marshal_as_attr_type)
289 MarshalAsAttr = true;
290 else if (Type == TypeManager.guid_attr_type)
295 // Now we extract the positional and named arguments
297 ArrayList pos_args = new ArrayList ();
298 ArrayList named_args = new ArrayList ();
299 int pos_arg_count = 0;
301 if (Arguments != null) {
302 pos_args = (ArrayList) Arguments [0];
303 if (pos_args != null)
304 pos_arg_count = pos_args.Count;
305 if (Arguments.Count > 1)
306 named_args = (ArrayList) Arguments [1];
309 pos_values = new object [pos_arg_count];
312 // First process positional arguments
316 for (i = 0; i < pos_arg_count; i++) {
317 Argument a = (Argument) pos_args [i];
320 if (!a.Resolve (ec, Location))
326 if (!GetAttributeArgumentExpression (e, Location, a.Type, out val))
329 pos_values [i] = val;
333 usage_attribute = new AttributeUsageAttribute ((AttributeTargets)val);
334 } else if (MethodImplAttr) {
335 this.ImplOptions = (MethodImplOptions) val;
336 } else if (GuidAttr){
338 // we will later check the validity of the type
341 if (!ValidateGuid ((string) val))
345 } else if (MarshalAsAttr)
347 (System.Runtime.InteropServices.UnmanagedType) val;
352 // Now process named arguments
355 ArrayList field_infos = null;
356 ArrayList prop_infos = null;
357 ArrayList field_values = null;
358 ArrayList prop_values = null;
360 if (named_args.Count > 0) {
361 field_infos = new ArrayList ();
362 prop_infos = new ArrayList ();
363 field_values = new ArrayList ();
364 prop_values = new ArrayList ();
367 Hashtable seen_names = new Hashtable();
369 for (i = 0; i < named_args.Count; i++) {
370 DictionaryEntry de = (DictionaryEntry) named_args [i];
371 string member_name = (string) de.Key;
372 Argument a = (Argument) de.Value;
375 if (seen_names.Contains(member_name)) {
376 Report.Error(643, Location, "'" + member_name + "' duplicate named attribute argument");
379 seen_names.Add(member_name, 1);
381 if (!a.Resolve (ec, Location))
384 Expression member = Expression.MemberLookup (
385 ec, Type, member_name,
386 MemberTypes.Field | MemberTypes.Property,
387 BindingFlags.Public | BindingFlags.Instance,
390 if (member == null) {
391 member = Expression.MemberLookup (ec, Type, member_name,
392 MemberTypes.Field | MemberTypes.Property, BindingFlags.NonPublic | BindingFlags.Instance,
395 if (member != null) {
396 Report.Error (122, Location, "'{0}' is inaccessible due to its protection level", GetFullMemberName (member_name));
401 if (member == null || !(member is PropertyExpr || member is FieldExpr)) {
402 Error_InvalidNamedArgument (member_name);
407 if (e is TypeParameterExpr){
408 Error_TypeParameterInAttribute (Location);
412 if (member is PropertyExpr) {
413 PropertyExpr pe = (PropertyExpr) member;
414 PropertyInfo pi = pe.PropertyInfo;
416 if (!pi.CanWrite || !pi.CanRead) {
417 Report.SymbolRelatedToPreviousError (pi);
418 Error_InvalidNamedArgument (member_name);
423 if (!GetAttributeArgumentExpression (e, Location, pi.PropertyType, out value))
426 if (usage_attribute != null) {
427 if (member_name == "AllowMultiple")
428 usage_attribute.AllowMultiple = (bool) value;
429 if (member_name == "Inherited")
430 usage_attribute.Inherited = (bool) value;
433 prop_values.Add (value);
436 } else if (member is FieldExpr) {
437 FieldExpr fe = (FieldExpr) member;
438 FieldInfo fi = fe.FieldInfo;
441 Error_InvalidNamedArgument (member_name);
446 if (!GetAttributeArgumentExpression (e, Location, fi.FieldType, out value))
449 field_values.Add (value);
451 field_infos.Add (fi);
455 Expression mg = Expression.MemberLookup (
456 ec, Type, ".ctor", MemberTypes.Constructor,
457 BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly,
461 Error_AttributeConstructorMismatch ();
465 MethodBase constructor = Invocation.OverloadResolve (
466 ec, (MethodGroupExpr) mg, pos_args, false, Location);
468 if (constructor == null) {
473 // Now we perform some checks on the positional args as they
474 // cannot be null for a constructor which expects a parameter
478 ParameterData pd = Invocation.GetParameterData (constructor);
480 int group_in_params_array = Int32.MaxValue;
482 if (pc > 0 && pd.ParameterModifier (pc-1) == Parameter.Modifier.PARAMS)
483 group_in_params_array = pc-1;
485 for (int j = 0; j < pos_arg_count; ++j) {
486 Argument a = (Argument) pos_args [j];
488 if (a.Expr is NullLiteral && pd.ParameterType (j) == TypeManager.object_type) {
489 Error_AttributeArgumentNotValid (Location);
493 if (j < group_in_params_array)
496 if (j == group_in_params_array){
497 object v = pos_values [j];
498 int count = pos_arg_count - j;
500 object [] array = new object [count];
501 pos_values [j] = array;
504 object [] array = (object []) pos_values [group_in_params_array];
506 array [j - group_in_params_array] = pos_values [j];
511 // Adjust the size of the pos_values if it had params
513 if (group_in_params_array != Int32.MaxValue){
514 int argc = group_in_params_array+1;
515 object [] new_pos_values = new object [argc];
517 for (int p = 0; p < argc; p++)
518 new_pos_values [p] = pos_values [p];
519 pos_values = new_pos_values;
523 if (named_args.Count > 0) {
524 prop_info_arr = new PropertyInfo [prop_infos.Count];
525 field_info_arr = new FieldInfo [field_infos.Count];
526 field_values_arr = new object [field_values.Count];
527 prop_values_arr = new object [prop_values.Count];
529 field_infos.CopyTo (field_info_arr, 0);
530 field_values.CopyTo (field_values_arr, 0);
532 prop_values.CopyTo (prop_values_arr, 0);
533 prop_infos.CopyTo (prop_info_arr, 0);
535 cb = new CustomAttributeBuilder (
536 (ConstructorInfo) constructor, pos_values,
537 prop_info_arr, prop_values_arr,
538 field_info_arr, field_values_arr);
541 cb = new CustomAttributeBuilder (
542 (ConstructorInfo) constructor, pos_values);
543 } catch (NullReferenceException) {
545 // Don't know what to do here
548 -101, Location, "NullReferenceException while trying to create attribute." +
549 "Something's wrong!");
550 } catch (Exception e) {
553 // using System.ComponentModel;
554 // [DefaultValue (CollectionChangeAction.Add)]
555 // class X { static void Main () {} }
558 -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);
565 /// Get a string containing a list of valid targets for the attribute 'attr'
567 public string GetValidTargets ()
569 StringBuilder sb = new StringBuilder ();
570 AttributeTargets targets = GetAttributeUsage ().ValidOn;
572 if ((targets & AttributeTargets.Assembly) != 0)
573 sb.Append ("'assembly' ");
575 if ((targets & AttributeTargets.Class) != 0)
576 sb.Append ("'class' ");
578 if ((targets & AttributeTargets.Constructor) != 0)
579 sb.Append ("'constructor' ");
581 if ((targets & AttributeTargets.Delegate) != 0)
582 sb.Append ("'delegate' ");
584 if ((targets & AttributeTargets.Enum) != 0)
585 sb.Append ("'enum' ");
587 if ((targets & AttributeTargets.Event) != 0)
588 sb.Append ("'event' ");
590 if ((targets & AttributeTargets.Field) != 0)
591 sb.Append ("'field' ");
593 if ((targets & AttributeTargets.Interface) != 0)
594 sb.Append ("'interface' ");
596 if ((targets & AttributeTargets.Method) != 0)
597 sb.Append ("'method' ");
599 if ((targets & AttributeTargets.Module) != 0)
600 sb.Append ("'module' ");
602 if ((targets & AttributeTargets.Parameter) != 0)
603 sb.Append ("'parameter' ");
605 if ((targets & AttributeTargets.Property) != 0)
606 sb.Append ("'property' ");
608 if ((targets & AttributeTargets.ReturnValue) != 0)
609 sb.Append ("'return' ");
611 if ((targets & AttributeTargets.Struct) != 0)
612 sb.Append ("'struct' ");
614 return sb.ToString ();
619 /// Returns AttributeUsage attribute for this type
621 public AttributeUsageAttribute GetAttributeUsage ()
623 AttributeUsageAttribute ua = usage_attr_cache [Type] as AttributeUsageAttribute;
627 Class attr_class = TypeManager.LookupClass (Type);
629 if (attr_class == null) {
630 object[] usage_attr = Type.GetCustomAttributes (TypeManager.attribute_usage_type, true);
631 ua = (AttributeUsageAttribute)usage_attr [0];
632 usage_attr_cache.Add (Type, ua);
636 return attr_class.AttributeUsage;
640 /// Returns custom name of indexer
642 public string GetIndexerAttributeValue (EmitContext ec)
644 if (pos_values == null) {
645 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
646 // But because a lot of attribute class code must be rewritten will be better to wait...
650 return pos_values [0] as string;
654 /// Returns condition of ConditionalAttribute
656 public string GetConditionalAttributeValue (DeclSpace ds)
658 if (pos_values == null) {
659 EmitContext ec = new EmitContext (ds, ds, Location, null, null, 0, false);
661 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
662 // But because a lot of attribute class code must be rewritten will be better to wait...
666 // Some error occurred
667 if (pos_values [0] == null)
670 return (string)pos_values [0];
674 /// Creates the instance of ObsoleteAttribute from this attribute instance
676 public ObsoleteAttribute GetObsoleteAttribute (DeclSpace ds)
678 if (pos_values == null) {
679 EmitContext ec = new EmitContext (ds, ds, Location, null, null, 0, false);
681 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
682 // But because a lot of attribute class code must be rewritten will be better to wait...
686 // Some error occurred
687 if (pos_values == null)
690 if (pos_values.Length == 0)
691 return new ObsoleteAttribute ();
693 if (pos_values.Length == 1)
694 return new ObsoleteAttribute ((string)pos_values [0]);
696 return new ObsoleteAttribute ((string)pos_values [0], (bool)pos_values [1]);
700 /// Returns value of CLSCompliantAttribute contructor parameter but because the method can be called
701 /// before ApplyAttribute. We need to resolve the arguments.
702 /// This situation occurs when class deps is differs from Emit order.
704 public bool GetClsCompliantAttributeValue (DeclSpace ds)
706 if (pos_values == null) {
707 EmitContext ec = new EmitContext (ds, ds, Location, null, null, 0, false);
709 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
710 // But because a lot of attribute class code must be rewritten will be better to wait...
714 // Some error occurred
715 if (pos_values [0] == null)
718 return (bool)pos_values [0];
721 object GetValue (object value)
723 if (value is EnumConstant)
724 return ((EnumConstant) value).GetValue ();
729 public object GetPositionalValue (int i)
731 return (pos_values == null) ? null : pos_values[i];
734 object GetFieldValue (string name)
737 if (field_info_arr == null)
740 foreach (FieldInfo fi in field_info_arr) {
742 return GetValue (field_values_arr [i]);
748 public UnmanagedMarshal GetMarshal ()
750 object o = GetFieldValue ("ArraySubType");
751 UnmanagedType array_sub_type = o == null ? UnmanagedType.I4 : (UnmanagedType) o;
753 switch (UnmanagedType) {
754 case UnmanagedType.CustomMarshaler:
755 MethodInfo define_custom = typeof (UnmanagedMarshal).GetMethod ("DefineCustom",
756 BindingFlags.Static | BindingFlags.Public);
757 if (define_custom == null)
760 object [] args = new object [4];
761 args [0] = GetFieldValue ("MarshalTypeRef");
762 args [1] = GetFieldValue ("MarshalCookie");
763 args [2] = GetFieldValue ("MarshalType");
764 args [3] = Guid.Empty;
765 return (UnmanagedMarshal) define_custom.Invoke (null, args);
767 case UnmanagedType.LPArray:
768 return UnmanagedMarshal.DefineLPArray (array_sub_type);
770 case UnmanagedType.SafeArray:
771 return UnmanagedMarshal.DefineSafeArray (array_sub_type);
773 case UnmanagedType.ByValArray:
774 return UnmanagedMarshal.DefineByValArray ((int) GetFieldValue ("SizeConst"));
776 case UnmanagedType.ByValTStr:
777 return UnmanagedMarshal.DefineByValTStr ((int) GetFieldValue ("SizeConst"));
780 return UnmanagedMarshal.DefineUnmanagedMarshal (UnmanagedType);
784 public bool IsInternalCall
786 get { return ImplOptions == MethodImplOptions.InternalCall; }
790 /// Emit attribute for Attributable symbol
792 public void Emit (EmitContext ec, Attributable ias, ListDictionary emitted_attr)
794 CustomAttributeBuilder cb = Resolve (ec);
798 AttributeUsageAttribute usage_attr = GetAttributeUsage ();
799 if ((usage_attr.ValidOn & Target) == 0) {
800 Report.Error (592, Location, "Attribute '{0}' is not valid on this declaration type. It is valid on {1} declarations only.", Name, GetValidTargets ());
804 ias.ApplyAttributeBuilder (this, cb);
806 if (!usage_attr.AllowMultiple) {
807 ArrayList emitted_targets = (ArrayList)emitted_attr [Type];
808 if (emitted_targets == null) {
809 emitted_targets = new ArrayList ();
810 emitted_attr.Add (Type, emitted_targets);
811 } else if (emitted_targets.Contains (Target)) {
812 Report.Error (579, Location, "Duplicate '" + Name + "' attribute");
815 emitted_targets.Add (Target);
818 if (!RootContext.VerifyClsCompliance)
821 // Here we are testing attribute arguments for array usage (error 3016)
822 if (ias.IsClsCompliaceRequired (ec.DeclSpace)) {
823 if (Arguments == null)
826 ArrayList pos_args = (ArrayList) Arguments [0];
827 if (pos_args != null) {
828 foreach (Argument arg in pos_args) {
829 // Type is undefined (was error 246)
830 if (arg.Type == null)
833 if (arg.Type.IsArray) {
834 Report.Error (3016, Location, "Arrays as attribute arguments are not CLS-compliant");
840 if (Arguments.Count < 2)
843 ArrayList named_args = (ArrayList) Arguments [1];
844 foreach (DictionaryEntry de in named_args) {
845 Argument arg = (Argument) de.Value;
847 // Type is undefined (was error 246)
848 if (arg.Type == null)
851 if (arg.Type.IsArray) {
852 Report.Error (3016, Location, "Arrays as attribute arguments are not CLS-compliant");
859 public object GetValue (EmitContext ec, Constant c, Type target)
861 if (Convert.ImplicitConversionExists (ec, c, target))
862 return c.GetValue ();
864 Convert.Error_CannotImplicitConversion (Location, c.Type, target);
868 public MethodBuilder DefinePInvokeMethod (EmitContext ec, TypeBuilder builder, string name,
869 MethodAttributes flags, Type ret_type, Type [] param_types)
872 // We extract from the attribute the information we need
875 if (Arguments == null) {
876 Console.WriteLine ("Internal error : this is not supposed to happen !");
880 ResolveType (ec, true);
884 ArrayList named_args = new ArrayList ();
886 ArrayList pos_args = (ArrayList) Arguments [0];
887 if (Arguments.Count > 1)
888 named_args = (ArrayList) Arguments [1];
891 string dll_name = null;
893 Argument tmp = (Argument) pos_args [0];
895 if (!tmp.Resolve (ec, Location))
898 if (tmp.Expr is Constant)
899 dll_name = (string) ((Constant) tmp.Expr).GetValue ();
901 Error_AttributeArgumentNotValid (Location);
905 // Now we process the named arguments
906 CallingConvention cc = CallingConvention.Winapi;
907 CharSet charset = CharSet.Ansi;
908 bool preserve_sig = true;
910 bool exact_spelling = false;
912 bool set_last_err = false;
913 string entry_point = null;
915 for (int i = 0; i < named_args.Count; i++) {
917 DictionaryEntry de = (DictionaryEntry) named_args [i];
919 string member_name = (string) de.Key;
920 Argument a = (Argument) de.Value;
922 if (!a.Resolve (ec, Location))
925 Expression member = Expression.MemberLookup (
926 ec, Type, member_name,
927 MemberTypes.Field | MemberTypes.Property,
928 BindingFlags.Public | BindingFlags.Instance,
931 if (member == null || !(member is FieldExpr)) {
932 Error_InvalidNamedArgument (member_name);
936 if (member is FieldExpr) {
937 FieldExpr fe = (FieldExpr) member;
938 FieldInfo fi = fe.FieldInfo;
941 Error_InvalidNamedArgument (member_name);
945 if (a.Expr is Constant) {
946 Constant c = (Constant) a.Expr;
949 if (member_name == "CallingConvention"){
950 object val = GetValue (ec, c, typeof (CallingConvention));
953 cc = (CallingConvention) val;
954 } else if (member_name == "CharSet"){
955 charset = (CharSet) c.GetValue ();
956 } else if (member_name == "EntryPoint")
957 entry_point = (string) c.GetValue ();
958 else if (member_name == "SetLastError")
959 set_last_err = (bool) c.GetValue ();
961 else if (member_name == "ExactSpelling")
962 exact_spelling = (bool) c.GetValue ();
964 else if (member_name == "PreserveSig")
965 preserve_sig = (bool) c.GetValue ();
966 } catch (InvalidCastException){
967 Error_InvalidNamedArgument (member_name);
968 Error_AttributeArgumentNotValid (Location);
971 Error_AttributeArgumentNotValid (Location);
978 if (entry_point == null)
981 charset = (CharSet)((int)charset | 0x40);
983 MethodBuilder mb = builder.DefinePInvokeMethod (
984 name, dll_name, entry_point, flags | MethodAttributes.HideBySig,
985 CallingConventions.Standard,
992 mb.SetImplementationFlags (MethodImplAttributes.PreserveSig);
997 private Expression GetValue ()
999 if ((Arguments == null) || (Arguments.Count < 1))
1001 ArrayList al = (ArrayList) Arguments [0];
1002 if ((al == null) || (al.Count < 1))
1004 Argument arg = (Argument) al [0];
1005 if ((arg == null) || (arg.Expr == null))
1010 public string GetString ()
1012 Expression e = GetValue ();
1013 if (e is StringLiteral)
1014 return (e as StringLiteral).Value;
1018 public bool GetBoolean ()
1020 Expression e = GetValue ();
1021 if (e is BoolLiteral)
1022 return (e as BoolLiteral).Value;
1029 /// For global attributes (assembly, module) we need special handling.
1030 /// Attributes can be located in the several files
1032 public class GlobalAttribute: Attribute
1034 public readonly NamespaceEntry ns;
1036 public GlobalAttribute (TypeContainer container, string target, string name, ArrayList args, Location loc):
1037 base (target, name, args, loc)
1039 ns = container.NamespaceEntry;
1042 protected override Type CheckAttributeType (EmitContext ec, bool complain)
1044 NamespaceEntry old = ec.DeclSpace.NamespaceEntry;
1045 if (old == null || old.NS == null || old.NS == Namespace.Root)
1046 ec.DeclSpace.NamespaceEntry = ns;
1047 return base.CheckAttributeType (ec, complain);
1051 public class Attributes {
1052 public ArrayList Attrs;
1054 public Attributes (Attribute a)
1056 Attrs = new ArrayList ();
1060 public Attributes (ArrayList attrs)
1065 public void AddAttributes (ArrayList attrs)
1067 Attrs.AddRange (attrs);
1071 /// Checks whether attribute target is valid for the current element
1073 public void CheckTargets (Attributable member)
1075 string[] valid_targets = member.ValidAttributeTargets;
1076 foreach (Attribute a in Attrs) {
1077 if (a.ExplicitTarget == null || a.ExplicitTarget == valid_targets [0]) {
1078 a.Target = member.AttributeTargets;
1082 // TODO: we can skip the first item
1083 if (((IList) valid_targets).Contains (a.ExplicitTarget)) {
1084 switch (a.ExplicitTarget) {
1085 case "return": a.Target = AttributeTargets.ReturnValue; continue;
1086 case "param": a.Target = AttributeTargets.Parameter; continue;
1087 case "field": a.Target = AttributeTargets.Field; continue;
1088 case "method": a.Target = AttributeTargets.Method; continue;
1089 case "property": a.Target = AttributeTargets.Property; continue;
1091 throw new InternalErrorException ("Unknown explicit target: " + a.ExplicitTarget);
1094 StringBuilder sb = new StringBuilder ();
1095 foreach (string s in valid_targets) {
1099 sb.Remove (sb.Length - 2, 2);
1100 Report.Error (657, a.Location, "'{0}' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are '{1}'", a.Target, sb.ToString ());
1104 private Attribute Search (Type t, EmitContext ec, bool complain)
1106 foreach (Attribute a in Attrs) {
1107 if (a.ResolveType (ec, complain) == t)
1113 public Attribute Search (Type t, EmitContext ec)
1115 return Search (t, ec, true);
1119 /// Returns all attributes of type 't'. Use it when attribute is AllowMultiple = true
1121 public Attribute[] SearchMulti (Type t, EmitContext ec)
1123 ArrayList ar = null;
1125 foreach (Attribute a in Attrs) {
1126 if (a.ResolveType (ec, false) == t) {
1128 ar = new ArrayList ();
1133 return ar == null ? null : ar.ToArray (typeof (Attribute)) as Attribute[];
1136 public void Emit (EmitContext ec, Attributable ias)
1138 ListDictionary ld = new ListDictionary ();
1140 foreach (Attribute a in Attrs)
1141 a.Emit (ec, ias, ld);
1144 public bool Contains (Type t, EmitContext ec)
1146 return Search (t, ec) != null;
1149 public Attribute GetClsCompliantAttribute (EmitContext ec)
1151 return Search (TypeManager.cls_compliant_attribute_type, ec, false);
1155 /// Pulls the IndexerName attribute from an Indexer if it exists.
1157 public Attribute GetIndexerNameAttribute (EmitContext ec)
1159 Attribute a = Search (TypeManager.indexer_name_type, ec, false);
1163 // Remove the attribute from the list because it is not emitted
1171 /// Helper class for attribute verification routine.
1173 sealed class AttributeTester
1175 static PtrHashtable analyzed_types = new PtrHashtable ();
1176 static PtrHashtable analyzed_types_obsolete = new PtrHashtable ();
1177 static PtrHashtable analyzed_member_obsolete = new PtrHashtable ();
1178 static PtrHashtable analyzed_method_excluded = new PtrHashtable ();
1180 private AttributeTester ()
1185 /// Returns true if parameters of two compared methods are CLS-Compliant.
1186 /// It tests differing only in ref or out, or in array rank.
1188 public static bool AreOverloadedMethodParamsClsCompliant (Type[] types_a, Type[] types_b)
1190 if (types_a == null || types_b == null)
1193 if (types_a.Length != types_b.Length)
1196 for (int i = 0; i < types_b.Length; ++i) {
1197 Type aType = types_a [i];
1198 Type bType = types_b [i];
1200 if (aType.IsArray && bType.IsArray && aType.GetArrayRank () != bType.GetArrayRank () && aType.GetElementType () == bType.GetElementType ()) {
1204 Type aBaseType = aType;
1205 bool is_either_ref_or_out = false;
1207 if (aType.IsByRef || aType.IsPointer) {
1208 aBaseType = aType.GetElementType ();
1209 is_either_ref_or_out = true;
1212 Type bBaseType = bType;
1213 if (bType.IsByRef || bType.IsPointer)
1215 bBaseType = bType.GetElementType ();
1216 is_either_ref_or_out = !is_either_ref_or_out;
1219 if (aBaseType != bBaseType)
1222 if (is_either_ref_or_out)
1229 /// Goes through all parameters and test if they are CLS-Compliant.
1231 public static bool AreParametersCompliant (Parameter[] fixedParameters, Location loc)
1233 if (fixedParameters == null)
1236 foreach (Parameter arg in fixedParameters) {
1237 if (!AttributeTester.IsClsCompliant (arg.ParameterType)) {
1238 Report.Error (3001, loc, "Argument type '{0}' is not CLS-compliant", arg.GetSignatureForError ());
1247 /// This method tests the CLS compliance of external types. It doesn't test type visibility.
1249 public static bool IsClsCompliant (Type type)
1254 object type_compliance = analyzed_types[type];
1255 if (type_compliance != null)
1256 return type_compliance == TRUE;
1258 if (type.IsPointer) {
1259 analyzed_types.Add (type, null);
1264 if (type.IsArray || type.IsByRef) {
1265 result = IsClsCompliant (TypeManager.GetElementType (type));
1267 result = AnalyzeTypeCompliance (type);
1269 analyzed_types.Add (type, result ? TRUE : FALSE);
1273 static object TRUE = new object ();
1274 static object FALSE = new object ();
1276 public static void VerifyModulesClsCompliance ()
1278 Module[] modules = TypeManager.Modules;
1279 if (modules == null)
1282 // The first module is generated assembly
1283 for (int i = 1; i < modules.Length; ++i) {
1284 Module module = modules [i];
1285 if (!IsClsCompliant (module)) {
1286 Report.Error (3013, "Added modules must be marked with the CLSCompliant attribute to match the assembly", module.Name);
1293 /// Tests container name for CLS-Compliant name (differing only in case)
1295 public static void VerifyTopLevelNameClsCompliance ()
1297 Hashtable locase_table = new Hashtable ();
1299 // Convert imported type names to lower case and ignore not cls compliant
1300 foreach (DictionaryEntry de in TypeManager.all_imported_types) {
1301 Type t = (Type)de.Value;
1302 if (!AttributeTester.IsClsCompliant (t))
1305 locase_table.Add (((string)de.Key).ToLower (System.Globalization.CultureInfo.InvariantCulture), t);
1308 foreach (DictionaryEntry de in RootContext.Tree.Decls) {
1309 DeclSpace decl = (DeclSpace)de.Value;
1310 if (!decl.IsClsCompliaceRequired (decl))
1313 string lcase = decl.Name.ToLower (System.Globalization.CultureInfo.InvariantCulture);
1314 if (!locase_table.Contains (lcase)) {
1315 locase_table.Add (lcase, decl);
1319 object conflict = locase_table [lcase];
1320 if (conflict is Type)
1321 Report.SymbolRelatedToPreviousError ((Type)conflict);
1323 Report.SymbolRelatedToPreviousError ((MemberCore)conflict);
1325 Report.Error (3005, decl.Location, "Identifier '{0}' differing only in case is not CLS-compliant", decl.GetSignatureForError ());
1329 static bool IsClsCompliant (ICustomAttributeProvider attribute_provider)
1331 object[] CompliantAttribute = attribute_provider.GetCustomAttributes (TypeManager.cls_compliant_attribute_type, false);
1332 if (CompliantAttribute.Length == 0)
1335 return ((CLSCompliantAttribute)CompliantAttribute[0]).IsCompliant;
1338 static bool AnalyzeTypeCompliance (Type type)
1340 DeclSpace ds = TypeManager.LookupDeclSpace (type);
1342 return ds.IsClsCompliaceRequired (ds.Parent);
1345 if (type.IsGenericParameter)
1348 object[] CompliantAttribute = type.GetCustomAttributes (TypeManager.cls_compliant_attribute_type, false);
1349 if (CompliantAttribute.Length == 0)
1350 return IsClsCompliant (type.Assembly);
1352 return ((CLSCompliantAttribute)CompliantAttribute[0]).IsCompliant;
1356 /// Returns instance of ObsoleteAttribute when type is obsolete
1358 public static ObsoleteAttribute GetObsoleteAttribute (Type type)
1360 object type_obsolete = analyzed_types_obsolete [type];
1361 if (type_obsolete == FALSE)
1364 if (type_obsolete != null)
1365 return (ObsoleteAttribute)type_obsolete;
1367 ObsoleteAttribute result = null;
1368 if (type.IsByRef || type.IsArray || type.IsPointer) {
1369 result = GetObsoleteAttribute (TypeManager.GetElementType (type));
1370 } else if (type.IsGenericParameter || type.IsGenericInstance)
1373 DeclSpace type_ds = TypeManager.LookupDeclSpace (type);
1375 // Type is external, we can get attribute directly
1376 if (type_ds == null) {
1377 object[] attribute = type.GetCustomAttributes (TypeManager.obsolete_attribute_type, false);
1378 if (attribute.Length == 1)
1379 result = (ObsoleteAttribute)attribute [0];
1381 result = type_ds.GetObsoleteAttribute (type_ds);
1385 analyzed_types_obsolete.Add (type, result == null ? FALSE : result);
1390 /// Returns instance of ObsoleteAttribute when method is obsolete
1392 public static ObsoleteAttribute GetMethodObsoleteAttribute (MethodBase mb)
1394 IMethodData mc = TypeManager.GetMethod (mb);
1396 return mc.GetObsoleteAttribute ();
1398 // compiler generated methods are not registered by AddMethod
1399 if (mb.DeclaringType is TypeBuilder)
1402 return GetMemberObsoleteAttribute (mb);
1406 /// Returns instance of ObsoleteAttribute when member is obsolete
1408 public static ObsoleteAttribute GetMemberObsoleteAttribute (MemberInfo mi)
1410 object type_obsolete = analyzed_member_obsolete [mi];
1411 if (type_obsolete == FALSE)
1414 if (type_obsolete != null)
1415 return (ObsoleteAttribute)type_obsolete;
1417 if ((mi.DeclaringType is TypeBuilder) || mi.DeclaringType.IsGenericInstance)
1420 ObsoleteAttribute oa = System.Attribute.GetCustomAttribute (mi, TypeManager.obsolete_attribute_type, false) as ObsoleteAttribute;
1421 analyzed_member_obsolete.Add (mi, oa == null ? FALSE : oa);
1426 /// Common method for Obsolete error/warning reporting.
1428 public static void Report_ObsoleteMessage (ObsoleteAttribute oa, string member, Location loc)
1431 Report.Error (619, loc, "'{0}' is obsolete: '{1}'", member, oa.Message);
1435 if (oa.Message == null) {
1436 Report.Warning (612, loc, "'{0}' is obsolete", member);
1439 if (RootContext.WarningLevel >= 2)
1440 Report.Warning (618, loc, "'{0}' is obsolete: '{1}'", member, oa.Message);
1443 public static bool IsConditionalMethodExcluded (MethodBase mb)
1445 object excluded = analyzed_method_excluded [mb];
1446 if (excluded != null)
1447 return excluded == TRUE ? true : false;
1449 if (mb.Mono_IsInflatedMethod)
1452 ConditionalAttribute[] attrs = mb.GetCustomAttributes (TypeManager.conditional_attribute_type, true) as ConditionalAttribute[];
1453 if (attrs.Length == 0) {
1454 analyzed_method_excluded.Add (mb, FALSE);
1458 foreach (ConditionalAttribute a in attrs) {
1459 if (RootContext.AllDefines.Contains (a.ConditionString)) {
1460 analyzed_method_excluded.Add (mb, FALSE);
1464 analyzed_method_excluded.Add (mb, TRUE);