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;
21 using System.Security;
22 using System.Security.Permissions;
25 namespace Mono.CSharp {
28 /// Base class for objects that can have Attributes applied to them.
30 public abstract class Attributable {
32 /// Attributes for this type
34 Attributes attributes;
36 public Attributable(Attributes attrs)
41 public Attributes OptAttributes
52 /// Use member-specific procedure to apply attribute @a in @cb to the entity being built in @builder
54 public abstract void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb);
57 /// Returns one AttributeTarget for this element.
59 public abstract AttributeTargets AttributeTargets { get; }
61 public abstract bool IsClsCompliaceRequired (DeclSpace ds);
64 /// Gets list of valid attribute targets for explicit target declaration.
65 /// The first array item is default target. Don't break this rule.
67 public abstract string[] ValidAttributeTargets { get; }
70 public class Attribute {
71 public readonly string ExplicitTarget;
72 public AttributeTargets Target;
74 public readonly string Name;
75 public readonly ArrayList Arguments;
77 public readonly Location Location;
81 // Is non-null if type is AttributeUsageAttribute
82 AttributeUsageAttribute usage_attribute;
84 public AttributeUsageAttribute UsageAttribute {
86 return usage_attribute;
90 MethodImplOptions ImplOptions;
91 UnmanagedType UnmanagedType;
92 CustomAttributeBuilder cb;
94 // non-null if named args present after Resolve () is called
95 PropertyInfo [] prop_info_arr;
96 FieldInfo [] field_info_arr;
97 object [] field_values_arr;
98 object [] prop_values_arr;
101 static PtrHashtable usage_attr_cache = new PtrHashtable ();
103 public Attribute (string target, string name, ArrayList args, Location loc)
108 ExplicitTarget = target;
111 void Error_InvalidNamedArgument (string name)
113 Report.Error (617, Location, "'" + name + "' is not a valid named attribute " +
114 "argument. Named attribute arguments must be fields which are not " +
115 "readonly, static or const, or read-write properties which are not static.");
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");
126 /// This is rather hack. We report many emit attribute error with same error to be compatible with
127 /// csc. But because csc has to report them this way because error came from ilasm we needn't.
129 public void Error_AttributeEmitError (string inner)
131 Report.Error (647, Location, "Error emitting '{0}' attribute because '{1}'", Name, inner);
134 public void Error_InvalidSecurityParent ()
136 Error_AttributeEmitError ("it is attached to invalid parent");
139 void Error_AttributeConstructorMismatch ()
141 Report.Error (-6, Location,
142 "Could not find a constructor for this argument list.");
146 /// Tries to resolve the type of the attribute. Flags an error if it can't, and complain is true.
148 protected virtual Type CheckAttributeType (EmitContext ec, bool complain)
150 Type t1 = RootContext.LookupType (ec.DeclSpace, Name, true, Location);
152 // FIXME: Shouldn't do this for quoted attributes: [@A]
153 Type t2 = RootContext.LookupType (ec.DeclSpace, Name + "Attribute", true, Location);
155 String err0616 = null;
157 if (t1 != null && ! t1.IsSubclassOf (TypeManager.attribute_type)) {
159 err0616 = "'" + Name + "': is not an attribute class";
161 if (t2 != null && ! t2.IsSubclassOf (TypeManager.attribute_type)) {
163 err0616 = (err0616 != null)
164 ? "Neither '" + Name + "' nor '" + Name + "Attribute' is an attribute class"
165 : "'" + Name + "Attribute': is not an attribute class";
168 if (t1 != null && t2 != null) {
169 Report.Error(1614, Location, "'" + Name + "': is ambiguous; "
170 + " use either '@" + Name + "' or '" + Name + "Attribute'");
178 if (err0616 != null) {
179 Report.Error (616, Location, err0616);
184 Report.Error (246, Location,
185 "Could not find attribute '" + Name
186 + "' (are you missing a using directive or an assembly reference ?)");
190 public Type ResolveType (EmitContext ec, bool complain)
193 Type = CheckAttributeType (ec, complain);
198 /// Validates the guid string
200 bool ValidateGuid (string guid)
206 Report.Error (647, Location, "Format of GUID is invalid: " + guid);
211 string GetFullMemberName (string member)
213 return Type.FullName + '.' + member;
217 // Given an expression, if the expression is a valid attribute-argument-expression
218 // returns an object that can be used to encode it, or null on failure.
220 public static bool GetAttributeArgumentExpression (Expression e, Location loc, Type arg_type, out object result)
222 if (e is EnumConstant) {
223 if (RootContext.StdLib)
224 result = ((EnumConstant)e).GetValueAsEnumType ();
226 result = ((EnumConstant)e).GetValue ();
231 Constant constant = e as Constant;
232 if (constant != null) {
233 if (e.Type != arg_type) {
234 constant = Const.ChangeType (loc, constant, arg_type);
235 if (constant == null) {
237 Error_AttributeArgumentNotValid (loc);
241 result = constant.GetValue ();
243 } else if (e is TypeOf) {
244 result = ((TypeOf) e).TypeArg;
246 } else if (e is ArrayCreation){
247 result = ((ArrayCreation) e).EncodeAsAttribute ();
250 } else if (e is EmptyCast) {
251 Expression child = ((EmptyCast)e).Child;
252 return GetAttributeArgumentExpression (child, loc, child.Type, out result);
256 Error_AttributeArgumentNotValid (loc);
260 public CustomAttributeBuilder Resolve (EmitContext ec)
265 Type = CheckAttributeType (ec, true);
267 if (oldType == null && Type == null)
269 if (oldType != null && oldType != Type){
270 Report.Error (-27, Location,
271 "Attribute {0} resolved to different types at different times: {1} vs. {2}",
272 Name, oldType, Type);
276 if (Type.IsAbstract) {
277 Report.Error (653, Location, "Cannot apply attribute class '{0}' because it is abstract", Name);
281 bool MethodImplAttr = false;
282 bool MarshalAsAttr = false;
283 bool GuidAttr = false;
284 bool usage_attr = false;
286 bool DoCompares = true;
289 // If we are a certain special attribute, we
290 // set the information accordingly
293 if (Type == TypeManager.attribute_usage_type)
295 else if (Type == TypeManager.methodimpl_attr_type)
296 MethodImplAttr = true;
297 else if (Type == TypeManager.marshal_as_attr_type)
298 MarshalAsAttr = true;
299 else if (Type == TypeManager.guid_attr_type)
304 // Now we extract the positional and named arguments
306 ArrayList pos_args = new ArrayList ();
307 ArrayList named_args = new ArrayList ();
308 int pos_arg_count = 0;
310 if (Arguments != null) {
311 pos_args = (ArrayList) Arguments [0];
312 if (pos_args != null)
313 pos_arg_count = pos_args.Count;
314 if (Arguments.Count > 1)
315 named_args = (ArrayList) Arguments [1];
318 pos_values = new object [pos_arg_count];
321 // First process positional arguments
325 for (i = 0; i < pos_arg_count; i++) {
326 Argument a = (Argument) pos_args [i];
329 if (!a.Resolve (ec, Location))
335 if (!GetAttributeArgumentExpression (e, Location, a.Type, out val))
338 pos_values [i] = val;
342 usage_attribute = new AttributeUsageAttribute ((AttributeTargets)val);
343 } else if (MethodImplAttr) {
344 this.ImplOptions = (MethodImplOptions) val;
345 } else if (GuidAttr){
347 // we will later check the validity of the type
350 if (!ValidateGuid ((string) val))
354 } else if (MarshalAsAttr)
356 (System.Runtime.InteropServices.UnmanagedType) val;
361 // Now process named arguments
364 ArrayList field_infos = null;
365 ArrayList prop_infos = null;
366 ArrayList field_values = null;
367 ArrayList prop_values = null;
369 if (named_args.Count > 0) {
370 field_infos = new ArrayList ();
371 prop_infos = new ArrayList ();
372 field_values = new ArrayList ();
373 prop_values = new ArrayList ();
376 Hashtable seen_names = new Hashtable();
378 for (i = 0; i < named_args.Count; i++) {
379 DictionaryEntry de = (DictionaryEntry) named_args [i];
380 string member_name = (string) de.Key;
381 Argument a = (Argument) de.Value;
384 if (seen_names.Contains(member_name)) {
385 Report.Error(643, Location, "'" + member_name + "' duplicate named attribute argument");
388 seen_names.Add(member_name, 1);
390 if (!a.Resolve (ec, Location))
393 Expression member = Expression.MemberLookup (
394 ec, Type, member_name,
395 MemberTypes.Field | MemberTypes.Property,
396 BindingFlags.Public | BindingFlags.Instance,
399 if (member == null) {
400 member = Expression.MemberLookup (ec, Type, member_name,
401 MemberTypes.Field | MemberTypes.Property, BindingFlags.NonPublic | BindingFlags.Instance,
404 if (member != null) {
405 Report.Error (122, Location, "'{0}' is inaccessible due to its protection level", GetFullMemberName (member_name));
410 if (member == null || !(member is PropertyExpr || member is FieldExpr)) {
411 Error_InvalidNamedArgument (member_name);
416 if (member is PropertyExpr) {
417 PropertyExpr pe = (PropertyExpr) member;
418 PropertyInfo pi = pe.PropertyInfo;
420 if (!pi.CanWrite || !pi.CanRead) {
421 Report.SymbolRelatedToPreviousError (pi);
422 Error_InvalidNamedArgument (member_name);
427 if (!GetAttributeArgumentExpression (e, Location, pi.PropertyType, out value))
430 if (usage_attribute != null) {
431 if (member_name == "AllowMultiple")
432 usage_attribute.AllowMultiple = (bool) value;
433 if (member_name == "Inherited")
434 usage_attribute.Inherited = (bool) value;
437 prop_values.Add (value);
440 } else if (member is FieldExpr) {
441 FieldExpr fe = (FieldExpr) member;
442 FieldInfo fi = fe.FieldInfo;
445 Error_InvalidNamedArgument (member_name);
450 if (!GetAttributeArgumentExpression (e, Location, fi.FieldType, out value))
453 field_values.Add (value);
454 field_infos.Add (fi);
458 Expression mg = Expression.MemberLookup (
459 ec, Type, ".ctor", MemberTypes.Constructor,
460 BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly,
464 Error_AttributeConstructorMismatch ();
468 MethodBase constructor = Invocation.OverloadResolve (
469 ec, (MethodGroupExpr) mg, pos_args, false, Location);
471 if (constructor == null) {
476 // Now we perform some checks on the positional args as they
477 // cannot be null for a constructor which expects a parameter
481 ParameterData pd = Invocation.GetParameterData (constructor);
483 int group_in_params_array = Int32.MaxValue;
485 if (pc > 0 && pd.ParameterModifier (pc-1) == Parameter.Modifier.PARAMS)
486 group_in_params_array = pc-1;
488 for (int j = 0; j < pos_arg_count; ++j) {
489 Argument a = (Argument) pos_args [j];
491 if (a.Expr is NullLiteral && pd.ParameterType (j) == TypeManager.object_type) {
492 Error_AttributeArgumentNotValid (Location);
496 if (j < group_in_params_array)
499 if (j == group_in_params_array){
500 object v = pos_values [j];
501 int count = pos_arg_count - j;
503 object [] array = new object [count];
504 pos_values [j] = array;
507 object [] array = (object []) pos_values [group_in_params_array];
509 array [j - group_in_params_array] = pos_values [j];
514 // Adjust the size of the pos_values if it had params
516 if (group_in_params_array != Int32.MaxValue){
517 int argc = group_in_params_array+1;
518 object [] new_pos_values = new object [argc];
520 for (int p = 0; p < argc; p++)
521 new_pos_values [p] = pos_values [p];
522 pos_values = new_pos_values;
526 if (named_args.Count > 0) {
527 prop_info_arr = new PropertyInfo [prop_infos.Count];
528 field_info_arr = new FieldInfo [field_infos.Count];
529 field_values_arr = new object [field_values.Count];
530 prop_values_arr = new object [prop_values.Count];
532 field_infos.CopyTo (field_info_arr, 0);
533 field_values.CopyTo (field_values_arr, 0);
535 prop_values.CopyTo (prop_values_arr, 0);
536 prop_infos.CopyTo (prop_info_arr, 0);
538 cb = new CustomAttributeBuilder (
539 (ConstructorInfo) constructor, pos_values,
540 prop_info_arr, prop_values_arr,
541 field_info_arr, field_values_arr);
544 cb = new CustomAttributeBuilder (
545 (ConstructorInfo) constructor, pos_values);
546 } catch (NullReferenceException) {
548 // Don't know what to do here
551 -101, Location, "NullReferenceException while trying to create attribute." +
552 "Something's wrong!");
553 } catch (Exception e) {
556 // using System.ComponentModel;
557 // [DefaultValue (CollectionChangeAction.Add)]
558 // class X { static void Main () {} }
561 -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);
568 /// Get a string containing a list of valid targets for the attribute 'attr'
570 public string GetValidTargets ()
572 StringBuilder sb = new StringBuilder ();
573 AttributeTargets targets = GetAttributeUsage ().ValidOn;
575 if ((targets & AttributeTargets.Assembly) != 0)
576 sb.Append ("'assembly' ");
578 if ((targets & AttributeTargets.Class) != 0)
579 sb.Append ("'class' ");
581 if ((targets & AttributeTargets.Constructor) != 0)
582 sb.Append ("'constructor' ");
584 if ((targets & AttributeTargets.Delegate) != 0)
585 sb.Append ("'delegate' ");
587 if ((targets & AttributeTargets.Enum) != 0)
588 sb.Append ("'enum' ");
590 if ((targets & AttributeTargets.Event) != 0)
591 sb.Append ("'event' ");
593 if ((targets & AttributeTargets.Field) != 0)
594 sb.Append ("'field' ");
596 if ((targets & AttributeTargets.Interface) != 0)
597 sb.Append ("'interface' ");
599 if ((targets & AttributeTargets.Method) != 0)
600 sb.Append ("'method' ");
602 if ((targets & AttributeTargets.Module) != 0)
603 sb.Append ("'module' ");
605 if ((targets & AttributeTargets.Parameter) != 0)
606 sb.Append ("'parameter' ");
608 if ((targets & AttributeTargets.Property) != 0)
609 sb.Append ("'property' ");
611 if ((targets & AttributeTargets.ReturnValue) != 0)
612 sb.Append ("'return' ");
614 if ((targets & AttributeTargets.Struct) != 0)
615 sb.Append ("'struct' ");
617 return sb.ToString ();
622 /// Returns AttributeUsage attribute for this type
624 public AttributeUsageAttribute GetAttributeUsage ()
626 AttributeUsageAttribute ua = usage_attr_cache [Type] as AttributeUsageAttribute;
630 Class attr_class = TypeManager.LookupClass (Type);
632 if (attr_class == null) {
633 object[] usage_attr = Type.GetCustomAttributes (TypeManager.attribute_usage_type, true);
634 ua = (AttributeUsageAttribute)usage_attr [0];
635 usage_attr_cache.Add (Type, ua);
639 return attr_class.AttributeUsage;
643 /// Returns custom name of indexer
645 public string GetIndexerAttributeValue (EmitContext ec)
647 if (pos_values == null) {
648 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
649 // But because a lot of attribute class code must be rewritten will be better to wait...
653 return pos_values [0] as string;
657 /// Returns condition of ConditionalAttribute
659 public string GetConditionalAttributeValue (DeclSpace ds)
661 if (pos_values == null) {
662 EmitContext ec = new EmitContext (ds, ds, Location, null, null, 0, false);
664 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
665 // But because a lot of attribute class code must be rewritten will be better to wait...
669 // Some error occurred
670 if (pos_values [0] == null)
673 return (string)pos_values [0];
677 /// Creates the instance of ObsoleteAttribute from this attribute instance
679 public ObsoleteAttribute GetObsoleteAttribute (DeclSpace ds)
681 if (pos_values == null) {
682 EmitContext ec = new EmitContext (ds, ds, Location, null, null, 0, false);
684 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
685 // But because a lot of attribute class code must be rewritten will be better to wait...
689 // Some error occurred
690 if (pos_values == null)
693 if (pos_values.Length == 0)
694 return new ObsoleteAttribute ();
696 if (pos_values.Length == 1)
697 return new ObsoleteAttribute ((string)pos_values [0]);
699 return new ObsoleteAttribute ((string)pos_values [0], (bool)pos_values [1]);
703 /// Returns value of CLSCompliantAttribute contructor parameter but because the method can be called
704 /// before ApplyAttribute. We need to resolve the arguments.
705 /// This situation occurs when class deps is differs from Emit order.
707 public bool GetClsCompliantAttributeValue (DeclSpace ds)
709 if (pos_values == null) {
710 EmitContext ec = new EmitContext (ds, ds, Location, null, null, 0, false);
712 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
713 // But because a lot of attribute class code must be rewritten will be better to wait...
717 // Some error occurred
718 if (pos_values [0] == null)
721 return (bool)pos_values [0];
725 /// Tests permitted SecurityAction for assembly or other types
727 public bool CheckSecurityActionValidity (bool for_assembly)
729 SecurityAction action = GetSecurityActionValue ();
731 if ((action == SecurityAction.RequestMinimum || action == SecurityAction.RequestOptional || action == SecurityAction.RequestRefuse) && for_assembly)
735 if (action < SecurityAction.Demand || action > SecurityAction.InheritanceDemand) {
736 Error_AttributeEmitError ("SecurityAction is out of range");
740 if ((action != SecurityAction.RequestMinimum && action != SecurityAction.RequestOptional && action != SecurityAction.RequestRefuse) && !for_assembly)
744 Error_AttributeEmitError (String.Concat ("SecurityAction '", action, "' is not valid for this declaration"));
748 System.Security.Permissions.SecurityAction GetSecurityActionValue ()
750 return (SecurityAction)pos_values [0];
754 /// Creates instance of SecurityAttribute class and add result of CreatePermission method to permission table.
756 /// <returns></returns>
757 public void ExtractSecurityPermissionSet (ListDictionary permissions)
759 if (TypeManager.LookupDeclSpace (Type) != null && RootContext.StdLib) {
760 Error_AttributeEmitError ("security custom attributes can not be referenced from defining assembly");
764 SecurityAttribute sa;
765 // For all assemblies except corlib we can avoid all hacks
766 if (RootContext.StdLib) {
767 sa = (SecurityAttribute) Activator.CreateInstance (Type, pos_values);
769 if (prop_info_arr != null) {
770 for (int i = 0; i < prop_info_arr.Length; ++i) {
771 PropertyInfo pi = prop_info_arr [i];
772 pi.SetValue (sa, prop_values_arr [i], null);
776 Type temp_type = Type.GetType (Type.FullName);
777 // HACK: All mscorlib attributes have same ctor syntax
778 sa = (SecurityAttribute) Activator.CreateInstance (temp_type, new object[] { GetSecurityActionValue () } );
780 // All types are from newly created corlib but for invocation with old we need to convert them
781 if (prop_info_arr != null) {
782 for (int i = 0; i < prop_info_arr.Length; ++i) {
783 PropertyInfo emited_pi = prop_info_arr [i];
784 PropertyInfo pi = temp_type.GetProperty (emited_pi.Name, emited_pi.PropertyType);
786 object old_instance = pi.PropertyType.IsEnum ?
787 System.Enum.ToObject (pi.PropertyType, prop_values_arr [i]) :
790 pi.SetValue (sa, old_instance, null);
795 IPermission perm = sa.CreatePermission ();
796 SecurityAction action;
798 // IS is correct because for corlib we are using an instance from old corlib
799 if (perm is System.Security.CodeAccessPermission) {
800 action = GetSecurityActionValue ();
802 switch (GetSecurityActionValue ()) {
803 case SecurityAction.Demand:
804 action = (SecurityAction)13;
806 case SecurityAction.LinkDemand:
807 action = (SecurityAction)14;
809 case SecurityAction.InheritanceDemand:
810 action = (SecurityAction)15;
813 Error_AttributeEmitError ("Invalid SecurityAction for non-Code Access Security permission");
818 PermissionSet ps = (PermissionSet)permissions [action];
820 ps = new PermissionSet (PermissionState.None);
821 permissions.Add (action, ps);
823 ps.AddPermission (sa.CreatePermission ());
826 object GetValue (object value)
828 if (value is EnumConstant)
829 return ((EnumConstant) value).GetValue ();
834 public object GetPositionalValue (int i)
836 return (pos_values == null) ? null : pos_values[i];
839 object GetFieldValue (string name)
842 if (field_info_arr == null)
845 foreach (FieldInfo fi in field_info_arr) {
847 return GetValue (field_values_arr [i]);
853 public UnmanagedMarshal GetMarshal (Attributable attr)
855 object value = GetFieldValue ("SizeParamIndex");
856 if (value != null && UnmanagedType != UnmanagedType.LPArray) {
857 Error_AttributeEmitError ("SizeParamIndex field is not valid for the specified unmanaged type");
861 object o = GetFieldValue ("ArraySubType");
862 UnmanagedType array_sub_type = o == null ? UnmanagedType.I4 : (UnmanagedType) o;
864 switch (UnmanagedType) {
865 case UnmanagedType.CustomMarshaler:
866 MethodInfo define_custom = typeof (UnmanagedMarshal).GetMethod ("DefineCustom",
867 BindingFlags.Static | BindingFlags.Public);
868 if (define_custom == null) {
869 Report.RuntimeMissingSupport (Location, "set marshal info");
873 object [] args = new object [4];
874 args [0] = GetFieldValue ("MarshalTypeRef");
875 args [1] = GetFieldValue ("MarshalCookie");
876 args [2] = GetFieldValue ("MarshalType");
877 args [3] = Guid.Empty;
878 return (UnmanagedMarshal) define_custom.Invoke (null, args);
880 case UnmanagedType.LPArray:
881 return UnmanagedMarshal.DefineLPArray (array_sub_type);
883 case UnmanagedType.SafeArray:
884 return UnmanagedMarshal.DefineSafeArray (array_sub_type);
886 case UnmanagedType.ByValArray:
887 FieldMember fm = attr as FieldMember;
889 Error_AttributeEmitError ("Specified unmanaged type is only valid on fields");
892 return UnmanagedMarshal.DefineByValArray ((int) GetFieldValue ("SizeConst"));
894 case UnmanagedType.ByValTStr:
895 return UnmanagedMarshal.DefineByValTStr ((int) GetFieldValue ("SizeConst"));
898 return UnmanagedMarshal.DefineUnmanagedMarshal (UnmanagedType);
902 public bool IsInternalCall
904 get { return ImplOptions == MethodImplOptions.InternalCall; }
908 /// Emit attribute for Attributable symbol
910 public void Emit (EmitContext ec, Attributable ias, ListDictionary emitted_attr)
912 CustomAttributeBuilder cb = Resolve (ec);
916 AttributeUsageAttribute usage_attr = GetAttributeUsage ();
917 if ((usage_attr.ValidOn & Target) == 0) {
918 Report.Error (592, Location, "Attribute '{0}' is not valid on this declaration type. It is valid on {1} declarations only.", Name, GetValidTargets ());
922 ias.ApplyAttributeBuilder (this, cb);
924 if (!usage_attr.AllowMultiple) {
925 ArrayList emitted_targets = (ArrayList)emitted_attr [Type];
926 if (emitted_targets == null) {
927 emitted_targets = new ArrayList ();
928 emitted_attr.Add (Type, emitted_targets);
929 } else if (emitted_targets.Contains (Target)) {
930 Report.Error (579, Location, "Duplicate '" + Name + "' attribute");
933 emitted_targets.Add (Target);
936 if (!RootContext.VerifyClsCompliance)
939 // Here we are testing attribute arguments for array usage (error 3016)
940 if (ias.IsClsCompliaceRequired (ec.DeclSpace)) {
941 if (Arguments == null)
944 ArrayList pos_args = (ArrayList) Arguments [0];
945 if (pos_args != null) {
946 foreach (Argument arg in pos_args) {
947 // Type is undefined (was error 246)
948 if (arg.Type == null)
951 if (arg.Type.IsArray) {
952 Report.Error (3016, Location, "Arrays as attribute arguments are not CLS-compliant");
958 if (Arguments.Count < 2)
961 ArrayList named_args = (ArrayList) Arguments [1];
962 foreach (DictionaryEntry de in named_args) {
963 Argument arg = (Argument) de.Value;
965 // Type is undefined (was error 246)
966 if (arg.Type == null)
969 if (arg.Type.IsArray) {
970 Report.Error (3016, Location, "Arrays as attribute arguments are not CLS-compliant");
977 public object GetValue (EmitContext ec, Constant c, Type target)
979 if (Convert.ImplicitConversionExists (ec, c, target))
980 return c.GetValue ();
982 Convert.Error_CannotImplicitConversion (Location, c.Type, target);
986 public MethodBuilder DefinePInvokeMethod (EmitContext ec, TypeBuilder builder, string name,
987 MethodAttributes flags, Type ret_type, Type [] param_types)
990 // We extract from the attribute the information we need
993 if (Arguments == null) {
994 Console.WriteLine ("Internal error : this is not supposed to happen !");
998 ResolveType (ec, true);
1002 ArrayList named_args = new ArrayList ();
1004 ArrayList pos_args = (ArrayList) Arguments [0];
1005 if (Arguments.Count > 1)
1006 named_args = (ArrayList) Arguments [1];
1009 string dll_name = null;
1011 Argument tmp = (Argument) pos_args [0];
1013 if (!tmp.Resolve (ec, Location))
1016 if (tmp.Expr is Constant)
1017 dll_name = (string) ((Constant) tmp.Expr).GetValue ();
1019 Error_AttributeArgumentNotValid (Location);
1023 // Now we process the named arguments
1024 CallingConvention cc = CallingConvention.Winapi;
1025 CharSet charset = CharSet.Ansi;
1026 bool preserve_sig = true;
1028 bool exact_spelling = false;
1030 bool set_last_err = false;
1031 string entry_point = null;
1033 for (int i = 0; i < named_args.Count; i++) {
1035 DictionaryEntry de = (DictionaryEntry) named_args [i];
1037 string member_name = (string) de.Key;
1038 Argument a = (Argument) de.Value;
1040 if (!a.Resolve (ec, Location))
1043 Expression member = Expression.MemberLookup (
1044 ec, Type, member_name,
1045 MemberTypes.Field | MemberTypes.Property,
1046 BindingFlags.Public | BindingFlags.Instance,
1049 if (member == null || !(member is FieldExpr)) {
1050 Error_InvalidNamedArgument (member_name);
1054 if (member is FieldExpr) {
1055 FieldExpr fe = (FieldExpr) member;
1056 FieldInfo fi = fe.FieldInfo;
1058 if (fi.IsInitOnly) {
1059 Error_InvalidNamedArgument (member_name);
1063 if (a.Expr is Constant) {
1064 Constant c = (Constant) a.Expr;
1067 if (member_name == "CallingConvention"){
1068 object val = GetValue (ec, c, typeof (CallingConvention));
1071 cc = (CallingConvention) val;
1072 } else if (member_name == "CharSet"){
1073 charset = (CharSet) c.GetValue ();
1074 } else if (member_name == "EntryPoint")
1075 entry_point = (string) c.GetValue ();
1076 else if (member_name == "SetLastError")
1077 set_last_err = (bool) c.GetValue ();
1079 else if (member_name == "ExactSpelling")
1080 exact_spelling = (bool) c.GetValue ();
1082 else if (member_name == "PreserveSig")
1083 preserve_sig = (bool) c.GetValue ();
1084 } catch (InvalidCastException){
1085 Error_InvalidNamedArgument (member_name);
1086 Error_AttributeArgumentNotValid (Location);
1089 Error_AttributeArgumentNotValid (Location);
1096 if (entry_point == null)
1099 charset = (CharSet)((int)charset | 0x40);
1101 MethodBuilder mb = builder.DefinePInvokeMethod (
1102 name, dll_name, entry_point, flags | MethodAttributes.HideBySig,
1103 CallingConventions.Standard,
1110 mb.SetImplementationFlags (MethodImplAttributes.PreserveSig);
1115 private Expression GetValue ()
1117 if ((Arguments == null) || (Arguments.Count < 1))
1119 ArrayList al = (ArrayList) Arguments [0];
1120 if ((al == null) || (al.Count < 1))
1122 Argument arg = (Argument) al [0];
1123 if ((arg == null) || (arg.Expr == null))
1128 public string GetString ()
1130 Expression e = GetValue ();
1131 if (e is StringLiteral)
1132 return (e as StringLiteral).Value;
1136 public bool GetBoolean ()
1138 Expression e = GetValue ();
1139 if (e is BoolLiteral)
1140 return (e as BoolLiteral).Value;
1147 /// For global attributes (assembly, module) we need special handling.
1148 /// Attributes can be located in the several files
1150 public class GlobalAttribute: Attribute
1152 public readonly NamespaceEntry ns;
1154 public GlobalAttribute (TypeContainer container, string target, string name, ArrayList args, Location loc):
1155 base (target, name, args, loc)
1157 ns = container.NamespaceEntry;
1160 protected override Type CheckAttributeType (EmitContext ec, bool complain)
1162 NamespaceEntry old = ec.DeclSpace.NamespaceEntry;
1163 if (old == null || old.NS == null || old.NS == Namespace.Root)
1164 ec.DeclSpace.NamespaceEntry = ns;
1165 return base.CheckAttributeType (ec, complain);
1169 public class Attributes {
1170 public ArrayList Attrs;
1172 public Attributes (Attribute a)
1174 Attrs = new ArrayList ();
1178 public Attributes (ArrayList attrs)
1183 public void AddAttributes (ArrayList attrs)
1185 Attrs.AddRange (attrs);
1189 /// Checks whether attribute target is valid for the current element
1191 public bool CheckTargets (Attributable member)
1193 string[] valid_targets = member.ValidAttributeTargets;
1194 foreach (Attribute a in Attrs) {
1195 if (a.ExplicitTarget == null || a.ExplicitTarget == valid_targets [0]) {
1196 a.Target = member.AttributeTargets;
1200 // TODO: we can skip the first item
1201 if (((IList) valid_targets).Contains (a.ExplicitTarget)) {
1202 switch (a.ExplicitTarget) {
1203 case "return": a.Target = AttributeTargets.ReturnValue; continue;
1204 case "param": a.Target = AttributeTargets.Parameter; continue;
1205 case "field": a.Target = AttributeTargets.Field; continue;
1206 case "method": a.Target = AttributeTargets.Method; continue;
1207 case "property": a.Target = AttributeTargets.Property; continue;
1209 throw new InternalErrorException ("Unknown explicit target: " + a.ExplicitTarget);
1212 StringBuilder sb = new StringBuilder ();
1213 foreach (string s in valid_targets) {
1217 sb.Remove (sb.Length - 2, 2);
1218 Report.Error (657, a.Location, "'{0}' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are '{1}'", a.ExplicitTarget, sb.ToString ());
1224 private Attribute Search (Type t, EmitContext ec, bool complain)
1226 foreach (Attribute a in Attrs) {
1227 if (a.ResolveType (ec, complain) == t)
1233 public Attribute Search (Type t, EmitContext ec)
1235 return Search (t, ec, true);
1239 /// Returns all attributes of type 't'. Use it when attribute is AllowMultiple = true
1241 public Attribute[] SearchMulti (Type t, EmitContext ec)
1243 ArrayList ar = null;
1245 foreach (Attribute a in Attrs) {
1246 if (a.ResolveType (ec, false) == t) {
1248 ar = new ArrayList ();
1253 return ar == null ? null : ar.ToArray (typeof (Attribute)) as Attribute[];
1256 public void Emit (EmitContext ec, Attributable ias)
1258 if (!CheckTargets (ias))
1261 ListDictionary ld = new ListDictionary ();
1263 foreach (Attribute a in Attrs)
1264 a.Emit (ec, ias, ld);
1267 public bool Contains (Type t, EmitContext ec)
1269 return Search (t, ec) != null;
1272 public Attribute GetClsCompliantAttribute (EmitContext ec)
1274 return Search (TypeManager.cls_compliant_attribute_type, ec, false);
1278 /// Pulls the IndexerName attribute from an Indexer if it exists.
1280 public Attribute GetIndexerNameAttribute (EmitContext ec)
1282 Attribute a = Search (TypeManager.indexer_name_type, ec, false);
1286 // Remove the attribute from the list because it is not emitted
1294 /// Helper class for attribute verification routine.
1296 sealed class AttributeTester
1298 static PtrHashtable analyzed_types = new PtrHashtable ();
1299 static PtrHashtable analyzed_types_obsolete = new PtrHashtable ();
1300 static PtrHashtable analyzed_member_obsolete = new PtrHashtable ();
1301 static PtrHashtable analyzed_method_excluded = new PtrHashtable ();
1303 private AttributeTester ()
1308 /// Returns true if parameters of two compared methods are CLS-Compliant.
1309 /// It tests differing only in ref or out, or in array rank.
1311 public static bool AreOverloadedMethodParamsClsCompliant (Type[] types_a, Type[] types_b)
1313 if (types_a == null || types_b == null)
1316 if (types_a.Length != types_b.Length)
1319 for (int i = 0; i < types_b.Length; ++i) {
1320 Type aType = types_a [i];
1321 Type bType = types_b [i];
1323 if (aType.IsArray && bType.IsArray && aType.GetArrayRank () != bType.GetArrayRank () && aType.GetElementType () == bType.GetElementType ()) {
1327 Type aBaseType = aType;
1328 bool is_either_ref_or_out = false;
1330 if (aType.IsByRef || aType.IsPointer) {
1331 aBaseType = aType.GetElementType ();
1332 is_either_ref_or_out = true;
1335 Type bBaseType = bType;
1336 if (bType.IsByRef || bType.IsPointer)
1338 bBaseType = bType.GetElementType ();
1339 is_either_ref_or_out = !is_either_ref_or_out;
1342 if (aBaseType != bBaseType)
1345 if (is_either_ref_or_out)
1352 /// Goes through all parameters and test if they are CLS-Compliant.
1354 public static bool AreParametersCompliant (Parameter[] fixedParameters, Location loc)
1356 if (fixedParameters == null)
1359 foreach (Parameter arg in fixedParameters) {
1360 if (!AttributeTester.IsClsCompliant (arg.ParameterType)) {
1361 Report.Error (3001, loc, "Argument type '{0}' is not CLS-compliant", arg.GetSignatureForError ());
1370 /// This method tests the CLS compliance of external types. It doesn't test type visibility.
1372 public static bool IsClsCompliant (Type type)
1377 object type_compliance = analyzed_types[type];
1378 if (type_compliance != null)
1379 return type_compliance == TRUE;
1381 if (type.IsPointer) {
1382 analyzed_types.Add (type, null);
1387 if (type.IsArray || type.IsByRef) {
1388 result = IsClsCompliant (TypeManager.GetElementType (type));
1390 result = AnalyzeTypeCompliance (type);
1392 analyzed_types.Add (type, result ? TRUE : FALSE);
1396 static object TRUE = new object ();
1397 static object FALSE = new object ();
1399 public static void VerifyModulesClsCompliance ()
1401 Module[] modules = TypeManager.Modules;
1402 if (modules == null)
1405 // The first module is generated assembly
1406 for (int i = 1; i < modules.Length; ++i) {
1407 Module module = modules [i];
1408 if (!IsClsCompliant (module)) {
1409 Report.Error (3013, "Added modules must be marked with the CLSCompliant attribute to match the assembly", module.Name);
1416 /// Tests container name for CLS-Compliant name (differing only in case)
1418 public static void VerifyTopLevelNameClsCompliance ()
1420 Hashtable locase_table = new Hashtable ();
1422 // Convert imported type names to lower case and ignore not cls compliant
1423 foreach (DictionaryEntry de in TypeManager.all_imported_types) {
1424 Type t = (Type)de.Value;
1425 if (!AttributeTester.IsClsCompliant (t))
1428 locase_table.Add (((string)de.Key).ToLower (System.Globalization.CultureInfo.InvariantCulture), t);
1431 foreach (DictionaryEntry de in RootContext.Tree.Decls) {
1432 DeclSpace decl = (DeclSpace)de.Value;
1433 if (!decl.IsClsCompliaceRequired (decl))
1436 string lcase = decl.Name.ToLower (System.Globalization.CultureInfo.InvariantCulture);
1437 if (!locase_table.Contains (lcase)) {
1438 locase_table.Add (lcase, decl);
1442 object conflict = locase_table [lcase];
1443 if (conflict is Type)
1444 Report.SymbolRelatedToPreviousError ((Type)conflict);
1446 Report.SymbolRelatedToPreviousError ((MemberCore)conflict);
1448 Report.Error (3005, decl.Location, "Identifier '{0}' differing only in case is not CLS-compliant", decl.GetSignatureForError ());
1452 static bool IsClsCompliant (ICustomAttributeProvider attribute_provider)
1454 object[] CompliantAttribute = attribute_provider.GetCustomAttributes (TypeManager.cls_compliant_attribute_type, false);
1455 if (CompliantAttribute.Length == 0)
1458 return ((CLSCompliantAttribute)CompliantAttribute[0]).IsCompliant;
1461 static bool AnalyzeTypeCompliance (Type type)
1463 DeclSpace ds = TypeManager.LookupDeclSpace (type);
1465 return ds.IsClsCompliaceRequired (ds.Parent);
1468 object[] CompliantAttribute = type.GetCustomAttributes (TypeManager.cls_compliant_attribute_type, false);
1469 if (CompliantAttribute.Length == 0)
1470 return IsClsCompliant (type.Assembly);
1472 return ((CLSCompliantAttribute)CompliantAttribute[0]).IsCompliant;
1476 /// Returns instance of ObsoleteAttribute when type is obsolete
1478 public static ObsoleteAttribute GetObsoleteAttribute (Type type)
1480 object type_obsolete = analyzed_types_obsolete [type];
1481 if (type_obsolete == FALSE)
1484 if (type_obsolete != null)
1485 return (ObsoleteAttribute)type_obsolete;
1487 ObsoleteAttribute result = null;
1488 if (type.IsByRef || type.IsArray || type.IsPointer) {
1489 result = GetObsoleteAttribute (TypeManager.GetElementType (type));
1491 DeclSpace type_ds = TypeManager.LookupDeclSpace (type);
1493 // Type is external, we can get attribute directly
1494 if (type_ds == null) {
1495 object[] attribute = type.GetCustomAttributes (TypeManager.obsolete_attribute_type, false);
1496 if (attribute.Length == 1)
1497 result = (ObsoleteAttribute)attribute [0];
1499 result = type_ds.GetObsoleteAttribute (type_ds);
1503 analyzed_types_obsolete.Add (type, result == null ? FALSE : result);
1508 /// Returns instance of ObsoleteAttribute when method is obsolete
1510 public static ObsoleteAttribute GetMethodObsoleteAttribute (MethodBase mb)
1512 IMethodData mc = TypeManager.GetMethod (mb);
1514 return mc.GetObsoleteAttribute ();
1516 // compiler generated methods are not registered by AddMethod
1517 if (mb.DeclaringType is TypeBuilder)
1520 return GetMemberObsoleteAttribute (mb);
1524 /// Returns instance of ObsoleteAttribute when member is obsolete
1526 public static ObsoleteAttribute GetMemberObsoleteAttribute (MemberInfo mi)
1528 object type_obsolete = analyzed_member_obsolete [mi];
1529 if (type_obsolete == FALSE)
1532 if (type_obsolete != null)
1533 return (ObsoleteAttribute)type_obsolete;
1535 ObsoleteAttribute oa = System.Attribute.GetCustomAttribute (mi, TypeManager.obsolete_attribute_type, false) as ObsoleteAttribute;
1536 analyzed_member_obsolete.Add (mi, oa == null ? FALSE : oa);
1541 /// Common method for Obsolete error/warning reporting.
1543 public static void Report_ObsoleteMessage (ObsoleteAttribute oa, string member, Location loc)
1546 Report.Error (619, loc, "'{0}' is obsolete: '{1}'", member, oa.Message);
1550 if (oa.Message == null) {
1551 Report.Warning (612, loc, "'{0}' is obsolete", member);
1554 if (RootContext.WarningLevel >= 2)
1555 Report.Warning (618, loc, "'{0}' is obsolete: '{1}'", member, oa.Message);
1558 public static bool IsConditionalMethodExcluded (MethodBase mb)
1560 object excluded = analyzed_method_excluded [mb];
1561 if (excluded != null)
1562 return excluded == TRUE ? true : false;
1564 ConditionalAttribute[] attrs = mb.GetCustomAttributes (TypeManager.conditional_attribute_type, true) as ConditionalAttribute[];
1565 if (attrs.Length == 0) {
1566 analyzed_method_excluded.Add (mb, FALSE);
1570 foreach (ConditionalAttribute a in attrs) {
1571 if (RootContext.AllDefines.Contains (a.ConditionString)) {
1572 analyzed_method_excluded.Add (mb, FALSE);
1576 analyzed_method_excluded.Add (mb, TRUE);