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);
137 static void Error_TypeParameterInAttribute (Location loc)
140 -202, loc, "Can not use a type parameter in an attribute");
144 /// This is rather hack. We report many emit attribute error with same error to be compatible with
145 /// csc. But because csc has to report them this way because error came from ilasm we needn't.
147 public void Error_AttributeEmitError (string inner)
149 Report.Error (647, Location, "Error emitting '{0}' attribute because '{1}'", Name, inner);
152 public void Error_InvalidSecurityParent ()
154 Error_AttributeEmitError ("it is attached to invalid parent");
157 void Error_AttributeConstructorMismatch ()
159 Report.Error (-6, Location,
160 "Could not find a constructor for this argument list.");
163 void ResolvePossibleAttributeTypes (EmitContext ec, out Type t1, out Type t2)
168 FullNamedExpression n1 = null;
169 FullNamedExpression n2 = null;
170 string IdentifierAttribute = Identifier + "Attribute";
171 if (LeftExpr == null) {
172 n1 = new SimpleName (Identifier, Location).ResolveAsTypeStep (ec);
174 // FIXME: Shouldn't do this for quoted attributes: [@A]
175 n2 = new SimpleName (IdentifierAttribute, Location).ResolveAsTypeStep (ec);
177 FullNamedExpression l = LeftExpr.ResolveAsTypeStep (ec);
179 Report.Error (246, Location, "Couldn't find namespace or type '{0}'", LeftExpr);
182 n1 = new MemberAccess (l, Identifier, Location).ResolveNamespaceOrType (ec, true);
184 // FIXME: Shouldn't do this for quoted attributes: [X.@A]
185 n2 = new MemberAccess (l, IdentifierAttribute, Location).ResolveNamespaceOrType (ec, true);
188 TypeExpr te1 = n1 == null ? null : n1 as TypeExpr;
189 TypeExpr te2 = n2 == null ? null : n2 as TypeExpr;
192 t1 = te1.ResolveType (ec);
194 t2 = te2.ResolveType (ec);
198 /// Tries to resolve the type of the attribute. Flags an error if it can't, and complain is true.
200 Type CheckAttributeType (EmitContext ec)
203 ResolvePossibleAttributeTypes (ec, out t1, out t2);
205 string NameAttribute = Name + "Attribute";
207 String err0616 = null;
208 if (t1 != null && ! t1.IsSubclassOf (TypeManager.attribute_type)) {
210 err0616 = "'" + Name + "': is not an attribute class";
212 if (t2 != null && ! t2.IsSubclassOf (TypeManager.attribute_type)) {
214 err0616 = (err0616 != null)
215 ? "Neither '" + Name + "' nor '" + NameAttribute +"' is an attribute class"
216 : "'" + Name + "Attribute': is not an attribute class";
219 if (t1 != null && t2 != null) {
220 Report.Error(1614, Location, "'" + Name + "': is ambiguous; "
221 + " use either '@" + Name + "' or '" + NameAttribute + "'");
228 if (err0616 != null) {
229 Report.Error (616, Location, err0616);
233 Report.Error (246, Location,
234 "Could not find attribute '" + Name
235 + "' (are you missing a using directive or an assembly reference ?)");
237 resolve_error = true;
241 public virtual Type ResolveType (EmitContext ec)
244 Type = CheckAttributeType (ec);
249 /// Validates the guid string
251 bool ValidateGuid (string guid)
257 Report.Error (647, Location, "Format of GUID is invalid: " + guid);
262 string GetFullMemberName (string member)
264 return Type.FullName + '.' + member;
268 // Given an expression, if the expression is a valid attribute-argument-expression
269 // returns an object that can be used to encode it, or null on failure.
271 public static bool GetAttributeArgumentExpression (Expression e, Location loc, Type arg_type, out object result)
273 if (e is EnumConstant) {
274 if (RootContext.StdLib)
275 result = ((EnumConstant)e).GetValueAsEnumType ();
277 result = ((EnumConstant)e).GetValue ();
282 Constant constant = e as Constant;
283 if (constant != null) {
284 if (e.Type != arg_type) {
285 constant = Const.ChangeType (loc, constant, arg_type);
286 if (constant == null) {
288 Error_AttributeArgumentNotValid (loc);
292 result = constant.GetValue ();
294 } else if (e is TypeOf) {
295 result = ((TypeOf) e).TypeArg;
297 } else if (e is ArrayCreation){
298 result = ((ArrayCreation) e).EncodeAsAttribute ();
301 } else if (e is EmptyCast) {
302 Expression child = ((EmptyCast)e).Child;
303 return GetAttributeArgumentExpression (child, loc, child.Type, out result);
307 Error_AttributeArgumentNotValid (loc);
311 public virtual CustomAttributeBuilder Resolve (EmitContext ec)
316 resolve_error = true;
321 Type = CheckAttributeType (ec);
323 if (oldType == null && Type == null)
325 if (oldType != null && oldType != Type){
326 Report.Error (-27, Location,
327 "Attribute {0} resolved to different types at different times: {1} vs. {2}",
328 Name, oldType, Type);
332 if (Type.IsAbstract) {
333 Report.Error (653, Location, "Cannot apply attribute class '{0}' because it is abstract", Name);
337 bool MethodImplAttr = false;
338 bool MarshalAsAttr = false;
339 bool GuidAttr = false;
340 bool usage_attr = false;
342 bool DoCompares = true;
345 // If we are a certain special attribute, we
346 // set the information accordingly
349 if (Type == TypeManager.attribute_usage_type)
351 else if (Type == TypeManager.methodimpl_attr_type)
352 MethodImplAttr = true;
353 else if (Type == TypeManager.marshal_as_attr_type)
354 MarshalAsAttr = true;
355 else if (Type == TypeManager.guid_attr_type)
360 // Now we extract the positional and named arguments
362 ArrayList pos_args = new ArrayList ();
363 ArrayList named_args = new ArrayList ();
364 int pos_arg_count = 0;
366 if (Arguments != null) {
367 pos_args = (ArrayList) Arguments [0];
368 if (pos_args != null)
369 pos_arg_count = pos_args.Count;
370 if (Arguments.Count > 1)
371 named_args = (ArrayList) Arguments [1];
374 pos_values = new object [pos_arg_count];
377 // First process positional arguments
381 for (i = 0; i < pos_arg_count; i++) {
382 Argument a = (Argument) pos_args [i];
385 if (!a.Resolve (ec, Location))
391 if (!GetAttributeArgumentExpression (e, Location, a.Type, out val))
394 pos_values [i] = val;
399 Report.Error (591, Location, "Invalid value for argument to 'System.AttributeUsage' attribute");
402 usage_attribute = new AttributeUsageAttribute ((AttributeTargets)val);
403 } else if (MethodImplAttr) {
404 this.ImplOptions = (MethodImplOptions) val;
405 } else if (GuidAttr){
407 // we will later check the validity of the type
410 if (!ValidateGuid ((string) val))
414 } else if (MarshalAsAttr)
416 (System.Runtime.InteropServices.UnmanagedType) val;
421 // Now process named arguments
424 ArrayList field_infos = null;
425 ArrayList prop_infos = null;
426 ArrayList field_values = null;
427 ArrayList prop_values = null;
429 if (named_args.Count > 0) {
430 field_infos = new ArrayList ();
431 prop_infos = new ArrayList ();
432 field_values = new ArrayList ();
433 prop_values = new ArrayList ();
436 Hashtable seen_names = new Hashtable();
438 for (i = 0; i < named_args.Count; i++) {
439 DictionaryEntry de = (DictionaryEntry) named_args [i];
440 string member_name = (string) de.Key;
441 Argument a = (Argument) de.Value;
444 if (seen_names.Contains(member_name)) {
445 Report.Error(643, Location, "'" + member_name + "' duplicate named attribute argument");
448 seen_names.Add(member_name, 1);
450 if (!a.Resolve (ec, Location))
453 Expression member = Expression.MemberLookup (
454 ec, Type, member_name,
455 MemberTypes.Field | MemberTypes.Property,
456 BindingFlags.Public | BindingFlags.Instance,
459 if (member == null) {
460 member = Expression.MemberLookup (ec, Type, member_name,
461 MemberTypes.Field | MemberTypes.Property, BindingFlags.NonPublic | BindingFlags.Instance,
464 if (member != null) {
465 Report.Error (122, Location, "'{0}' is inaccessible due to its protection level", GetFullMemberName (member_name));
471 Report.Error (117, Location, "Attribute `{0}' does not contain a definition for `{1}'",
476 if (!(member is PropertyExpr || member is FieldExpr)) {
477 Error_InvalidNamedArgument (member_name);
482 if (e is TypeParameterExpr){
483 Error_TypeParameterInAttribute (Location);
487 if (member is PropertyExpr) {
488 PropertyExpr pe = (PropertyExpr) member;
489 PropertyInfo pi = pe.PropertyInfo;
491 if (!pi.CanWrite || !pi.CanRead) {
492 Report.SymbolRelatedToPreviousError (pi);
493 Error_InvalidNamedArgument (member_name);
498 if (!GetAttributeArgumentExpression (e, Location, pi.PropertyType, out value))
501 if (usage_attribute != null) {
502 if (member_name == "AllowMultiple")
503 usage_attribute.AllowMultiple = (bool) value;
504 if (member_name == "Inherited")
505 usage_attribute.Inherited = (bool) value;
508 prop_values.Add (value);
511 } else if (member is FieldExpr) {
512 FieldExpr fe = (FieldExpr) member;
513 FieldInfo fi = fe.FieldInfo;
516 Error_InvalidNamedArgument (member_name);
521 if (!GetAttributeArgumentExpression (e, Location, fi.FieldType, out value))
524 field_values.Add (value);
526 field_infos.Add (fi);
530 Expression mg = Expression.MemberLookup (
531 ec, Type, ".ctor", MemberTypes.Constructor,
532 BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly,
536 Error_AttributeConstructorMismatch ();
540 MethodBase constructor = Invocation.OverloadResolve (
541 ec, (MethodGroupExpr) mg, pos_args, false, Location);
543 if (constructor == null) {
548 // Now we perform some checks on the positional args as they
549 // cannot be null for a constructor which expects a parameter
553 ParameterData pd = TypeManager.GetParameterData (constructor);
555 int last_real_param = pd.Count;
557 // When the params is not filled we need to put one
558 if (last_real_param > pos_arg_count) {
559 object [] new_pos_values = new object [pos_arg_count + 1];
560 pos_values.CopyTo (new_pos_values, 0);
561 new_pos_values [pos_arg_count] = new object [] {} ;
562 pos_values = new_pos_values;
567 for (int j = 0; j < pos_arg_count; ++j) {
568 Argument a = (Argument) pos_args [j];
570 if (a.Expr is NullLiteral && pd.ParameterType (j) == TypeManager.object_type) {
571 Error_AttributeArgumentNotValid (Location);
575 if (j < last_real_param)
578 if (j == last_real_param) {
579 object [] array = new object [pos_arg_count - last_real_param];
580 array [0] = pos_values [j];
581 pos_values [j] = array;
585 object [] params_array = (object []) pos_values [last_real_param];
586 params_array [j - last_real_param] = pos_values [j];
589 // Adjust the size of the pos_values if it had params
590 if (last_real_param != pos_arg_count) {
591 object [] new_pos_values = new object [last_real_param + 1];
592 Array.Copy (pos_values, new_pos_values, last_real_param + 1);
593 pos_values = new_pos_values;
597 if (named_args.Count > 0) {
598 prop_info_arr = new PropertyInfo [prop_infos.Count];
599 field_info_arr = new FieldInfo [field_infos.Count];
600 field_values_arr = new object [field_values.Count];
601 prop_values_arr = new object [prop_values.Count];
603 field_infos.CopyTo (field_info_arr, 0);
604 field_values.CopyTo (field_values_arr, 0);
606 prop_values.CopyTo (prop_values_arr, 0);
607 prop_infos.CopyTo (prop_info_arr, 0);
609 cb = new CustomAttributeBuilder (
610 (ConstructorInfo) constructor, pos_values,
611 prop_info_arr, prop_values_arr,
612 field_info_arr, field_values_arr);
615 cb = new CustomAttributeBuilder (
616 (ConstructorInfo) constructor, pos_values);
617 } catch (Exception e) {
620 // using System.ComponentModel;
621 // [DefaultValue (CollectionChangeAction.Add)]
622 // class X { static void Main () {} }
624 Error_AttributeArgumentNotValid (Location);
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 = GetAttributeUsage ().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 ()
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 return attr_class.AttributeUsage;
708 /// Returns custom name of indexer
710 public string GetIndexerAttributeValue (EmitContext ec)
712 if (pos_values == null)
713 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
714 // But because a lot of attribute class code must be rewritten will be better to wait...
717 return pos_values [0] as string;
721 /// Returns condition of ConditionalAttribute
723 public string GetConditionalAttributeValue (EmitContext ec)
725 if (pos_values == null)
726 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
727 // But because a lot of attribute class code must be rewritten will be better to wait...
730 // Some error occurred
731 if (pos_values [0] == null)
734 return (string)pos_values [0];
738 /// Creates the instance of ObsoleteAttribute from this attribute instance
740 public ObsoleteAttribute GetObsoleteAttribute (EmitContext ec)
742 if (pos_values == null)
743 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
744 // But because a lot of attribute class code must be rewritten will be better to wait...
747 // Some error occurred
748 if (pos_values == null)
751 if (pos_values.Length == 0)
752 return new ObsoleteAttribute ();
754 if (pos_values.Length == 1)
755 return new ObsoleteAttribute ((string)pos_values [0]);
757 return new ObsoleteAttribute ((string)pos_values [0], (bool)pos_values [1]);
761 /// Returns value of CLSCompliantAttribute contructor parameter but because the method can be called
762 /// before ApplyAttribute. We need to resolve the arguments.
763 /// This situation occurs when class deps is differs from Emit order.
765 public bool GetClsCompliantAttributeValue (EmitContext ec)
767 if (pos_values == null)
768 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
769 // But because a lot of attribute class code must be rewritten will be better to wait...
772 // Some error occurred
773 if (pos_values [0] == null)
776 return (bool)pos_values [0];
780 /// Tests permitted SecurityAction for assembly or other types
782 public bool CheckSecurityActionValidity (bool for_assembly)
784 SecurityAction action = GetSecurityActionValue ();
786 if ((action == SecurityAction.RequestMinimum || action == SecurityAction.RequestOptional || action == SecurityAction.RequestRefuse) && for_assembly)
790 if (action < SecurityAction.Demand || action > SecurityAction.InheritanceDemand) {
791 Error_AttributeEmitError ("SecurityAction is out of range");
795 if ((action != SecurityAction.RequestMinimum && action != SecurityAction.RequestOptional && action != SecurityAction.RequestRefuse) && !for_assembly)
799 Error_AttributeEmitError (String.Concat ("SecurityAction '", action, "' is not valid for this declaration"));
803 System.Security.Permissions.SecurityAction GetSecurityActionValue ()
805 return (SecurityAction)pos_values [0];
809 /// Creates instance of SecurityAttribute class and add result of CreatePermission method to permission table.
811 /// <returns></returns>
812 public void ExtractSecurityPermissionSet (ListDictionary permissions)
814 if (TypeManager.LookupDeclSpace (Type) != null && RootContext.StdLib) {
815 Error_AttributeEmitError ("security custom attributes can not be referenced from defining assembly");
819 SecurityAttribute sa;
820 // For all assemblies except corlib we can avoid all hacks
821 if (RootContext.StdLib) {
822 sa = (SecurityAttribute) Activator.CreateInstance (Type, pos_values);
824 if (prop_info_arr != null) {
825 for (int i = 0; i < prop_info_arr.Length; ++i) {
826 PropertyInfo pi = prop_info_arr [i];
827 pi.SetValue (sa, prop_values_arr [i], null);
831 Type temp_type = Type.GetType (Type.FullName);
832 // HACK: All mscorlib attributes have same ctor syntax
833 sa = (SecurityAttribute) Activator.CreateInstance (temp_type, new object[] { GetSecurityActionValue () } );
835 // All types are from newly created corlib but for invocation with old we need to convert them
836 if (prop_info_arr != null) {
837 for (int i = 0; i < prop_info_arr.Length; ++i) {
838 PropertyInfo emited_pi = prop_info_arr [i];
839 PropertyInfo pi = temp_type.GetProperty (emited_pi.Name, emited_pi.PropertyType);
841 object old_instance = pi.PropertyType.IsEnum ?
842 System.Enum.ToObject (pi.PropertyType, prop_values_arr [i]) :
845 pi.SetValue (sa, old_instance, null);
852 perm = sa.CreatePermission ();
854 catch (Exception e) {
855 Error_AttributeEmitError (String.Format ("{0} was thrown during attribute processing: {1}", e.GetType (), e.Message));
858 SecurityAction action = GetSecurityActionValue ();
860 // IS is correct because for corlib we are using an instance from old corlib
861 if (!(perm is System.Security.CodeAccessPermission)) {
863 case SecurityAction.Demand:
864 action = (SecurityAction)13;
866 case SecurityAction.LinkDemand:
867 action = (SecurityAction)14;
869 case SecurityAction.InheritanceDemand:
870 action = (SecurityAction)15;
875 PermissionSet ps = (PermissionSet)permissions [action];
877 if (sa is PermissionSetAttribute)
878 ps = new PermissionSet (sa.Unrestricted ? PermissionState.Unrestricted : PermissionState.None);
880 ps = new PermissionSet (PermissionState.None);
882 permissions.Add (action, ps);
883 } else if (!ps.IsUnrestricted () && sa.Unrestricted) {
884 ps = ps.Union (new PermissionSet (PermissionState.Unrestricted));
885 permissions [action] = ps;
887 ps.AddPermission (perm);
890 object GetValue (object value)
892 if (value is EnumConstant)
893 return ((EnumConstant) value).GetValue ();
898 public object GetPositionalValue (int i)
900 return (pos_values == null) ? null : pos_values[i];
903 object GetFieldValue (string name)
906 if (field_info_arr == null)
909 foreach (FieldInfo fi in field_info_arr) {
911 return GetValue (field_values_arr [i]);
917 public UnmanagedMarshal GetMarshal (Attributable attr)
919 object value = GetFieldValue ("SizeParamIndex");
920 if (value != null && UnmanagedType != UnmanagedType.LPArray) {
921 Error_AttributeEmitError ("SizeParamIndex field is not valid for the specified unmanaged type");
925 object o = GetFieldValue ("ArraySubType");
926 UnmanagedType array_sub_type = o == null ? UnmanagedType.I4 : (UnmanagedType) o;
928 switch (UnmanagedType) {
929 case UnmanagedType.CustomMarshaler:
930 MethodInfo define_custom = typeof (UnmanagedMarshal).GetMethod ("DefineCustom",
931 BindingFlags.Static | BindingFlags.Public);
932 if (define_custom == null) {
933 Report.RuntimeMissingSupport (Location, "set marshal info");
937 object [] args = new object [4];
938 args [0] = GetFieldValue ("MarshalTypeRef");
939 args [1] = GetFieldValue ("MarshalCookie");
940 args [2] = GetFieldValue ("MarshalType");
941 args [3] = Guid.Empty;
942 return (UnmanagedMarshal) define_custom.Invoke (null, args);
944 case UnmanagedType.LPArray:
945 return UnmanagedMarshal.DefineLPArray (array_sub_type);
947 case UnmanagedType.SafeArray:
948 return UnmanagedMarshal.DefineSafeArray (array_sub_type);
950 case UnmanagedType.ByValArray:
951 FieldMember fm = attr as FieldMember;
953 Error_AttributeEmitError ("Specified unmanaged type is only valid on fields");
956 return UnmanagedMarshal.DefineByValArray ((int) GetFieldValue ("SizeConst"));
958 case UnmanagedType.ByValTStr:
959 return UnmanagedMarshal.DefineByValTStr ((int) GetFieldValue ("SizeConst"));
962 return UnmanagedMarshal.DefineUnmanagedMarshal (UnmanagedType);
966 public bool IsInternalCall
968 get { return ImplOptions == MethodImplOptions.InternalCall; }
972 /// Emit attribute for Attributable symbol
974 public void Emit (EmitContext ec, Attributable ias, ListDictionary emitted_attr)
976 CustomAttributeBuilder cb = Resolve (ec);
980 AttributeUsageAttribute usage_attr = GetAttributeUsage ();
981 if ((usage_attr.ValidOn & Target) == 0) {
982 Report.Error (592, Location, "Attribute '{0}' is not valid on this declaration type. It is valid on {1} declarations only.", Name, GetValidTargets ());
986 ias.ApplyAttributeBuilder (this, cb);
988 if (!usage_attr.AllowMultiple) {
989 ArrayList emitted_targets = (ArrayList)emitted_attr [Type];
990 if (emitted_targets == null) {
991 emitted_targets = new ArrayList ();
992 emitted_attr.Add (Type, emitted_targets);
993 } else if (emitted_targets.Contains (Target)) {
994 Report.Error (579, Location, "Duplicate '" + Name + "' attribute");
997 emitted_targets.Add (Target);
1000 if (!RootContext.VerifyClsCompliance)
1003 // Here we are testing attribute arguments for array usage (error 3016)
1004 if (ias.IsClsCompliaceRequired (ec.DeclSpace)) {
1005 if (Arguments == null)
1008 ArrayList pos_args = (ArrayList) Arguments [0];
1009 if (pos_args != null) {
1010 foreach (Argument arg in pos_args) {
1011 // Type is undefined (was error 246)
1012 if (arg.Type == null)
1015 if (arg.Type.IsArray) {
1016 Report.Error (3016, Location, "Arrays as attribute arguments are not CLS-compliant");
1022 if (Arguments.Count < 2)
1025 ArrayList named_args = (ArrayList) Arguments [1];
1026 foreach (DictionaryEntry de in named_args) {
1027 Argument arg = (Argument) de.Value;
1029 // Type is undefined (was error 246)
1030 if (arg.Type == null)
1033 if (arg.Type.IsArray) {
1034 Report.Error (3016, Location, "Arrays as attribute arguments are not CLS-compliant");
1041 public object GetValue (EmitContext ec, Constant c, Type target)
1043 if (Convert.ImplicitConversionExists (ec, c, target))
1044 return c.GetValue ();
1046 Convert.Error_CannotImplicitConversion (Location, c.Type, target);
1050 public MethodBuilder DefinePInvokeMethod (EmitContext ec, TypeBuilder builder, string name,
1051 MethodAttributes flags, Type ret_type, Type [] param_types)
1054 // We extract from the attribute the information we need
1057 if (Arguments == null) {
1058 Console.WriteLine ("Internal error : this is not supposed to happen !");
1066 ArrayList named_args = new ArrayList ();
1068 ArrayList pos_args = (ArrayList) Arguments [0];
1069 if (Arguments.Count > 1)
1070 named_args = (ArrayList) Arguments [1];
1073 string dll_name = null;
1075 Argument tmp = (Argument) pos_args [0];
1077 if (!tmp.Resolve (ec, Location))
1080 if (tmp.Expr is Constant)
1081 dll_name = (string) ((Constant) tmp.Expr).GetValue ();
1083 Error_AttributeArgumentNotValid (Location);
1086 if (dll_name == null || dll_name == ""){
1087 Error_AttributeArgumentNotValid (": DllImport requires a non-empty string", Location);
1091 // Now we process the named arguments
1092 CallingConvention cc = CallingConvention.Winapi;
1093 CharSet charset = CharSet.Ansi;
1094 bool preserve_sig = true;
1096 bool exact_spelling = false;
1098 bool set_last_err = false;
1099 string entry_point = null;
1101 for (int i = 0; i < named_args.Count; i++) {
1103 DictionaryEntry de = (DictionaryEntry) named_args [i];
1105 string member_name = (string) de.Key;
1106 Argument a = (Argument) de.Value;
1108 if (!a.Resolve (ec, Location))
1111 Expression member = Expression.MemberLookup (
1112 ec, Type, member_name,
1113 MemberTypes.Field | MemberTypes.Property,
1114 BindingFlags.Public | BindingFlags.Instance,
1117 if (member == null || !(member is FieldExpr)) {
1118 Error_InvalidNamedArgument (member_name);
1122 if (member is FieldExpr) {
1123 FieldExpr fe = (FieldExpr) member;
1124 FieldInfo fi = fe.FieldInfo;
1126 if (fi.IsInitOnly) {
1127 Error_InvalidNamedArgument (member_name);
1131 if (a.Expr is Constant) {
1132 Constant c = (Constant) a.Expr;
1135 if (member_name == "CallingConvention"){
1136 object val = GetValue (ec, c, typeof (CallingConvention));
1139 cc = (CallingConvention) val;
1140 } else if (member_name == "CharSet"){
1141 charset = (CharSet) c.GetValue ();
1142 } else if (member_name == "EntryPoint")
1143 entry_point = (string) c.GetValue ();
1144 else if (member_name == "SetLastError")
1145 set_last_err = (bool) c.GetValue ();
1147 else if (member_name == "ExactSpelling")
1148 exact_spelling = (bool) c.GetValue ();
1150 else if (member_name == "PreserveSig")
1151 preserve_sig = (bool) c.GetValue ();
1152 } catch (InvalidCastException){
1153 Error_InvalidNamedArgument (member_name);
1154 Error_AttributeArgumentNotValid (Location);
1157 Error_AttributeArgumentNotValid (Location);
1164 if (entry_point == null)
1167 charset = (CharSet)((int)charset | 0x40);
1169 MethodBuilder mb = builder.DefinePInvokeMethod (
1170 name, dll_name, entry_point, flags | MethodAttributes.HideBySig,
1171 CallingConventions.Standard,
1178 mb.SetImplementationFlags (MethodImplAttributes.PreserveSig);
1183 private Expression GetValue ()
1185 if ((Arguments == null) || (Arguments.Count < 1))
1187 ArrayList al = (ArrayList) Arguments [0];
1188 if ((al == null) || (al.Count < 1))
1190 Argument arg = (Argument) al [0];
1191 if ((arg == null) || (arg.Expr == null))
1196 public string GetString ()
1198 Expression e = GetValue ();
1199 if (e is StringLiteral)
1200 return (e as StringLiteral).Value;
1204 public bool GetBoolean ()
1206 Expression e = GetValue ();
1207 if (e is BoolLiteral)
1208 return (e as BoolLiteral).Value;
1215 /// For global attributes (assembly, module) we need special handling.
1216 /// Attributes can be located in the several files
1218 public class GlobalAttribute: Attribute
1220 public readonly NamespaceEntry ns;
1222 public GlobalAttribute (TypeContainer container, string target,
1223 Expression left_expr, string identifier, ArrayList args, Location loc):
1224 base (target, left_expr, identifier, args, loc)
1226 ns = container.NamespaceEntry;
1231 // RootContext.Tree.Types has a single NamespaceEntry which gets overwritten
1232 // each time a new file is parsed. However, we need to use the NamespaceEntry
1233 // in effect where the attribute was used. Since code elsewhere cannot assume
1234 // that the NamespaceEntry is right, just overwrite it.
1236 // Precondition: RootContext.Tree.Types == null
1238 if (RootContext.Tree.Types.NamespaceEntry != null)
1239 throw new InternalErrorException (Location + " non-null NamespaceEntry");
1241 RootContext.Tree.Types.NamespaceEntry = ns;
1246 RootContext.Tree.Types.NamespaceEntry = null;
1249 public override Type ResolveType (EmitContext ec)
1252 Type retval = base.ResolveType (ec);
1257 public override CustomAttributeBuilder Resolve (EmitContext ec)
1260 CustomAttributeBuilder retval = base.Resolve (ec);
1266 public class Attributes {
1267 public ArrayList Attrs;
1269 public Attributes (Attribute a)
1271 Attrs = new ArrayList ();
1275 public Attributes (ArrayList attrs)
1280 public void AddAttributes (ArrayList attrs)
1282 Attrs.AddRange (attrs);
1286 /// Checks whether attribute target is valid for the current element
1288 public bool CheckTargets (Attributable member)
1290 string[] valid_targets = member.ValidAttributeTargets;
1291 foreach (Attribute a in Attrs) {
1292 if (a.ExplicitTarget == null || a.ExplicitTarget == valid_targets [0]) {
1293 a.Target = member.AttributeTargets;
1297 // TODO: we can skip the first item
1298 if (((IList) valid_targets).Contains (a.ExplicitTarget)) {
1299 switch (a.ExplicitTarget) {
1300 case "return": a.Target = AttributeTargets.ReturnValue; continue;
1301 case "param": a.Target = AttributeTargets.Parameter; continue;
1302 case "field": a.Target = AttributeTargets.Field; continue;
1303 case "method": a.Target = AttributeTargets.Method; continue;
1304 case "property": a.Target = AttributeTargets.Property; continue;
1306 throw new InternalErrorException ("Unknown explicit target: " + a.ExplicitTarget);
1309 StringBuilder sb = new StringBuilder ();
1310 foreach (string s in valid_targets) {
1314 sb.Remove (sb.Length - 2, 2);
1315 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 ());
1321 public Attribute Search (Type t, EmitContext ec)
1323 foreach (Attribute a in Attrs) {
1324 if (a.ResolveType (ec) == t)
1331 /// Returns all attributes of type 't'. Use it when attribute is AllowMultiple = true
1333 public Attribute[] SearchMulti (Type t, EmitContext ec)
1335 ArrayList ar = null;
1337 foreach (Attribute a in Attrs) {
1338 if (a.ResolveType (ec) == t) {
1340 ar = new ArrayList ();
1345 return ar == null ? null : ar.ToArray (typeof (Attribute)) as Attribute[];
1348 public void Emit (EmitContext ec, Attributable ias)
1350 if (!CheckTargets (ias))
1353 ListDictionary ld = new ListDictionary ();
1355 foreach (Attribute a in Attrs)
1356 a.Emit (ec, ias, ld);
1359 public bool Contains (Type t, EmitContext ec)
1361 return Search (t, ec) != null;
1366 /// Helper class for attribute verification routine.
1368 sealed class AttributeTester
1370 static PtrHashtable analyzed_types = new PtrHashtable ();
1371 static PtrHashtable analyzed_types_obsolete = new PtrHashtable ();
1372 static PtrHashtable analyzed_member_obsolete = new PtrHashtable ();
1373 static PtrHashtable analyzed_method_excluded = new PtrHashtable ();
1375 private AttributeTester ()
1380 /// Returns true if parameters of two compared methods are CLS-Compliant.
1381 /// It tests differing only in ref or out, or in array rank.
1383 public static bool AreOverloadedMethodParamsClsCompliant (Type[] types_a, Type[] types_b)
1385 if (types_a == null || types_b == null)
1388 if (types_a.Length != types_b.Length)
1391 for (int i = 0; i < types_b.Length; ++i) {
1392 Type aType = types_a [i];
1393 Type bType = types_b [i];
1395 if (aType.IsArray && bType.IsArray && aType.GetArrayRank () != bType.GetArrayRank () && aType.GetElementType () == bType.GetElementType ()) {
1399 Type aBaseType = aType;
1400 bool is_either_ref_or_out = false;
1402 if (aType.IsByRef || aType.IsPointer) {
1403 aBaseType = aType.GetElementType ();
1404 is_either_ref_or_out = true;
1407 Type bBaseType = bType;
1408 if (bType.IsByRef || bType.IsPointer)
1410 bBaseType = bType.GetElementType ();
1411 is_either_ref_or_out = !is_either_ref_or_out;
1414 if (aBaseType != bBaseType)
1417 if (is_either_ref_or_out)
1424 /// Goes through all parameters and test if they are CLS-Compliant.
1426 public static bool AreParametersCompliant (Parameter[] fixedParameters, Location loc)
1428 if (fixedParameters == null)
1431 foreach (Parameter arg in fixedParameters) {
1432 if (!AttributeTester.IsClsCompliant (arg.ParameterType)) {
1433 Report.Error (3001, loc, "Argument type '{0}' is not CLS-compliant", arg.GetSignatureForError ());
1442 /// This method tests the CLS compliance of external types. It doesn't test type visibility.
1444 public static bool IsClsCompliant (Type type)
1449 object type_compliance = analyzed_types[type];
1450 if (type_compliance != null)
1451 return type_compliance == TRUE;
1453 if (type.IsPointer) {
1454 analyzed_types.Add (type, null);
1459 if (type.IsArray || type.IsByRef) {
1460 result = IsClsCompliant (TypeManager.GetElementType (type));
1462 result = AnalyzeTypeCompliance (type);
1464 analyzed_types.Add (type, result ? TRUE : FALSE);
1468 static object TRUE = new object ();
1469 static object FALSE = new object ();
1471 public static void VerifyModulesClsCompliance ()
1473 Module[] modules = TypeManager.Modules;
1474 if (modules == null)
1477 // The first module is generated assembly
1478 for (int i = 1; i < modules.Length; ++i) {
1479 Module module = modules [i];
1480 if (!IsClsCompliant (module)) {
1481 Report.Error (3013, "Added modules must be marked with the CLSCompliant attribute to match the assembly", module.Name);
1488 /// Tests container name for CLS-Compliant name (differing only in case)
1490 public static void VerifyTopLevelNameClsCompliance ()
1492 Hashtable locase_table = new Hashtable ();
1494 // Convert imported type names to lower case and ignore not cls compliant
1495 foreach (DictionaryEntry de in TypeManager.all_imported_types) {
1496 Type t = (Type)de.Value;
1497 if (!AttributeTester.IsClsCompliant (t))
1500 locase_table.Add (((string)de.Key).ToLower (System.Globalization.CultureInfo.InvariantCulture), t);
1503 foreach (DictionaryEntry de in RootContext.Tree.Decls) {
1504 DeclSpace decl = (DeclSpace)de.Value;
1505 if (!decl.IsClsCompliaceRequired (decl))
1508 string lcase = decl.Name.ToLower (System.Globalization.CultureInfo.InvariantCulture);
1509 if (!locase_table.Contains (lcase)) {
1510 locase_table.Add (lcase, decl);
1514 object conflict = locase_table [lcase];
1515 if (conflict is Type)
1516 Report.SymbolRelatedToPreviousError ((Type)conflict);
1518 Report.SymbolRelatedToPreviousError ((MemberCore)conflict);
1520 Report.Error (3005, decl.Location, "Identifier '{0}' differing only in case is not CLS-compliant", decl.GetSignatureForError ());
1524 static bool IsClsCompliant (ICustomAttributeProvider attribute_provider)
1526 object[] CompliantAttribute = attribute_provider.GetCustomAttributes (TypeManager.cls_compliant_attribute_type, false);
1527 if (CompliantAttribute.Length == 0)
1530 return ((CLSCompliantAttribute)CompliantAttribute[0]).IsCompliant;
1533 static bool AnalyzeTypeCompliance (Type type)
1535 DeclSpace ds = TypeManager.LookupDeclSpace (type);
1537 return ds.IsClsCompliaceRequired (ds.Parent);
1540 if (type.IsGenericParameter || type.IsGenericInstance)
1543 object[] CompliantAttribute = type.GetCustomAttributes (TypeManager.cls_compliant_attribute_type, false);
1544 if (CompliantAttribute.Length == 0)
1545 return IsClsCompliant (type.Assembly);
1547 return ((CLSCompliantAttribute)CompliantAttribute[0]).IsCompliant;
1551 /// Returns instance of ObsoleteAttribute when type is obsolete
1553 public static ObsoleteAttribute GetObsoleteAttribute (Type type)
1555 object type_obsolete = analyzed_types_obsolete [type];
1556 if (type_obsolete == FALSE)
1559 if (type_obsolete != null)
1560 return (ObsoleteAttribute)type_obsolete;
1562 ObsoleteAttribute result = null;
1563 if (type.IsByRef || type.IsArray || type.IsPointer) {
1564 result = GetObsoleteAttribute (TypeManager.GetElementType (type));
1565 } else if (type.IsGenericParameter || type.IsGenericInstance)
1568 DeclSpace type_ds = TypeManager.LookupDeclSpace (type);
1570 // Type is external, we can get attribute directly
1571 if (type_ds == null) {
1572 object[] attribute = type.GetCustomAttributes (TypeManager.obsolete_attribute_type, false);
1573 if (attribute.Length == 1)
1574 result = (ObsoleteAttribute)attribute [0];
1576 result = type_ds.GetObsoleteAttribute (type_ds);
1580 analyzed_types_obsolete.Add (type, result == null ? FALSE : result);
1585 /// Returns instance of ObsoleteAttribute when method is obsolete
1587 public static ObsoleteAttribute GetMethodObsoleteAttribute (MethodBase mb)
1589 IMethodData mc = TypeManager.GetMethod (mb);
1591 return mc.GetObsoleteAttribute ();
1593 // compiler generated methods are not registered by AddMethod
1594 if (mb.DeclaringType is TypeBuilder)
1597 PropertyInfo pi = PropertyExpr.AccessorTable [mb] as PropertyInfo;
1599 return GetMemberObsoleteAttribute (pi);
1601 return GetMemberObsoleteAttribute (mb);
1605 /// Returns instance of ObsoleteAttribute when member is obsolete
1607 public static ObsoleteAttribute GetMemberObsoleteAttribute (MemberInfo mi)
1609 object type_obsolete = analyzed_member_obsolete [mi];
1610 if (type_obsolete == FALSE)
1613 if (type_obsolete != null)
1614 return (ObsoleteAttribute)type_obsolete;
1616 if ((mi.DeclaringType is TypeBuilder) || mi.DeclaringType.IsGenericInstance)
1619 ObsoleteAttribute oa = System.Attribute.GetCustomAttribute (mi, TypeManager.obsolete_attribute_type, false) as ObsoleteAttribute;
1620 analyzed_member_obsolete.Add (mi, oa == null ? FALSE : oa);
1625 /// Common method for Obsolete error/warning reporting.
1627 public static void Report_ObsoleteMessage (ObsoleteAttribute oa, string member, Location loc)
1630 Report.Error (619, loc, "'{0}' is obsolete: '{1}'", member, oa.Message);
1634 if (oa.Message == null) {
1635 Report.Warning (612, loc, "'{0}' is obsolete", member);
1638 if (RootContext.WarningLevel >= 2)
1639 Report.Warning (618, loc, "'{0}' is obsolete: '{1}'", member, oa.Message);
1642 public static bool IsConditionalMethodExcluded (MethodBase mb)
1644 object excluded = analyzed_method_excluded [mb];
1645 if (excluded != null)
1646 return excluded == TRUE ? true : false;
1648 if (mb.Mono_IsInflatedMethod)
1651 ConditionalAttribute[] attrs = mb.GetCustomAttributes (TypeManager.conditional_attribute_type, true) as ConditionalAttribute[];
1652 if (attrs.Length == 0) {
1653 analyzed_method_excluded.Add (mb, FALSE);
1657 foreach (ConditionalAttribute a in attrs) {
1658 if (RootContext.AllDefines.Contains (a.ConditionString)) {
1659 analyzed_method_excluded.Add (mb, FALSE);
1663 analyzed_method_excluded.Add (mb, TRUE);