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 Expression LeftExpr;
76 public readonly string Identifier;
78 public readonly ArrayList Arguments;
80 public readonly Location Location;
86 public AttributeUsageAttribute UsageAttribute;
87 public static AttributeUsageAttribute DefaultUsageAttribute = new AttributeUsageAttribute (AttributeTargets.All);
89 MethodImplOptions ImplOptions;
90 UnmanagedType UnmanagedType;
91 CustomAttributeBuilder cb;
93 // non-null if named args present after Resolve () is called
94 PropertyInfo [] prop_info_arr;
95 FieldInfo [] field_info_arr;
96 object [] field_values_arr;
97 object [] prop_values_arr;
100 static PtrHashtable usage_attr_cache = new PtrHashtable ();
102 public Attribute (string target, Expression left_expr, string identifier, ArrayList args, Location loc)
104 LeftExpr = left_expr;
105 Identifier = identifier;
106 Name = LeftExpr == null ? identifier : LeftExpr + "." + identifier;
109 ExplicitTarget = target;
112 void Error_InvalidNamedArgument (string name)
114 Report.Error (617, Location, "Invalid attribute argument: '{0}'. Argument must be fields " +
115 "fields which are not readonly, static or const; or read-write instance properties.",
119 static void Error_AttributeArgumentNotValid (string extra, Location loc)
121 Report.Error (182, loc,
122 "An attribute argument must be a constant expression, typeof " +
123 "expression or array creation expression" + extra);
126 static void Error_AttributeArgumentNotValid (Location loc)
128 Error_AttributeArgumentNotValid ("", loc);
133 /// This is rather hack. We report many emit attribute error with same error to be compatible with
134 /// csc. But because csc has to report them this way because error came from ilasm we needn't.
136 public void Error_AttributeEmitError (string inner)
138 Report.Error (647, Location, "Error emitting '{0}' attribute because '{1}'", Name, inner);
141 public void Error_InvalidSecurityParent ()
143 Error_AttributeEmitError ("it is attached to invalid parent");
146 void Error_AttributeConstructorMismatch ()
148 Report.Error (-6, Location,
149 "Could not find a constructor for this argument list.");
152 void ResolvePossibleAttributeTypes (EmitContext ec, out Type t1, out Type t2)
157 FullNamedExpression n1 = null;
158 FullNamedExpression n2 = null;
159 string IdentifierAttribute = Identifier + "Attribute";
160 if (LeftExpr == null) {
161 n1 = new SimpleName (Identifier, Location).ResolveAsTypeStep (ec);
163 // FIXME: Shouldn't do this for quoted attributes: [@A]
164 n2 = new SimpleName (IdentifierAttribute, Location).ResolveAsTypeStep (ec);
166 FullNamedExpression l = LeftExpr.ResolveAsTypeStep (ec);
168 Report.Error (246, Location, "Couldn't find namespace or type '{0}'", LeftExpr);
171 n1 = new MemberAccess (l, Identifier, Location).ResolveNamespaceOrType (ec, true);
173 // FIXME: Shouldn't do this for quoted attributes: [X.@A]
174 n2 = new MemberAccess (l, IdentifierAttribute, Location).ResolveNamespaceOrType (ec, true);
177 TypeExpr te1 = n1 == null ? null : n1 as TypeExpr;
178 TypeExpr te2 = n2 == null ? null : n2 as TypeExpr;
181 t1 = te1.ResolveType (ec);
183 t2 = te2.ResolveType (ec);
187 /// Tries to resolve the type of the attribute. Flags an error if it can't, and complain is true.
189 Type CheckAttributeType (EmitContext ec)
193 ResolvePossibleAttributeTypes (ec, out t1, out t2);
195 string NameAttribute = Name + "Attribute";
197 String err0616 = null;
199 if (t1 != null && ! t1.IsSubclassOf (TypeManager.attribute_type)) {
201 err0616 = "'" + Name + "': is not an attribute class";
203 if (t2 != null && ! t2.IsSubclassOf (TypeManager.attribute_type)) {
205 err0616 = (err0616 != null)
206 ? "Neither '" + Name + "' nor '" + NameAttribute +"' is an attribute class"
207 : "'" + Name + "Attribute': is not an attribute class";
210 if (t1 != null && t2 != null) {
211 Report.Error(1614, Location, "'" + Name + "': is ambiguous; "
212 + " use either '@" + Name + "' or '" + NameAttribute + "'");
220 if (err0616 != null) {
221 Report.Error (616, Location, err0616);
225 Report.Error (246, Location,
226 "Could not find attribute '" + Name
227 + "' (are you missing a using directive or an assembly reference ?)");
229 resolve_error = true;
233 public virtual Type ResolveType (EmitContext ec)
235 if (Type == null && !resolve_error)
236 Type = CheckAttributeType (ec);
241 /// Validates the guid string
243 bool ValidateGuid (string guid)
249 Report.Error (647, Location, "Format of GUID is invalid: " + guid);
254 string GetFullMemberName (string member)
256 return Type.FullName + '.' + member;
260 // Given an expression, if the expression is a valid attribute-argument-expression
261 // returns an object that can be used to encode it, or null on failure.
263 public static bool GetAttributeArgumentExpression (Expression e, Location loc, Type arg_type, out object result)
265 if (e is EnumConstant) {
266 if (RootContext.StdLib)
267 result = ((EnumConstant)e).GetValueAsEnumType ();
269 result = ((EnumConstant)e).GetValue ();
274 Constant constant = e as Constant;
275 if (constant != null) {
276 if (e.Type != arg_type) {
277 constant = Const.ChangeType (loc, constant, arg_type);
278 if (constant == null) {
280 Error_AttributeArgumentNotValid (loc);
284 result = constant.GetValue ();
286 } else if (e is TypeOf) {
287 result = ((TypeOf) e).TypeArg;
289 } else if (e is ArrayCreation){
290 result = ((ArrayCreation) e).EncodeAsAttribute ();
293 } else if (e is EmptyCast) {
294 Expression child = ((EmptyCast)e).Child;
295 return GetAttributeArgumentExpression (child, loc, child.Type, out result);
299 Error_AttributeArgumentNotValid (loc);
303 public virtual CustomAttributeBuilder Resolve (EmitContext ec)
308 resolve_error = true;
313 Type = CheckAttributeType (ec); // TODO: I really don't think we need such expensive double check
315 if (oldType == null && Type == null)
317 if (oldType != null && oldType != Type){
318 Report.Error (-27, Location,
319 "Attribute {0} resolved to different types at different times: {1} vs. {2}",
320 Name, oldType, Type);
324 if (Type.IsAbstract) {
325 Report.Error (653, Location, "Cannot apply attribute class '{0}' because it is abstract", Name);
329 bool MethodImplAttr = false;
330 bool MarshalAsAttr = false;
331 bool GuidAttr = false;
332 bool usage_attr = false;
334 bool DoCompares = true;
337 // If we are a certain special attribute, we
338 // set the information accordingly
341 if (Type == TypeManager.attribute_usage_type)
343 else if (Type == TypeManager.methodimpl_attr_type)
344 MethodImplAttr = true;
345 else if (Type == TypeManager.marshal_as_attr_type)
346 MarshalAsAttr = true;
347 else if (Type == TypeManager.guid_attr_type)
352 // Now we extract the positional and named arguments
354 ArrayList pos_args = new ArrayList ();
355 ArrayList named_args = new ArrayList ();
356 int pos_arg_count = 0;
358 if (Arguments != null) {
359 pos_args = (ArrayList) Arguments [0];
360 if (pos_args != null)
361 pos_arg_count = pos_args.Count;
362 if (Arguments.Count > 1)
363 named_args = (ArrayList) Arguments [1];
366 pos_values = new object [pos_arg_count];
369 // First process positional arguments
373 for (i = 0; i < pos_arg_count; i++) {
374 Argument a = (Argument) pos_args [i];
377 if (!a.Resolve (ec, Location))
383 if (!GetAttributeArgumentExpression (e, Location, a.Type, out val))
386 pos_values [i] = val;
391 Report.Error (591, Location, "Invalid value for argument to 'System.AttributeUsage' attribute");
394 UsageAttribute = new AttributeUsageAttribute ((AttributeTargets)val);
395 } else if (MethodImplAttr) {
396 this.ImplOptions = (MethodImplOptions) val;
397 } else if (GuidAttr){
399 // we will later check the validity of the type
402 if (!ValidateGuid ((string) val))
406 } else if (MarshalAsAttr)
408 (System.Runtime.InteropServices.UnmanagedType) val;
413 // Now process named arguments
416 ArrayList field_infos = null;
417 ArrayList prop_infos = null;
418 ArrayList field_values = null;
419 ArrayList prop_values = null;
421 if (named_args.Count > 0) {
422 field_infos = new ArrayList ();
423 prop_infos = new ArrayList ();
424 field_values = new ArrayList ();
425 prop_values = new ArrayList ();
428 Hashtable seen_names = new Hashtable();
430 for (i = 0; i < named_args.Count; i++) {
431 DictionaryEntry de = (DictionaryEntry) named_args [i];
432 string member_name = (string) de.Key;
433 Argument a = (Argument) de.Value;
436 if (seen_names.Contains(member_name)) {
437 Report.Error(643, Location, "'" + member_name + "' duplicate named attribute argument");
440 seen_names.Add(member_name, 1);
442 if (!a.Resolve (ec, Location))
445 Expression member = Expression.MemberLookup (
446 ec, Type, member_name,
447 MemberTypes.Field | MemberTypes.Property,
448 BindingFlags.Public | BindingFlags.Instance,
451 if (member == null) {
452 member = Expression.MemberLookup (ec, Type, member_name,
453 MemberTypes.Field | MemberTypes.Property, BindingFlags.NonPublic | BindingFlags.Instance,
456 if (member != null) {
457 Report.Error (122, Location, "'{0}' is inaccessible due to its protection level", GetFullMemberName (member_name));
463 Report.Error (117, Location, "Attribute `{0}' does not contain a definition for `{1}'",
468 if (!(member is PropertyExpr || member is FieldExpr)) {
469 Error_InvalidNamedArgument (member_name);
474 if (member is PropertyExpr) {
475 PropertyExpr pe = (PropertyExpr) member;
476 PropertyInfo pi = pe.PropertyInfo;
478 if (!pi.CanWrite || !pi.CanRead) {
479 Report.SymbolRelatedToPreviousError (pi);
480 Error_InvalidNamedArgument (member_name);
485 if (!GetAttributeArgumentExpression (e, Location, pi.PropertyType, out value))
488 if (UsageAttribute != null) {
489 if (member_name == "AllowMultiple")
490 UsageAttribute.AllowMultiple = (bool) value;
491 if (member_name == "Inherited")
492 UsageAttribute.Inherited = (bool) value;
495 prop_values.Add (value);
498 } else if (member is FieldExpr) {
499 FieldExpr fe = (FieldExpr) member;
500 FieldInfo fi = fe.FieldInfo;
503 Error_InvalidNamedArgument (member_name);
508 if (!GetAttributeArgumentExpression (e, Location, fi.FieldType, out value))
511 field_values.Add (value);
512 field_infos.Add (fi);
516 Expression mg = Expression.MemberLookup (
517 ec, Type, ".ctor", MemberTypes.Constructor,
518 BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly,
522 Error_AttributeConstructorMismatch ();
526 MethodBase constructor = Invocation.OverloadResolve (
527 ec, (MethodGroupExpr) mg, pos_args, false, Location);
529 if (constructor == null) {
534 // Now we perform some checks on the positional args as they
535 // cannot be null for a constructor which expects a parameter
539 ParameterData pd = TypeManager.GetParameterData (constructor);
541 int last_real_param = pd.Count;
543 // When the params is not filled we need to put one
544 if (last_real_param > pos_arg_count) {
545 object [] new_pos_values = new object [pos_arg_count + 1];
546 pos_values.CopyTo (new_pos_values, 0);
547 new_pos_values [pos_arg_count] = new object [] {} ;
548 pos_values = new_pos_values;
553 for (int j = 0; j < pos_arg_count; ++j) {
554 Argument a = (Argument) pos_args [j];
556 if (a.Expr is NullLiteral && pd.ParameterType (j) == TypeManager.object_type) {
557 Error_AttributeArgumentNotValid (Location);
561 object value = pos_values [j];
562 if (value != null && a.Type != value.GetType () && a.Type.IsPrimitive) {
564 pos_values [j] = TypeManager.ChangeType (value, a.Type, out fail);
566 // TODO: Can failed ?
567 throw new NotImplementedException ();
571 if (j < last_real_param)
574 if (j == last_real_param) {
575 object [] array = new object [pos_arg_count - last_real_param];
576 array [0] = pos_values [j];
577 pos_values [j] = array;
581 object [] params_array = (object []) pos_values [last_real_param];
582 params_array [j - last_real_param] = pos_values [j];
585 // Adjust the size of the pos_values if it had params
586 if (last_real_param != pos_arg_count) {
587 object [] new_pos_values = new object [last_real_param + 1];
588 Array.Copy (pos_values, new_pos_values, last_real_param + 1);
589 pos_values = new_pos_values;
593 if (named_args.Count > 0) {
594 prop_info_arr = new PropertyInfo [prop_infos.Count];
595 field_info_arr = new FieldInfo [field_infos.Count];
596 field_values_arr = new object [field_values.Count];
597 prop_values_arr = new object [prop_values.Count];
599 field_infos.CopyTo (field_info_arr, 0);
600 field_values.CopyTo (field_values_arr, 0);
602 prop_values.CopyTo (prop_values_arr, 0);
603 prop_infos.CopyTo (prop_info_arr, 0);
605 cb = new CustomAttributeBuilder (
606 (ConstructorInfo) constructor, pos_values,
607 prop_info_arr, prop_values_arr,
608 field_info_arr, field_values_arr);
611 cb = new CustomAttributeBuilder (
612 (ConstructorInfo) constructor, pos_values);
613 } catch (Exception e) {
616 // using System.ComponentModel;
617 // [DefaultValue (CollectionChangeAction.Add)]
618 // class X { static void Main () {} }
620 Error_AttributeArgumentNotValid (Location);
625 UsageAttribute = DefaultUsageAttribute;
628 resolve_error = false;
633 /// Get a string containing a list of valid targets for the attribute 'attr'
635 public string GetValidTargets ()
637 StringBuilder sb = new StringBuilder ();
638 AttributeTargets targets = UsageAttribute.ValidOn;
640 if ((targets & AttributeTargets.Assembly) != 0)
641 sb.Append ("'assembly' ");
643 if ((targets & AttributeTargets.Class) != 0)
644 sb.Append ("'class' ");
646 if ((targets & AttributeTargets.Constructor) != 0)
647 sb.Append ("'constructor' ");
649 if ((targets & AttributeTargets.Delegate) != 0)
650 sb.Append ("'delegate' ");
652 if ((targets & AttributeTargets.Enum) != 0)
653 sb.Append ("'enum' ");
655 if ((targets & AttributeTargets.Event) != 0)
656 sb.Append ("'event' ");
658 if ((targets & AttributeTargets.Field) != 0)
659 sb.Append ("'field' ");
661 if ((targets & AttributeTargets.Interface) != 0)
662 sb.Append ("'interface' ");
664 if ((targets & AttributeTargets.Method) != 0)
665 sb.Append ("'method' ");
667 if ((targets & AttributeTargets.Module) != 0)
668 sb.Append ("'module' ");
670 if ((targets & AttributeTargets.Parameter) != 0)
671 sb.Append ("'parameter' ");
673 if ((targets & AttributeTargets.Property) != 0)
674 sb.Append ("'property' ");
676 if ((targets & AttributeTargets.ReturnValue) != 0)
677 sb.Append ("'return' ");
679 if ((targets & AttributeTargets.Struct) != 0)
680 sb.Append ("'struct' ");
682 return sb.ToString ();
687 /// Returns AttributeUsage attribute for this type
689 public AttributeUsageAttribute GetAttributeUsage (EmitContext ec)
691 AttributeUsageAttribute ua = usage_attr_cache [Type] as AttributeUsageAttribute;
695 Class attr_class = TypeManager.LookupClass (Type);
697 if (attr_class == null) {
698 object[] usage_attr = Type.GetCustomAttributes (TypeManager.attribute_usage_type, true);
699 ua = (AttributeUsageAttribute)usage_attr [0];
700 usage_attr_cache.Add (Type, ua);
704 ua = attr_class.ResolveAttributeUsage (ec);
705 usage_attr_cache.Add (Type, ua);
710 /// Returns custom name of indexer
712 public string GetIndexerAttributeValue (EmitContext ec)
714 if (pos_values == null)
715 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
716 // But because a lot of attribute class code must be rewritten will be better to wait...
719 return pos_values [0] as string;
723 /// Returns condition of ConditionalAttribute
725 public string GetConditionalAttributeValue (EmitContext ec)
727 if (pos_values == null)
728 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
729 // But because a lot of attribute class code must be rewritten will be better to wait...
732 // Some error occurred
733 if (pos_values [0] == null)
736 return (string)pos_values [0];
740 /// Creates the instance of ObsoleteAttribute from this attribute instance
742 public ObsoleteAttribute GetObsoleteAttribute (EmitContext ec)
744 if (pos_values == null)
745 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
746 // But because a lot of attribute class code must be rewritten will be better to wait...
749 // Some error occurred
750 if (pos_values == null)
753 if (pos_values.Length == 0)
754 return new ObsoleteAttribute ();
756 if (pos_values.Length == 1)
757 return new ObsoleteAttribute ((string)pos_values [0]);
759 return new ObsoleteAttribute ((string)pos_values [0], (bool)pos_values [1]);
763 /// Returns value of CLSCompliantAttribute contructor parameter but because the method can be called
764 /// before ApplyAttribute. We need to resolve the arguments.
765 /// This situation occurs when class deps is differs from Emit order.
767 public bool GetClsCompliantAttributeValue (EmitContext ec)
769 if (pos_values == null)
770 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
771 // But because a lot of attribute class code must be rewritten will be better to wait...
774 // Some error occurred
775 if (pos_values [0] == null)
778 return (bool)pos_values [0];
782 /// Tests permitted SecurityAction for assembly or other types
784 public bool CheckSecurityActionValidity (bool for_assembly)
786 SecurityAction action = GetSecurityActionValue ();
788 if ((action == SecurityAction.RequestMinimum || action == SecurityAction.RequestOptional || action == SecurityAction.RequestRefuse) && for_assembly)
792 if (action < SecurityAction.Demand || action > SecurityAction.InheritanceDemand) {
793 Error_AttributeEmitError ("SecurityAction is out of range");
797 if ((action != SecurityAction.RequestMinimum && action != SecurityAction.RequestOptional && action != SecurityAction.RequestRefuse) && !for_assembly)
801 Error_AttributeEmitError (String.Concat ("SecurityAction '", action, "' is not valid for this declaration"));
805 System.Security.Permissions.SecurityAction GetSecurityActionValue ()
807 return (SecurityAction)pos_values [0];
811 /// Creates instance of SecurityAttribute class and add result of CreatePermission method to permission table.
813 /// <returns></returns>
814 public void ExtractSecurityPermissionSet (ListDictionary permissions)
816 if (TypeManager.LookupDeclSpace (Type) != null && RootContext.StdLib) {
817 Error_AttributeEmitError ("security custom attributes can not be referenced from defining assembly");
821 SecurityAttribute sa;
822 // For all assemblies except corlib we can avoid all hacks
823 if (RootContext.StdLib) {
824 sa = (SecurityAttribute) Activator.CreateInstance (Type, pos_values);
826 if (prop_info_arr != null) {
827 for (int i = 0; i < prop_info_arr.Length; ++i) {
828 PropertyInfo pi = prop_info_arr [i];
829 pi.SetValue (sa, prop_values_arr [i], null);
833 Type temp_type = Type.GetType (Type.FullName);
834 // HACK: All mscorlib attributes have same ctor syntax
835 sa = (SecurityAttribute) Activator.CreateInstance (temp_type, new object[] { GetSecurityActionValue () } );
837 // All types are from newly created corlib but for invocation with old we need to convert them
838 if (prop_info_arr != null) {
839 for (int i = 0; i < prop_info_arr.Length; ++i) {
840 PropertyInfo emited_pi = prop_info_arr [i];
841 PropertyInfo pi = temp_type.GetProperty (emited_pi.Name, emited_pi.PropertyType);
843 object old_instance = pi.PropertyType.IsEnum ?
844 System.Enum.ToObject (pi.PropertyType, prop_values_arr [i]) :
847 pi.SetValue (sa, old_instance, null);
854 perm = sa.CreatePermission ();
856 catch (Exception e) {
857 Error_AttributeEmitError (String.Format ("{0} was thrown during attribute processing: {1}", e.GetType (), e.Message));
860 SecurityAction action = GetSecurityActionValue ();
862 // IS is correct because for corlib we are using an instance from old corlib
863 if (!(perm is System.Security.CodeAccessPermission)) {
865 case SecurityAction.Demand:
866 action = (SecurityAction)13;
868 case SecurityAction.LinkDemand:
869 action = (SecurityAction)14;
871 case SecurityAction.InheritanceDemand:
872 action = (SecurityAction)15;
877 PermissionSet ps = (PermissionSet)permissions [action];
879 if (sa is PermissionSetAttribute)
880 ps = new PermissionSet (sa.Unrestricted ? PermissionState.Unrestricted : PermissionState.None);
882 ps = new PermissionSet (PermissionState.None);
884 permissions.Add (action, ps);
885 } else if (!ps.IsUnrestricted () && sa.Unrestricted) {
886 ps = ps.Union (new PermissionSet (PermissionState.Unrestricted));
887 permissions [action] = ps;
889 ps.AddPermission (perm);
892 object GetValue (object value)
894 if (value is EnumConstant)
895 return ((EnumConstant) value).GetValue ();
900 public object GetPositionalValue (int i)
902 return (pos_values == null) ? null : pos_values[i];
905 object GetFieldValue (string name)
908 if (field_info_arr == null)
911 foreach (FieldInfo fi in field_info_arr) {
913 return GetValue (field_values_arr [i]);
919 public UnmanagedMarshal GetMarshal (Attributable attr)
921 object value = GetFieldValue ("SizeParamIndex");
922 if (value != null && UnmanagedType != UnmanagedType.LPArray) {
923 Error_AttributeEmitError ("SizeParamIndex field is not valid for the specified unmanaged type");
927 object o = GetFieldValue ("ArraySubType");
928 UnmanagedType array_sub_type = o == null ? UnmanagedType.I4 : (UnmanagedType) o;
930 switch (UnmanagedType) {
931 case UnmanagedType.CustomMarshaler:
932 MethodInfo define_custom = typeof (UnmanagedMarshal).GetMethod ("DefineCustom",
933 BindingFlags.Static | BindingFlags.Public);
934 if (define_custom == null) {
935 Report.RuntimeMissingSupport (Location, "set marshal info");
939 object [] args = new object [4];
940 args [0] = GetFieldValue ("MarshalTypeRef");
941 args [1] = GetFieldValue ("MarshalCookie");
942 args [2] = GetFieldValue ("MarshalType");
943 args [3] = Guid.Empty;
944 return (UnmanagedMarshal) define_custom.Invoke (null, args);
946 case UnmanagedType.LPArray:
947 return UnmanagedMarshal.DefineLPArray (array_sub_type);
949 case UnmanagedType.SafeArray:
950 return UnmanagedMarshal.DefineSafeArray (array_sub_type);
952 case UnmanagedType.ByValArray:
953 FieldMember fm = attr as FieldMember;
955 Error_AttributeEmitError ("Specified unmanaged type is only valid on fields");
958 return UnmanagedMarshal.DefineByValArray ((int) GetFieldValue ("SizeConst"));
960 case UnmanagedType.ByValTStr:
961 return UnmanagedMarshal.DefineByValTStr ((int) GetFieldValue ("SizeConst"));
964 return UnmanagedMarshal.DefineUnmanagedMarshal (UnmanagedType);
968 public bool IsInternalCall
970 get { return ImplOptions == MethodImplOptions.InternalCall; }
974 /// Emit attribute for Attributable symbol
976 public void Emit (EmitContext ec, Attributable ias, ListDictionary emitted_attr)
978 CustomAttributeBuilder cb = Resolve (ec);
982 AttributeUsageAttribute usage_attr = GetAttributeUsage (ec);
983 if ((usage_attr.ValidOn & Target) == 0) {
984 Report.Error (592, Location, "Attribute '{0}' is not valid on this declaration type. It is valid on {1} declarations only.", Name, GetValidTargets ());
988 ias.ApplyAttributeBuilder (this, cb);
990 if (!usage_attr.AllowMultiple) {
991 ArrayList emitted_targets = (ArrayList)emitted_attr [Type];
992 if (emitted_targets == null) {
993 emitted_targets = new ArrayList ();
994 emitted_attr.Add (Type, emitted_targets);
995 } else if (emitted_targets.Contains (Target)) {
996 Report.Error (579, Location, "Duplicate '" + Name + "' attribute");
999 emitted_targets.Add (Target);
1002 if (!RootContext.VerifyClsCompliance)
1005 // Here we are testing attribute arguments for array usage (error 3016)
1006 if (ias.IsClsCompliaceRequired (ec.DeclSpace)) {
1007 if (Arguments == null)
1010 ArrayList pos_args = (ArrayList) Arguments [0];
1011 if (pos_args != null) {
1012 foreach (Argument arg in pos_args) {
1013 // Type is undefined (was error 246)
1014 if (arg.Type == null)
1017 if (arg.Type.IsArray) {
1018 Report.Error (3016, Location, "Arrays as attribute arguments are not CLS-compliant");
1024 if (Arguments.Count < 2)
1027 ArrayList named_args = (ArrayList) Arguments [1];
1028 foreach (DictionaryEntry de in named_args) {
1029 Argument arg = (Argument) de.Value;
1031 // Type is undefined (was error 246)
1032 if (arg.Type == null)
1035 if (arg.Type.IsArray) {
1036 Report.Error (3016, Location, "Arrays as attribute arguments are not CLS-compliant");
1043 public object GetValue (EmitContext ec, Constant c, Type target)
1045 if (Convert.ImplicitConversionExists (ec, c, target))
1046 return c.GetValue ();
1048 Convert.Error_CannotImplicitConversion (Location, c.Type, target);
1052 public MethodBuilder DefinePInvokeMethod (EmitContext ec, TypeBuilder builder, string name,
1053 MethodAttributes flags, Type ret_type, Type [] param_types)
1056 // We extract from the attribute the information we need
1059 if (Arguments == null) {
1060 Console.WriteLine ("Internal error : this is not supposed to happen !");
1068 ArrayList named_args = new ArrayList ();
1070 ArrayList pos_args = (ArrayList) Arguments [0];
1071 if (Arguments.Count > 1)
1072 named_args = (ArrayList) Arguments [1];
1075 string dll_name = null;
1077 Argument tmp = (Argument) pos_args [0];
1079 if (!tmp.Resolve (ec, Location))
1082 if (tmp.Expr is Constant)
1083 dll_name = (string) ((Constant) tmp.Expr).GetValue ();
1085 Error_AttributeArgumentNotValid (Location);
1088 if (dll_name == null || dll_name == ""){
1089 Error_AttributeArgumentNotValid (": DllImport requires a non-empty string", Location);
1093 // Now we process the named arguments
1094 CallingConvention cc = CallingConvention.Winapi;
1095 CharSet charset = CharSet.Ansi;
1096 bool preserve_sig = true;
1098 bool exact_spelling = false;
1100 bool set_last_err = false;
1101 string entry_point = null;
1103 for (int i = 0; i < named_args.Count; i++) {
1105 DictionaryEntry de = (DictionaryEntry) named_args [i];
1107 string member_name = (string) de.Key;
1108 Argument a = (Argument) de.Value;
1110 if (!a.Resolve (ec, Location))
1113 Expression member = Expression.MemberLookup (
1114 ec, Type, member_name,
1115 MemberTypes.Field | MemberTypes.Property,
1116 BindingFlags.Public | BindingFlags.Instance,
1119 if (member == null || !(member is FieldExpr)) {
1120 Error_InvalidNamedArgument (member_name);
1124 if (member is FieldExpr) {
1125 FieldExpr fe = (FieldExpr) member;
1126 FieldInfo fi = fe.FieldInfo;
1128 if (fi.IsInitOnly) {
1129 Error_InvalidNamedArgument (member_name);
1133 if (a.Expr is Constant) {
1134 Constant c = (Constant) a.Expr;
1137 if (member_name == "CallingConvention"){
1138 object val = GetValue (ec, c, typeof (CallingConvention));
1141 cc = (CallingConvention) val;
1142 } else if (member_name == "CharSet"){
1143 charset = (CharSet) c.GetValue ();
1144 } else if (member_name == "EntryPoint")
1145 entry_point = (string) c.GetValue ();
1146 else if (member_name == "SetLastError")
1147 set_last_err = (bool) c.GetValue ();
1149 else if (member_name == "ExactSpelling")
1150 exact_spelling = (bool) c.GetValue ();
1152 else if (member_name == "PreserveSig")
1153 preserve_sig = (bool) c.GetValue ();
1154 } catch (InvalidCastException){
1155 Error_InvalidNamedArgument (member_name);
1156 Error_AttributeArgumentNotValid (Location);
1159 Error_AttributeArgumentNotValid (Location);
1166 if (entry_point == null)
1169 charset = (CharSet)((int)charset | 0x40);
1171 MethodBuilder mb = builder.DefinePInvokeMethod (
1172 name, dll_name, entry_point, flags | MethodAttributes.HideBySig,
1173 CallingConventions.Standard,
1180 mb.SetImplementationFlags (MethodImplAttributes.PreserveSig);
1185 private Expression GetValue ()
1187 if ((Arguments == null) || (Arguments.Count < 1))
1189 ArrayList al = (ArrayList) Arguments [0];
1190 if ((al == null) || (al.Count < 1))
1192 Argument arg = (Argument) al [0];
1193 if ((arg == null) || (arg.Expr == null))
1198 public string GetString ()
1200 Expression e = GetValue ();
1201 if (e is StringLiteral)
1202 return (e as StringLiteral).Value;
1206 public bool GetBoolean ()
1208 Expression e = GetValue ();
1209 if (e is BoolLiteral)
1210 return (e as BoolLiteral).Value;
1217 /// For global attributes (assembly, module) we need special handling.
1218 /// Attributes can be located in the several files
1220 public class GlobalAttribute: Attribute
1222 public readonly NamespaceEntry ns;
1224 public GlobalAttribute (TypeContainer container, string target,
1225 Expression left_expr, string identifier, ArrayList args, Location loc):
1226 base (target, left_expr, identifier, args, loc)
1228 ns = container.NamespaceEntry;
1233 // RootContext.Tree.Types has a single NamespaceEntry which gets overwritten
1234 // each time a new file is parsed. However, we need to use the NamespaceEntry
1235 // in effect where the attribute was used. Since code elsewhere cannot assume
1236 // that the NamespaceEntry is right, just overwrite it.
1238 // Precondition: RootContext.Tree.Types == null
1240 if (RootContext.Tree.Types.NamespaceEntry != null)
1241 throw new InternalErrorException (Location + " non-null NamespaceEntry");
1243 RootContext.Tree.Types.NamespaceEntry = ns;
1248 RootContext.Tree.Types.NamespaceEntry = null;
1251 public override Type ResolveType (EmitContext ec)
1254 Type retval = base.ResolveType (ec);
1259 public override CustomAttributeBuilder Resolve (EmitContext ec)
1262 CustomAttributeBuilder retval = base.Resolve (ec);
1268 public class Attributes {
1269 public ArrayList Attrs;
1271 public Attributes (Attribute a)
1273 Attrs = new ArrayList ();
1277 public Attributes (ArrayList attrs)
1282 public void AddAttributes (ArrayList attrs)
1284 Attrs.AddRange (attrs);
1288 /// Checks whether attribute target is valid for the current element
1290 public bool CheckTargets (Attributable member)
1292 string[] valid_targets = member.ValidAttributeTargets;
1293 foreach (Attribute a in Attrs) {
1294 if (a.ExplicitTarget == null || a.ExplicitTarget == valid_targets [0]) {
1295 a.Target = member.AttributeTargets;
1299 // TODO: we can skip the first item
1300 if (((IList) valid_targets).Contains (a.ExplicitTarget)) {
1301 switch (a.ExplicitTarget) {
1302 case "return": a.Target = AttributeTargets.ReturnValue; continue;
1303 case "param": a.Target = AttributeTargets.Parameter; continue;
1304 case "field": a.Target = AttributeTargets.Field; continue;
1305 case "method": a.Target = AttributeTargets.Method; continue;
1306 case "property": a.Target = AttributeTargets.Property; continue;
1308 throw new InternalErrorException ("Unknown explicit target: " + a.ExplicitTarget);
1311 StringBuilder sb = new StringBuilder ();
1312 foreach (string s in valid_targets) {
1316 sb.Remove (sb.Length - 2, 2);
1317 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 ());
1323 public Attribute Search (Type t, EmitContext ec)
1325 foreach (Attribute a in Attrs) {
1326 if (a.ResolveType (ec) == t)
1333 /// Returns all attributes of type 't'. Use it when attribute is AllowMultiple = true
1335 public Attribute[] SearchMulti (Type t, EmitContext ec)
1337 ArrayList ar = null;
1339 foreach (Attribute a in Attrs) {
1340 if (a.ResolveType (ec) == t) {
1342 ar = new ArrayList ();
1347 return ar == null ? null : ar.ToArray (typeof (Attribute)) as Attribute[];
1350 public void Emit (EmitContext ec, Attributable ias)
1352 if (!CheckTargets (ias))
1355 ListDictionary ld = new ListDictionary ();
1357 foreach (Attribute a in Attrs)
1358 a.Emit (ec, ias, ld);
1361 public bool Contains (Type t, EmitContext ec)
1363 return Search (t, ec) != null;
1368 /// Helper class for attribute verification routine.
1370 sealed class AttributeTester
1372 static PtrHashtable analyzed_types = new PtrHashtable ();
1373 static PtrHashtable analyzed_types_obsolete = new PtrHashtable ();
1374 static PtrHashtable analyzed_member_obsolete = new PtrHashtable ();
1375 static PtrHashtable analyzed_method_excluded = new PtrHashtable ();
1376 static PtrHashtable fixed_buffer_cache = new PtrHashtable ();
1378 static object TRUE = new object ();
1379 static object FALSE = new object ();
1381 private AttributeTester ()
1386 /// Returns true if parameters of two compared methods are CLS-Compliant.
1387 /// It tests differing only in ref or out, or in array rank.
1389 public static bool AreOverloadedMethodParamsClsCompliant (Type[] types_a, Type[] types_b)
1391 if (types_a == null || types_b == null)
1394 if (types_a.Length != types_b.Length)
1397 for (int i = 0; i < types_b.Length; ++i) {
1398 Type aType = types_a [i];
1399 Type bType = types_b [i];
1401 if (aType.IsArray && bType.IsArray && aType.GetArrayRank () != bType.GetArrayRank () && aType.GetElementType () == bType.GetElementType ()) {
1405 Type aBaseType = aType;
1406 bool is_either_ref_or_out = false;
1408 if (aType.IsByRef || aType.IsPointer) {
1409 aBaseType = aType.GetElementType ();
1410 is_either_ref_or_out = true;
1413 Type bBaseType = bType;
1414 if (bType.IsByRef || bType.IsPointer)
1416 bBaseType = bType.GetElementType ();
1417 is_either_ref_or_out = !is_either_ref_or_out;
1420 if (aBaseType != bBaseType)
1423 if (is_either_ref_or_out)
1430 /// Goes through all parameters and test if they are CLS-Compliant.
1432 public static bool AreParametersCompliant (Parameter[] fixedParameters, Location loc)
1434 if (fixedParameters == null)
1437 foreach (Parameter arg in fixedParameters) {
1438 if (!AttributeTester.IsClsCompliant (arg.ParameterType)) {
1439 Report.Error (3001, loc, "Argument type '{0}' is not CLS-compliant", arg.GetSignatureForError ());
1448 /// This method tests the CLS compliance of external types. It doesn't test type visibility.
1450 public static bool IsClsCompliant (Type type)
1455 object type_compliance = analyzed_types[type];
1456 if (type_compliance != null)
1457 return type_compliance == TRUE;
1459 if (type.IsPointer) {
1460 analyzed_types.Add (type, null);
1465 if (type.IsArray || type.IsByRef) {
1466 result = IsClsCompliant (TypeManager.GetElementType (type));
1468 result = AnalyzeTypeCompliance (type);
1470 analyzed_types.Add (type, result ? TRUE : FALSE);
1475 /// Returns IFixedBuffer implementation if field is fixed buffer else null.
1477 public static IFixedBuffer GetFixedBuffer (FieldInfo fi)
1479 FieldBase fb = TypeManager.GetField (fi);
1481 return fb as IFixedBuffer;
1485 object o = fixed_buffer_cache [fi];
1487 if (System.Attribute.GetCustomAttribute (fi, TypeManager.fixed_buffer_attr_type) == null) {
1488 fixed_buffer_cache.Add (fi, FALSE);
1492 IFixedBuffer iff = new FixedFieldExternal (fi);
1493 fixed_buffer_cache.Add (fi, iff);
1500 return (IFixedBuffer)o;
1506 public static void VerifyModulesClsCompliance ()
1508 Module[] modules = TypeManager.Modules;
1509 if (modules == null)
1512 // The first module is generated assembly
1513 for (int i = 1; i < modules.Length; ++i) {
1514 Module module = modules [i];
1515 if (!IsClsCompliant (module)) {
1516 Report.Error (3013, "Added modules must be marked with the CLSCompliant attribute to match the assembly", module.Name);
1523 /// Tests container name for CLS-Compliant name (differing only in case)
1525 public static void VerifyTopLevelNameClsCompliance ()
1527 Hashtable locase_table = new Hashtable ();
1529 // Convert imported type names to lower case and ignore not cls compliant
1530 foreach (DictionaryEntry de in TypeManager.all_imported_types) {
1531 Type t = (Type)de.Value;
1532 if (!AttributeTester.IsClsCompliant (t))
1535 locase_table.Add (((string)de.Key).ToLower (System.Globalization.CultureInfo.InvariantCulture), t);
1538 foreach (DictionaryEntry de in RootContext.Tree.Decls) {
1539 DeclSpace decl = (DeclSpace)de.Value;
1540 if (!decl.IsClsCompliaceRequired (decl))
1543 string lcase = decl.Name.ToLower (System.Globalization.CultureInfo.InvariantCulture);
1544 if (!locase_table.Contains (lcase)) {
1545 locase_table.Add (lcase, decl);
1549 object conflict = locase_table [lcase];
1550 if (conflict is Type)
1551 Report.SymbolRelatedToPreviousError ((Type)conflict);
1553 Report.SymbolRelatedToPreviousError ((MemberCore)conflict);
1555 Report.Error (3005, decl.Location, "Identifier '{0}' differing only in case is not CLS-compliant", decl.GetSignatureForError ());
1559 static bool IsClsCompliant (ICustomAttributeProvider attribute_provider)
1561 object[] CompliantAttribute = attribute_provider.GetCustomAttributes (TypeManager.cls_compliant_attribute_type, false);
1562 if (CompliantAttribute.Length == 0)
1565 return ((CLSCompliantAttribute)CompliantAttribute[0]).IsCompliant;
1568 static bool AnalyzeTypeCompliance (Type type)
1570 DeclSpace ds = TypeManager.LookupDeclSpace (type);
1572 return ds.IsClsCompliaceRequired (ds.Parent);
1575 object[] CompliantAttribute = type.GetCustomAttributes (TypeManager.cls_compliant_attribute_type, false);
1576 if (CompliantAttribute.Length == 0)
1577 return IsClsCompliant (type.Assembly);
1579 return ((CLSCompliantAttribute)CompliantAttribute[0]).IsCompliant;
1583 /// Returns instance of ObsoleteAttribute when type is obsolete
1585 public static ObsoleteAttribute GetObsoleteAttribute (Type type)
1587 object type_obsolete = analyzed_types_obsolete [type];
1588 if (type_obsolete == FALSE)
1591 if (type_obsolete != null)
1592 return (ObsoleteAttribute)type_obsolete;
1594 ObsoleteAttribute result = null;
1595 if (type.IsByRef || type.IsArray || type.IsPointer) {
1596 result = GetObsoleteAttribute (TypeManager.GetElementType (type));
1598 DeclSpace type_ds = TypeManager.LookupDeclSpace (type);
1600 // Type is external, we can get attribute directly
1601 if (type_ds == null) {
1602 object[] attribute = type.GetCustomAttributes (TypeManager.obsolete_attribute_type, false);
1603 if (attribute.Length == 1)
1604 result = (ObsoleteAttribute)attribute [0];
1606 result = type_ds.GetObsoleteAttribute (type_ds);
1610 analyzed_types_obsolete.Add (type, result == null ? FALSE : result);
1615 /// Returns instance of ObsoleteAttribute when method is obsolete
1617 public static ObsoleteAttribute GetMethodObsoleteAttribute (MethodBase mb)
1619 IMethodData mc = TypeManager.GetMethod (mb);
1621 return mc.GetObsoleteAttribute ();
1623 // compiler generated methods are not registered by AddMethod
1624 if (mb.DeclaringType is TypeBuilder)
1627 PropertyInfo pi = PropertyExpr.AccessorTable [mb] as PropertyInfo;
1629 return GetMemberObsoleteAttribute (pi);
1631 return GetMemberObsoleteAttribute (mb);
1635 /// Returns instance of ObsoleteAttribute when member is obsolete
1637 public static ObsoleteAttribute GetMemberObsoleteAttribute (MemberInfo mi)
1639 object type_obsolete = analyzed_member_obsolete [mi];
1640 if (type_obsolete == FALSE)
1643 if (type_obsolete != null)
1644 return (ObsoleteAttribute)type_obsolete;
1646 ObsoleteAttribute oa = System.Attribute.GetCustomAttribute (mi, TypeManager.obsolete_attribute_type, false) as ObsoleteAttribute;
1647 analyzed_member_obsolete.Add (mi, oa == null ? FALSE : oa);
1652 /// Common method for Obsolete error/warning reporting.
1654 public static void Report_ObsoleteMessage (ObsoleteAttribute oa, string member, Location loc)
1657 Report.Error (619, loc, "'{0}' is obsolete: '{1}'", member, oa.Message);
1661 if (oa.Message == null) {
1662 Report.Warning (612, loc, "'{0}' is obsolete", member);
1665 if (RootContext.WarningLevel >= 2)
1666 Report.Warning (618, loc, "'{0}' is obsolete: '{1}'", member, oa.Message);
1669 public static bool IsConditionalMethodExcluded (MethodBase mb)
1671 object excluded = analyzed_method_excluded [mb];
1672 if (excluded != null)
1673 return excluded == TRUE ? true : false;
1675 ConditionalAttribute[] attrs = mb.GetCustomAttributes (TypeManager.conditional_attribute_type, true) as ConditionalAttribute[];
1676 if (attrs.Length == 0) {
1677 analyzed_method_excluded.Add (mb, FALSE);
1681 foreach (ConditionalAttribute a in attrs) {
1682 if (RootContext.AllDefines.Contains (a.ConditionString)) {
1683 analyzed_method_excluded.Add (mb, FALSE);
1687 analyzed_method_excluded.Add (mb, TRUE);