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 // Is non-null if type is AttributeUsageAttribute
87 AttributeUsageAttribute usage_attribute;
89 public AttributeUsageAttribute UsageAttribute {
91 return usage_attribute;
95 MethodImplOptions ImplOptions;
96 UnmanagedType UnmanagedType;
97 CustomAttributeBuilder cb;
99 // non-null if named args present after Resolve () is called
100 PropertyInfo [] prop_info_arr;
101 FieldInfo [] field_info_arr;
102 object [] field_values_arr;
103 object [] prop_values_arr;
104 object [] pos_values;
106 static PtrHashtable usage_attr_cache = new PtrHashtable ();
108 public Attribute (string target, Expression left_expr, string identifier, ArrayList args, Location loc)
110 LeftExpr = left_expr;
111 Identifier = identifier;
112 Name = LeftExpr == null ? identifier : LeftExpr + "." + identifier;
115 ExplicitTarget = target;
118 void Error_InvalidNamedArgument (string name)
120 Report.Error (617, Location, "Invalid attribute argument: '{0}'. Argument must be fields " +
121 "fields which are not readonly, static or const; or read-write instance properties.",
125 static void Error_AttributeArgumentNotValid (string extra, Location loc)
127 Report.Error (182, loc,
128 "An attribute argument must be a constant expression, typeof " +
129 "expression or array creation expression" + extra);
132 static void Error_AttributeArgumentNotValid (Location loc)
134 Error_AttributeArgumentNotValid ("", loc);
139 /// This is rather hack. We report many emit attribute error with same error to be compatible with
140 /// csc. But because csc has to report them this way because error came from ilasm we needn't.
142 public void Error_AttributeEmitError (string inner)
144 Report.Error (647, Location, "Error emitting '{0}' attribute because '{1}'", Name, inner);
147 public void Error_InvalidSecurityParent ()
149 Error_AttributeEmitError ("it is attached to invalid parent");
152 void Error_AttributeConstructorMismatch ()
154 Report.Error (-6, Location,
155 "Could not find a constructor for this argument list.");
158 void ResolvePossibleAttributeTypes (EmitContext ec, out Type t1, out Type t2)
163 FullNamedExpression n1 = null;
164 FullNamedExpression n2 = null;
165 string IdentifierAttribute = Identifier + "Attribute";
166 if (LeftExpr == null) {
167 n1 = new SimpleName (Identifier, Location).ResolveAsTypeStep (ec);
169 // FIXME: Shouldn't do this for quoted attributes: [@A]
170 n2 = new SimpleName (IdentifierAttribute, Location).ResolveAsTypeStep (ec);
172 FullNamedExpression l = LeftExpr.ResolveAsTypeStep (ec);
174 Report.Error (246, Location, "Couldn't find namespace or type '{0}'", LeftExpr);
177 n1 = new MemberAccess (l, Identifier, Location).ResolveNamespaceOrType (ec, true);
179 // FIXME: Shouldn't do this for quoted attributes: [X.@A]
180 n2 = new MemberAccess (l, IdentifierAttribute, Location).ResolveNamespaceOrType (ec, true);
183 TypeExpr te1 = n1 == null ? null : n1 as TypeExpr;
184 TypeExpr te2 = n2 == null ? null : n2 as TypeExpr;
187 t1 = te1.ResolveType (ec);
189 t2 = te2.ResolveType (ec);
193 /// Tries to resolve the type of the attribute. Flags an error if it can't, and complain is true.
195 Type CheckAttributeType (EmitContext ec)
199 ResolvePossibleAttributeTypes (ec, out t1, out t2);
201 string NameAttribute = Name + "Attribute";
203 String err0616 = null;
205 if (t1 != null && ! t1.IsSubclassOf (TypeManager.attribute_type)) {
207 err0616 = "'" + Name + "': is not an attribute class";
209 if (t2 != null && ! t2.IsSubclassOf (TypeManager.attribute_type)) {
211 err0616 = (err0616 != null)
212 ? "Neither '" + Name + "' nor '" + NameAttribute +"' is an attribute class"
213 : "'" + Name + "Attribute': is not an attribute class";
216 if (t1 != null && t2 != null) {
217 Report.Error(1614, Location, "'" + Name + "': is ambiguous; "
218 + " use either '@" + Name + "' or '" + NameAttribute + "'");
226 if (err0616 != null) {
227 Report.Error (616, Location, err0616);
231 Report.Error (246, Location,
232 "Could not find attribute '" + Name
233 + "' (are you missing a using directive or an assembly reference ?)");
235 resolve_error = true;
239 public virtual Type ResolveType (EmitContext ec)
242 Type = CheckAttributeType (ec);
247 /// Validates the guid string
249 bool ValidateGuid (string guid)
255 Report.Error (647, Location, "Format of GUID is invalid: " + guid);
260 string GetFullMemberName (string member)
262 return Type.FullName + '.' + member;
266 // Given an expression, if the expression is a valid attribute-argument-expression
267 // returns an object that can be used to encode it, or null on failure.
269 public static bool GetAttributeArgumentExpression (Expression e, Location loc, Type arg_type, out object result)
271 if (e is EnumConstant) {
272 if (RootContext.StdLib)
273 result = ((EnumConstant)e).GetValueAsEnumType ();
275 result = ((EnumConstant)e).GetValue ();
280 Constant constant = e as Constant;
281 if (constant != null) {
282 if (e.Type != arg_type) {
283 constant = Const.ChangeType (loc, constant, arg_type);
284 if (constant == null) {
286 Error_AttributeArgumentNotValid (loc);
290 result = constant.GetValue ();
292 } else if (e is TypeOf) {
293 result = ((TypeOf) e).TypeArg;
295 } else if (e is ArrayCreation){
296 result = ((ArrayCreation) e).EncodeAsAttribute ();
299 } else if (e is EmptyCast) {
300 Expression child = ((EmptyCast)e).Child;
301 return GetAttributeArgumentExpression (child, loc, child.Type, out result);
305 Error_AttributeArgumentNotValid (loc);
309 public virtual CustomAttributeBuilder Resolve (EmitContext ec)
314 resolve_error = true;
319 Type = CheckAttributeType (ec);
321 if (oldType == null && Type == null)
323 if (oldType != null && oldType != Type){
324 Report.Error (-27, Location,
325 "Attribute {0} resolved to different types at different times: {1} vs. {2}",
326 Name, oldType, Type);
330 if (Type.IsAbstract) {
331 Report.Error (653, Location, "Cannot apply attribute class '{0}' because it is abstract", Name);
335 bool MethodImplAttr = false;
336 bool MarshalAsAttr = false;
337 bool GuidAttr = false;
338 bool usage_attr = false;
340 bool DoCompares = true;
343 // If we are a certain special attribute, we
344 // set the information accordingly
347 if (Type == TypeManager.attribute_usage_type)
349 else if (Type == TypeManager.methodimpl_attr_type)
350 MethodImplAttr = true;
351 else if (Type == TypeManager.marshal_as_attr_type)
352 MarshalAsAttr = true;
353 else if (Type == TypeManager.guid_attr_type)
358 // Now we extract the positional and named arguments
360 ArrayList pos_args = new ArrayList ();
361 ArrayList named_args = new ArrayList ();
362 int pos_arg_count = 0;
364 if (Arguments != null) {
365 pos_args = (ArrayList) Arguments [0];
366 if (pos_args != null)
367 pos_arg_count = pos_args.Count;
368 if (Arguments.Count > 1)
369 named_args = (ArrayList) Arguments [1];
372 pos_values = new object [pos_arg_count];
375 // First process positional arguments
379 for (i = 0; i < pos_arg_count; i++) {
380 Argument a = (Argument) pos_args [i];
383 if (!a.Resolve (ec, Location))
389 if (!GetAttributeArgumentExpression (e, Location, a.Type, out val))
392 pos_values [i] = val;
397 Report.Error (591, Location, "Invalid value for argument to 'System.AttributeUsage' attribute");
400 usage_attribute = new AttributeUsageAttribute ((AttributeTargets)val);
401 } else if (MethodImplAttr) {
402 this.ImplOptions = (MethodImplOptions) val;
403 } else if (GuidAttr){
405 // we will later check the validity of the type
408 if (!ValidateGuid ((string) val))
412 } else if (MarshalAsAttr)
414 (System.Runtime.InteropServices.UnmanagedType) val;
419 // Now process named arguments
422 ArrayList field_infos = null;
423 ArrayList prop_infos = null;
424 ArrayList field_values = null;
425 ArrayList prop_values = null;
427 if (named_args.Count > 0) {
428 field_infos = new ArrayList ();
429 prop_infos = new ArrayList ();
430 field_values = new ArrayList ();
431 prop_values = new ArrayList ();
434 Hashtable seen_names = new Hashtable();
436 for (i = 0; i < named_args.Count; i++) {
437 DictionaryEntry de = (DictionaryEntry) named_args [i];
438 string member_name = (string) de.Key;
439 Argument a = (Argument) de.Value;
442 if (seen_names.Contains(member_name)) {
443 Report.Error(643, Location, "'" + member_name + "' duplicate named attribute argument");
446 seen_names.Add(member_name, 1);
448 if (!a.Resolve (ec, Location))
451 Expression member = Expression.MemberLookup (
452 ec, Type, member_name,
453 MemberTypes.Field | MemberTypes.Property,
454 BindingFlags.Public | BindingFlags.Instance,
457 if (member == null) {
458 member = Expression.MemberLookup (ec, Type, member_name,
459 MemberTypes.Field | MemberTypes.Property, BindingFlags.NonPublic | BindingFlags.Instance,
462 if (member != null) {
463 Report.Error (122, Location, "'{0}' is inaccessible due to its protection level", GetFullMemberName (member_name));
469 Report.Error (117, Location, "Attribute `{0}' does not contain a definition for `{1}'",
474 if (!(member is PropertyExpr || member is FieldExpr)) {
475 Error_InvalidNamedArgument (member_name);
480 if (member is PropertyExpr) {
481 PropertyExpr pe = (PropertyExpr) member;
482 PropertyInfo pi = pe.PropertyInfo;
484 if (!pi.CanWrite || !pi.CanRead) {
485 Report.SymbolRelatedToPreviousError (pi);
486 Error_InvalidNamedArgument (member_name);
491 if (!GetAttributeArgumentExpression (e, Location, pi.PropertyType, out value))
494 if (usage_attribute != null) {
495 if (member_name == "AllowMultiple")
496 usage_attribute.AllowMultiple = (bool) value;
497 if (member_name == "Inherited")
498 usage_attribute.Inherited = (bool) value;
501 prop_values.Add (value);
504 } else if (member is FieldExpr) {
505 FieldExpr fe = (FieldExpr) member;
506 FieldInfo fi = fe.FieldInfo;
509 Error_InvalidNamedArgument (member_name);
514 if (!GetAttributeArgumentExpression (e, Location, fi.FieldType, out value))
517 field_values.Add (value);
518 field_infos.Add (fi);
522 Expression mg = Expression.MemberLookup (
523 ec, Type, ".ctor", MemberTypes.Constructor,
524 BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly,
528 Error_AttributeConstructorMismatch ();
532 MethodBase constructor = Invocation.OverloadResolve (
533 ec, (MethodGroupExpr) mg, pos_args, false, Location);
535 if (constructor == null) {
540 // Now we perform some checks on the positional args as they
541 // cannot be null for a constructor which expects a parameter
545 ParameterData pd = TypeManager.GetParameterData (constructor);
547 int last_real_param = pd.Count;
549 // When the params is not filled we need to put one
550 if (last_real_param > pos_arg_count) {
551 object [] new_pos_values = new object [pos_arg_count + 1];
552 pos_values.CopyTo (new_pos_values, 0);
553 new_pos_values [pos_arg_count] = new object [] {} ;
554 pos_values = new_pos_values;
559 for (int j = 0; j < pos_arg_count; ++j) {
560 Argument a = (Argument) pos_args [j];
562 if (a.Expr is NullLiteral && pd.ParameterType (j) == TypeManager.object_type) {
563 Error_AttributeArgumentNotValid (Location);
567 if (j < last_real_param)
570 if (j == last_real_param) {
571 object [] array = new object [pos_arg_count - last_real_param];
572 array [0] = pos_values [j];
573 pos_values [j] = array;
577 object [] params_array = (object []) pos_values [last_real_param];
578 params_array [j - last_real_param] = pos_values [j];
581 // Adjust the size of the pos_values if it had params
582 if (last_real_param != pos_arg_count) {
583 object [] new_pos_values = new object [last_real_param + 1];
584 Array.Copy (pos_values, new_pos_values, last_real_param + 1);
585 pos_values = new_pos_values;
589 if (named_args.Count > 0) {
590 prop_info_arr = new PropertyInfo [prop_infos.Count];
591 field_info_arr = new FieldInfo [field_infos.Count];
592 field_values_arr = new object [field_values.Count];
593 prop_values_arr = new object [prop_values.Count];
595 field_infos.CopyTo (field_info_arr, 0);
596 field_values.CopyTo (field_values_arr, 0);
598 prop_values.CopyTo (prop_values_arr, 0);
599 prop_infos.CopyTo (prop_info_arr, 0);
601 cb = new CustomAttributeBuilder (
602 (ConstructorInfo) constructor, pos_values,
603 prop_info_arr, prop_values_arr,
604 field_info_arr, field_values_arr);
607 cb = new CustomAttributeBuilder (
608 (ConstructorInfo) constructor, pos_values);
609 } catch (Exception e) {
612 // using System.ComponentModel;
613 // [DefaultValue (CollectionChangeAction.Add)]
614 // class X { static void Main () {} }
616 Error_AttributeArgumentNotValid (Location);
620 resolve_error = false;
625 /// Get a string containing a list of valid targets for the attribute 'attr'
627 public string GetValidTargets ()
629 StringBuilder sb = new StringBuilder ();
630 AttributeTargets targets = GetAttributeUsage ().ValidOn;
632 if ((targets & AttributeTargets.Assembly) != 0)
633 sb.Append ("'assembly' ");
635 if ((targets & AttributeTargets.Class) != 0)
636 sb.Append ("'class' ");
638 if ((targets & AttributeTargets.Constructor) != 0)
639 sb.Append ("'constructor' ");
641 if ((targets & AttributeTargets.Delegate) != 0)
642 sb.Append ("'delegate' ");
644 if ((targets & AttributeTargets.Enum) != 0)
645 sb.Append ("'enum' ");
647 if ((targets & AttributeTargets.Event) != 0)
648 sb.Append ("'event' ");
650 if ((targets & AttributeTargets.Field) != 0)
651 sb.Append ("'field' ");
653 if ((targets & AttributeTargets.Interface) != 0)
654 sb.Append ("'interface' ");
656 if ((targets & AttributeTargets.Method) != 0)
657 sb.Append ("'method' ");
659 if ((targets & AttributeTargets.Module) != 0)
660 sb.Append ("'module' ");
662 if ((targets & AttributeTargets.Parameter) != 0)
663 sb.Append ("'parameter' ");
665 if ((targets & AttributeTargets.Property) != 0)
666 sb.Append ("'property' ");
668 if ((targets & AttributeTargets.ReturnValue) != 0)
669 sb.Append ("'return' ");
671 if ((targets & AttributeTargets.Struct) != 0)
672 sb.Append ("'struct' ");
674 return sb.ToString ();
679 /// Returns AttributeUsage attribute for this type
681 public AttributeUsageAttribute GetAttributeUsage ()
683 AttributeUsageAttribute ua = usage_attr_cache [Type] as AttributeUsageAttribute;
687 Class attr_class = TypeManager.LookupClass (Type);
689 if (attr_class == null) {
690 object[] usage_attr = Type.GetCustomAttributes (TypeManager.attribute_usage_type, true);
691 ua = (AttributeUsageAttribute)usage_attr [0];
692 usage_attr_cache.Add (Type, ua);
696 return attr_class.AttributeUsage;
700 /// Returns custom name of indexer
702 public string GetIndexerAttributeValue (EmitContext ec)
704 if (pos_values == null)
705 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
706 // But because a lot of attribute class code must be rewritten will be better to wait...
709 return pos_values [0] as string;
713 /// Returns condition of ConditionalAttribute
715 public string GetConditionalAttributeValue (EmitContext ec)
717 if (pos_values == null)
718 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
719 // But because a lot of attribute class code must be rewritten will be better to wait...
722 // Some error occurred
723 if (pos_values [0] == null)
726 return (string)pos_values [0];
730 /// Creates the instance of ObsoleteAttribute from this attribute instance
732 public ObsoleteAttribute GetObsoleteAttribute (EmitContext ec)
734 if (pos_values == null)
735 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
736 // But because a lot of attribute class code must be rewritten will be better to wait...
739 // Some error occurred
740 if (pos_values == null)
743 if (pos_values.Length == 0)
744 return new ObsoleteAttribute ();
746 if (pos_values.Length == 1)
747 return new ObsoleteAttribute ((string)pos_values [0]);
749 return new ObsoleteAttribute ((string)pos_values [0], (bool)pos_values [1]);
753 /// Returns value of CLSCompliantAttribute contructor parameter but because the method can be called
754 /// before ApplyAttribute. We need to resolve the arguments.
755 /// This situation occurs when class deps is differs from Emit order.
757 public bool GetClsCompliantAttributeValue (EmitContext ec)
759 if (pos_values == null)
760 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
761 // But because a lot of attribute class code must be rewritten will be better to wait...
764 // Some error occurred
765 if (pos_values [0] == null)
768 return (bool)pos_values [0];
772 /// Tests permitted SecurityAction for assembly or other types
774 public bool CheckSecurityActionValidity (bool for_assembly)
776 SecurityAction action = GetSecurityActionValue ();
778 if ((action == SecurityAction.RequestMinimum || action == SecurityAction.RequestOptional || action == SecurityAction.RequestRefuse) && for_assembly)
782 if (action < SecurityAction.Demand || action > SecurityAction.InheritanceDemand) {
783 Error_AttributeEmitError ("SecurityAction is out of range");
787 if ((action != SecurityAction.RequestMinimum && action != SecurityAction.RequestOptional && action != SecurityAction.RequestRefuse) && !for_assembly)
791 Error_AttributeEmitError (String.Concat ("SecurityAction '", action, "' is not valid for this declaration"));
795 System.Security.Permissions.SecurityAction GetSecurityActionValue ()
797 return (SecurityAction)pos_values [0];
801 /// Creates instance of SecurityAttribute class and add result of CreatePermission method to permission table.
803 /// <returns></returns>
804 public void ExtractSecurityPermissionSet (ListDictionary permissions)
806 if (TypeManager.LookupDeclSpace (Type) != null && RootContext.StdLib) {
807 Error_AttributeEmitError ("security custom attributes can not be referenced from defining assembly");
811 SecurityAttribute sa;
812 // For all assemblies except corlib we can avoid all hacks
813 if (RootContext.StdLib) {
814 sa = (SecurityAttribute) Activator.CreateInstance (Type, pos_values);
816 if (prop_info_arr != null) {
817 for (int i = 0; i < prop_info_arr.Length; ++i) {
818 PropertyInfo pi = prop_info_arr [i];
819 pi.SetValue (sa, prop_values_arr [i], null);
823 Type temp_type = Type.GetType (Type.FullName);
824 // HACK: All mscorlib attributes have same ctor syntax
825 sa = (SecurityAttribute) Activator.CreateInstance (temp_type, new object[] { GetSecurityActionValue () } );
827 // All types are from newly created corlib but for invocation with old we need to convert them
828 if (prop_info_arr != null) {
829 for (int i = 0; i < prop_info_arr.Length; ++i) {
830 PropertyInfo emited_pi = prop_info_arr [i];
831 PropertyInfo pi = temp_type.GetProperty (emited_pi.Name, emited_pi.PropertyType);
833 object old_instance = pi.PropertyType.IsEnum ?
834 System.Enum.ToObject (pi.PropertyType, prop_values_arr [i]) :
837 pi.SetValue (sa, old_instance, null);
844 perm = sa.CreatePermission ();
846 catch (Exception e) {
847 Error_AttributeEmitError (String.Format ("{0} was thrown during attribute processing: {1}", e.GetType (), e.Message));
850 SecurityAction action = GetSecurityActionValue ();
852 // IS is correct because for corlib we are using an instance from old corlib
853 if (!(perm is System.Security.CodeAccessPermission)) {
855 case SecurityAction.Demand:
856 action = (SecurityAction)13;
858 case SecurityAction.LinkDemand:
859 action = (SecurityAction)14;
861 case SecurityAction.InheritanceDemand:
862 action = (SecurityAction)15;
867 PermissionSet ps = (PermissionSet)permissions [action];
869 if (sa is PermissionSetAttribute)
870 ps = new PermissionSet (sa.Unrestricted ? PermissionState.Unrestricted : PermissionState.None);
872 ps = new PermissionSet (PermissionState.None);
874 permissions.Add (action, ps);
875 } else if (!ps.IsUnrestricted () && sa.Unrestricted) {
876 ps = ps.Union (new PermissionSet (PermissionState.Unrestricted));
877 permissions [action] = ps;
879 ps.AddPermission (perm);
882 object GetValue (object value)
884 if (value is EnumConstant)
885 return ((EnumConstant) value).GetValue ();
890 public object GetPositionalValue (int i)
892 return (pos_values == null) ? null : pos_values[i];
895 object GetFieldValue (string name)
898 if (field_info_arr == null)
901 foreach (FieldInfo fi in field_info_arr) {
903 return GetValue (field_values_arr [i]);
909 public UnmanagedMarshal GetMarshal (Attributable attr)
911 object value = GetFieldValue ("SizeParamIndex");
912 if (value != null && UnmanagedType != UnmanagedType.LPArray) {
913 Error_AttributeEmitError ("SizeParamIndex field is not valid for the specified unmanaged type");
917 object o = GetFieldValue ("ArraySubType");
918 UnmanagedType array_sub_type = o == null ? UnmanagedType.I4 : (UnmanagedType) o;
920 switch (UnmanagedType) {
921 case UnmanagedType.CustomMarshaler:
922 MethodInfo define_custom = typeof (UnmanagedMarshal).GetMethod ("DefineCustom",
923 BindingFlags.Static | BindingFlags.Public);
924 if (define_custom == null) {
925 Report.RuntimeMissingSupport (Location, "set marshal info");
929 object [] args = new object [4];
930 args [0] = GetFieldValue ("MarshalTypeRef");
931 args [1] = GetFieldValue ("MarshalCookie");
932 args [2] = GetFieldValue ("MarshalType");
933 args [3] = Guid.Empty;
934 return (UnmanagedMarshal) define_custom.Invoke (null, args);
936 case UnmanagedType.LPArray:
937 return UnmanagedMarshal.DefineLPArray (array_sub_type);
939 case UnmanagedType.SafeArray:
940 return UnmanagedMarshal.DefineSafeArray (array_sub_type);
942 case UnmanagedType.ByValArray:
943 FieldMember fm = attr as FieldMember;
945 Error_AttributeEmitError ("Specified unmanaged type is only valid on fields");
948 return UnmanagedMarshal.DefineByValArray ((int) GetFieldValue ("SizeConst"));
950 case UnmanagedType.ByValTStr:
951 return UnmanagedMarshal.DefineByValTStr ((int) GetFieldValue ("SizeConst"));
954 return UnmanagedMarshal.DefineUnmanagedMarshal (UnmanagedType);
958 public bool IsInternalCall
960 get { return ImplOptions == MethodImplOptions.InternalCall; }
964 /// Emit attribute for Attributable symbol
966 public void Emit (EmitContext ec, Attributable ias, ListDictionary emitted_attr)
968 CustomAttributeBuilder cb = Resolve (ec);
972 AttributeUsageAttribute usage_attr = GetAttributeUsage ();
973 if ((usage_attr.ValidOn & Target) == 0) {
974 Report.Error (592, Location, "Attribute '{0}' is not valid on this declaration type. It is valid on {1} declarations only.", Name, GetValidTargets ());
978 ias.ApplyAttributeBuilder (this, cb);
980 if (!usage_attr.AllowMultiple) {
981 ArrayList emitted_targets = (ArrayList)emitted_attr [Type];
982 if (emitted_targets == null) {
983 emitted_targets = new ArrayList ();
984 emitted_attr.Add (Type, emitted_targets);
985 } else if (emitted_targets.Contains (Target)) {
986 Report.Error (579, Location, "Duplicate '" + Name + "' attribute");
989 emitted_targets.Add (Target);
992 if (!RootContext.VerifyClsCompliance)
995 // Here we are testing attribute arguments for array usage (error 3016)
996 if (ias.IsClsCompliaceRequired (ec.DeclSpace)) {
997 if (Arguments == null)
1000 ArrayList pos_args = (ArrayList) Arguments [0];
1001 if (pos_args != null) {
1002 foreach (Argument arg in pos_args) {
1003 // Type is undefined (was error 246)
1004 if (arg.Type == null)
1007 if (arg.Type.IsArray) {
1008 Report.Error (3016, Location, "Arrays as attribute arguments are not CLS-compliant");
1014 if (Arguments.Count < 2)
1017 ArrayList named_args = (ArrayList) Arguments [1];
1018 foreach (DictionaryEntry de in named_args) {
1019 Argument arg = (Argument) de.Value;
1021 // Type is undefined (was error 246)
1022 if (arg.Type == null)
1025 if (arg.Type.IsArray) {
1026 Report.Error (3016, Location, "Arrays as attribute arguments are not CLS-compliant");
1033 public object GetValue (EmitContext ec, Constant c, Type target)
1035 if (Convert.ImplicitConversionExists (ec, c, target))
1036 return c.GetValue ();
1038 Convert.Error_CannotImplicitConversion (Location, c.Type, target);
1042 public MethodBuilder DefinePInvokeMethod (EmitContext ec, TypeBuilder builder, string name,
1043 MethodAttributes flags, Type ret_type, Type [] param_types)
1046 // We extract from the attribute the information we need
1049 if (Arguments == null) {
1050 Console.WriteLine ("Internal error : this is not supposed to happen !");
1058 ArrayList named_args = new ArrayList ();
1060 ArrayList pos_args = (ArrayList) Arguments [0];
1061 if (Arguments.Count > 1)
1062 named_args = (ArrayList) Arguments [1];
1065 string dll_name = null;
1067 Argument tmp = (Argument) pos_args [0];
1069 if (!tmp.Resolve (ec, Location))
1072 if (tmp.Expr is Constant)
1073 dll_name = (string) ((Constant) tmp.Expr).GetValue ();
1075 Error_AttributeArgumentNotValid (Location);
1078 if (dll_name == null || dll_name == ""){
1079 Error_AttributeArgumentNotValid (": DllImport requires a non-empty string", Location);
1083 // Now we process the named arguments
1084 CallingConvention cc = CallingConvention.Winapi;
1085 CharSet charset = CharSet.Ansi;
1086 bool preserve_sig = true;
1088 bool exact_spelling = false;
1090 bool set_last_err = false;
1091 string entry_point = null;
1093 for (int i = 0; i < named_args.Count; i++) {
1095 DictionaryEntry de = (DictionaryEntry) named_args [i];
1097 string member_name = (string) de.Key;
1098 Argument a = (Argument) de.Value;
1100 if (!a.Resolve (ec, Location))
1103 Expression member = Expression.MemberLookup (
1104 ec, Type, member_name,
1105 MemberTypes.Field | MemberTypes.Property,
1106 BindingFlags.Public | BindingFlags.Instance,
1109 if (member == null || !(member is FieldExpr)) {
1110 Error_InvalidNamedArgument (member_name);
1114 if (member is FieldExpr) {
1115 FieldExpr fe = (FieldExpr) member;
1116 FieldInfo fi = fe.FieldInfo;
1118 if (fi.IsInitOnly) {
1119 Error_InvalidNamedArgument (member_name);
1123 if (a.Expr is Constant) {
1124 Constant c = (Constant) a.Expr;
1127 if (member_name == "CallingConvention"){
1128 object val = GetValue (ec, c, typeof (CallingConvention));
1131 cc = (CallingConvention) val;
1132 } else if (member_name == "CharSet"){
1133 charset = (CharSet) c.GetValue ();
1134 } else if (member_name == "EntryPoint")
1135 entry_point = (string) c.GetValue ();
1136 else if (member_name == "SetLastError")
1137 set_last_err = (bool) c.GetValue ();
1139 else if (member_name == "ExactSpelling")
1140 exact_spelling = (bool) c.GetValue ();
1142 else if (member_name == "PreserveSig")
1143 preserve_sig = (bool) c.GetValue ();
1144 } catch (InvalidCastException){
1145 Error_InvalidNamedArgument (member_name);
1146 Error_AttributeArgumentNotValid (Location);
1149 Error_AttributeArgumentNotValid (Location);
1156 if (entry_point == null)
1159 charset = (CharSet)((int)charset | 0x40);
1161 MethodBuilder mb = builder.DefinePInvokeMethod (
1162 name, dll_name, entry_point, flags | MethodAttributes.HideBySig,
1163 CallingConventions.Standard,
1170 mb.SetImplementationFlags (MethodImplAttributes.PreserveSig);
1175 private Expression GetValue ()
1177 if ((Arguments == null) || (Arguments.Count < 1))
1179 ArrayList al = (ArrayList) Arguments [0];
1180 if ((al == null) || (al.Count < 1))
1182 Argument arg = (Argument) al [0];
1183 if ((arg == null) || (arg.Expr == null))
1188 public string GetString ()
1190 Expression e = GetValue ();
1191 if (e is StringLiteral)
1192 return (e as StringLiteral).Value;
1196 public bool GetBoolean ()
1198 Expression e = GetValue ();
1199 if (e is BoolLiteral)
1200 return (e as BoolLiteral).Value;
1207 /// For global attributes (assembly, module) we need special handling.
1208 /// Attributes can be located in the several files
1210 public class GlobalAttribute: Attribute
1212 public readonly NamespaceEntry ns;
1214 public GlobalAttribute (TypeContainer container, string target,
1215 Expression left_expr, string identifier, ArrayList args, Location loc):
1216 base (target, left_expr, identifier, args, loc)
1218 ns = container.NamespaceEntry;
1223 // RootContext.Tree.Types has a single NamespaceEntry which gets overwritten
1224 // each time a new file is parsed. However, we need to use the NamespaceEntry
1225 // in effect where the attribute was used. Since code elsewhere cannot assume
1226 // that the NamespaceEntry is right, just overwrite it.
1228 // Precondition: RootContext.Tree.Types == null
1230 if (RootContext.Tree.Types.NamespaceEntry != null)
1231 throw new InternalErrorException (Location + " non-null NamespaceEntry");
1233 RootContext.Tree.Types.NamespaceEntry = ns;
1238 RootContext.Tree.Types.NamespaceEntry = null;
1241 public override Type ResolveType (EmitContext ec)
1244 Type retval = base.ResolveType (ec);
1249 public override CustomAttributeBuilder Resolve (EmitContext ec)
1252 CustomAttributeBuilder retval = base.Resolve (ec);
1258 public class Attributes {
1259 public ArrayList Attrs;
1261 public Attributes (Attribute a)
1263 Attrs = new ArrayList ();
1267 public Attributes (ArrayList attrs)
1272 public void AddAttributes (ArrayList attrs)
1274 Attrs.AddRange (attrs);
1278 /// Checks whether attribute target is valid for the current element
1280 public bool CheckTargets (Attributable member)
1282 string[] valid_targets = member.ValidAttributeTargets;
1283 foreach (Attribute a in Attrs) {
1284 if (a.ExplicitTarget == null || a.ExplicitTarget == valid_targets [0]) {
1285 a.Target = member.AttributeTargets;
1289 // TODO: we can skip the first item
1290 if (((IList) valid_targets).Contains (a.ExplicitTarget)) {
1291 switch (a.ExplicitTarget) {
1292 case "return": a.Target = AttributeTargets.ReturnValue; continue;
1293 case "param": a.Target = AttributeTargets.Parameter; continue;
1294 case "field": a.Target = AttributeTargets.Field; continue;
1295 case "method": a.Target = AttributeTargets.Method; continue;
1296 case "property": a.Target = AttributeTargets.Property; continue;
1298 throw new InternalErrorException ("Unknown explicit target: " + a.ExplicitTarget);
1301 StringBuilder sb = new StringBuilder ();
1302 foreach (string s in valid_targets) {
1306 sb.Remove (sb.Length - 2, 2);
1307 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 ());
1313 public Attribute Search (Type t, EmitContext ec)
1315 foreach (Attribute a in Attrs) {
1316 if (a.ResolveType (ec) == t)
1323 /// Returns all attributes of type 't'. Use it when attribute is AllowMultiple = true
1325 public Attribute[] SearchMulti (Type t, EmitContext ec)
1327 ArrayList ar = null;
1329 foreach (Attribute a in Attrs) {
1330 if (a.ResolveType (ec) == t) {
1332 ar = new ArrayList ();
1337 return ar == null ? null : ar.ToArray (typeof (Attribute)) as Attribute[];
1340 public void Emit (EmitContext ec, Attributable ias)
1342 if (!CheckTargets (ias))
1345 ListDictionary ld = new ListDictionary ();
1347 foreach (Attribute a in Attrs)
1348 a.Emit (ec, ias, ld);
1351 public bool Contains (Type t, EmitContext ec)
1353 return Search (t, ec) != null;
1358 /// Helper class for attribute verification routine.
1360 sealed class AttributeTester
1362 static PtrHashtable analyzed_types = new PtrHashtable ();
1363 static PtrHashtable analyzed_types_obsolete = new PtrHashtable ();
1364 static PtrHashtable analyzed_member_obsolete = new PtrHashtable ();
1365 static PtrHashtable analyzed_method_excluded = new PtrHashtable ();
1366 static PtrHashtable fixed_buffer_cache = new PtrHashtable ();
1368 static object TRUE = new object ();
1369 static object FALSE = new object ();
1371 private AttributeTester ()
1376 /// Returns true if parameters of two compared methods are CLS-Compliant.
1377 /// It tests differing only in ref or out, or in array rank.
1379 public static bool AreOverloadedMethodParamsClsCompliant (Type[] types_a, Type[] types_b)
1381 if (types_a == null || types_b == null)
1384 if (types_a.Length != types_b.Length)
1387 for (int i = 0; i < types_b.Length; ++i) {
1388 Type aType = types_a [i];
1389 Type bType = types_b [i];
1391 if (aType.IsArray && bType.IsArray && aType.GetArrayRank () != bType.GetArrayRank () && aType.GetElementType () == bType.GetElementType ()) {
1395 Type aBaseType = aType;
1396 bool is_either_ref_or_out = false;
1398 if (aType.IsByRef || aType.IsPointer) {
1399 aBaseType = aType.GetElementType ();
1400 is_either_ref_or_out = true;
1403 Type bBaseType = bType;
1404 if (bType.IsByRef || bType.IsPointer)
1406 bBaseType = bType.GetElementType ();
1407 is_either_ref_or_out = !is_either_ref_or_out;
1410 if (aBaseType != bBaseType)
1413 if (is_either_ref_or_out)
1420 /// Goes through all parameters and test if they are CLS-Compliant.
1422 public static bool AreParametersCompliant (Parameter[] fixedParameters, Location loc)
1424 if (fixedParameters == null)
1427 foreach (Parameter arg in fixedParameters) {
1428 if (!AttributeTester.IsClsCompliant (arg.ParameterType)) {
1429 Report.Error (3001, loc, "Argument type '{0}' is not CLS-compliant", arg.GetSignatureForError ());
1438 /// This method tests the CLS compliance of external types. It doesn't test type visibility.
1440 public static bool IsClsCompliant (Type type)
1445 object type_compliance = analyzed_types[type];
1446 if (type_compliance != null)
1447 return type_compliance == TRUE;
1449 if (type.IsPointer) {
1450 analyzed_types.Add (type, null);
1455 if (type.IsArray || type.IsByRef) {
1456 result = IsClsCompliant (TypeManager.GetElementType (type));
1458 result = AnalyzeTypeCompliance (type);
1460 analyzed_types.Add (type, result ? TRUE : FALSE);
1465 /// Returns IFixedBuffer implementation if field is fixed buffer else null.
1467 public static IFixedBuffer GetFixedBuffer (FieldInfo fi)
1469 FieldBase fb = TypeManager.GetField (fi);
1471 return fb as IFixedBuffer;
1475 object o = fixed_buffer_cache [fi];
1477 if (System.Attribute.GetCustomAttribute (fi, TypeManager.fixed_buffer_attr_type) == null) {
1478 fixed_buffer_cache.Add (fi, FALSE);
1482 IFixedBuffer iff = new FixedFieldExternal (fi);
1483 fixed_buffer_cache.Add (fi, iff);
1490 return (IFixedBuffer)o;
1496 public static void VerifyModulesClsCompliance ()
1498 Module[] modules = TypeManager.Modules;
1499 if (modules == null)
1502 // The first module is generated assembly
1503 for (int i = 1; i < modules.Length; ++i) {
1504 Module module = modules [i];
1505 if (!IsClsCompliant (module)) {
1506 Report.Error (3013, "Added modules must be marked with the CLSCompliant attribute to match the assembly", module.Name);
1513 /// Tests container name for CLS-Compliant name (differing only in case)
1515 public static void VerifyTopLevelNameClsCompliance ()
1517 Hashtable locase_table = new Hashtable ();
1519 // Convert imported type names to lower case and ignore not cls compliant
1520 foreach (DictionaryEntry de in TypeManager.all_imported_types) {
1521 Type t = (Type)de.Value;
1522 if (!AttributeTester.IsClsCompliant (t))
1525 locase_table.Add (((string)de.Key).ToLower (System.Globalization.CultureInfo.InvariantCulture), t);
1528 foreach (DictionaryEntry de in RootContext.Tree.Decls) {
1529 DeclSpace decl = (DeclSpace)de.Value;
1530 if (!decl.IsClsCompliaceRequired (decl))
1533 string lcase = decl.Name.ToLower (System.Globalization.CultureInfo.InvariantCulture);
1534 if (!locase_table.Contains (lcase)) {
1535 locase_table.Add (lcase, decl);
1539 object conflict = locase_table [lcase];
1540 if (conflict is Type)
1541 Report.SymbolRelatedToPreviousError ((Type)conflict);
1543 Report.SymbolRelatedToPreviousError ((MemberCore)conflict);
1545 Report.Error (3005, decl.Location, "Identifier '{0}' differing only in case is not CLS-compliant", decl.GetSignatureForError ());
1549 static bool IsClsCompliant (ICustomAttributeProvider attribute_provider)
1551 object[] CompliantAttribute = attribute_provider.GetCustomAttributes (TypeManager.cls_compliant_attribute_type, false);
1552 if (CompliantAttribute.Length == 0)
1555 return ((CLSCompliantAttribute)CompliantAttribute[0]).IsCompliant;
1558 static bool AnalyzeTypeCompliance (Type type)
1560 DeclSpace ds = TypeManager.LookupDeclSpace (type);
1562 return ds.IsClsCompliaceRequired (ds.Parent);
1565 object[] CompliantAttribute = type.GetCustomAttributes (TypeManager.cls_compliant_attribute_type, false);
1566 if (CompliantAttribute.Length == 0)
1567 return IsClsCompliant (type.Assembly);
1569 return ((CLSCompliantAttribute)CompliantAttribute[0]).IsCompliant;
1573 /// Returns instance of ObsoleteAttribute when type is obsolete
1575 public static ObsoleteAttribute GetObsoleteAttribute (Type type)
1577 object type_obsolete = analyzed_types_obsolete [type];
1578 if (type_obsolete == FALSE)
1581 if (type_obsolete != null)
1582 return (ObsoleteAttribute)type_obsolete;
1584 ObsoleteAttribute result = null;
1585 if (type.IsByRef || type.IsArray || type.IsPointer) {
1586 result = GetObsoleteAttribute (TypeManager.GetElementType (type));
1588 DeclSpace type_ds = TypeManager.LookupDeclSpace (type);
1590 // Type is external, we can get attribute directly
1591 if (type_ds == null) {
1592 object[] attribute = type.GetCustomAttributes (TypeManager.obsolete_attribute_type, false);
1593 if (attribute.Length == 1)
1594 result = (ObsoleteAttribute)attribute [0];
1596 result = type_ds.GetObsoleteAttribute (type_ds);
1600 analyzed_types_obsolete.Add (type, result == null ? FALSE : result);
1605 /// Returns instance of ObsoleteAttribute when method is obsolete
1607 public static ObsoleteAttribute GetMethodObsoleteAttribute (MethodBase mb)
1609 IMethodData mc = TypeManager.GetMethod (mb);
1611 return mc.GetObsoleteAttribute ();
1613 // compiler generated methods are not registered by AddMethod
1614 if (mb.DeclaringType is TypeBuilder)
1617 PropertyInfo pi = PropertyExpr.AccessorTable [mb] as PropertyInfo;
1619 return GetMemberObsoleteAttribute (pi);
1621 return GetMemberObsoleteAttribute (mb);
1625 /// Returns instance of ObsoleteAttribute when member is obsolete
1627 public static ObsoleteAttribute GetMemberObsoleteAttribute (MemberInfo mi)
1629 object type_obsolete = analyzed_member_obsolete [mi];
1630 if (type_obsolete == FALSE)
1633 if (type_obsolete != null)
1634 return (ObsoleteAttribute)type_obsolete;
1636 ObsoleteAttribute oa = System.Attribute.GetCustomAttribute (mi, TypeManager.obsolete_attribute_type, false) as ObsoleteAttribute;
1637 analyzed_member_obsolete.Add (mi, oa == null ? FALSE : oa);
1642 /// Common method for Obsolete error/warning reporting.
1644 public static void Report_ObsoleteMessage (ObsoleteAttribute oa, string member, Location loc)
1647 Report.Error (619, loc, "'{0}' is obsolete: '{1}'", member, oa.Message);
1651 if (oa.Message == null) {
1652 Report.Warning (612, loc, "'{0}' is obsolete", member);
1655 if (RootContext.WarningLevel >= 2)
1656 Report.Warning (618, loc, "'{0}' is obsolete: '{1}'", member, oa.Message);
1659 public static bool IsConditionalMethodExcluded (MethodBase mb)
1661 object excluded = analyzed_method_excluded [mb];
1662 if (excluded != null)
1663 return excluded == TRUE ? true : false;
1665 ConditionalAttribute[] attrs = mb.GetCustomAttributes (TypeManager.conditional_attribute_type, true) as ConditionalAttribute[];
1666 if (attrs.Length == 0) {
1667 analyzed_method_excluded.Add (mb, FALSE);
1671 foreach (ConditionalAttribute a in attrs) {
1672 if (RootContext.AllDefines.Contains (a.ConditionString)) {
1673 analyzed_method_excluded.Add (mb, FALSE);
1677 analyzed_method_excluded.Add (mb, TRUE);