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);
131 static void Error_TypeParameterInAttribute (Location loc)
134 -202, loc, "Can not use a type parameter in an attribute");
138 /// This is rather hack. We report many emit attribute error with same error to be compatible with
139 /// csc. But because csc has to report them this way because error came from ilasm we needn't.
141 public void Error_AttributeEmitError (string inner)
143 Report.Error (647, Location, "Error emitting '{0}' attribute because '{1}'", Name, inner);
146 public void Error_InvalidSecurityParent ()
148 Error_AttributeEmitError ("it is attached to invalid parent");
151 void Error_AttributeConstructorMismatch ()
153 Report.Error (-6, Location,
154 "Could not find a constructor for this argument list.");
157 void ResolvePossibleAttributeTypes (EmitContext ec, out Type t1, out Type t2)
162 FullNamedExpression n1 = null;
163 FullNamedExpression n2 = null;
164 string IdentifierAttribute = Identifier + "Attribute";
165 if (LeftExpr == null) {
166 n1 = new SimpleName (Identifier, Location).ResolveAsTypeStep (ec);
168 // FIXME: Shouldn't do this for quoted attributes: [@A]
169 n2 = new SimpleName (IdentifierAttribute, Location).ResolveAsTypeStep (ec);
171 FullNamedExpression l = LeftExpr.ResolveAsTypeStep (ec);
173 Report.Error (246, Location, "Couldn't find namespace or type '{0}'", LeftExpr);
176 n1 = new MemberAccess (l, Identifier, Location).ResolveNamespaceOrType (ec, true);
178 // FIXME: Shouldn't do this for quoted attributes: [X.@A]
179 n2 = new MemberAccess (l, IdentifierAttribute, Location).ResolveNamespaceOrType (ec, true);
182 TypeExpr te1 = n1 == null ? null : n1 as TypeExpr;
183 TypeExpr te2 = n2 == null ? null : n2 as TypeExpr;
186 t1 = te1.ResolveType (ec);
188 t2 = te2.ResolveType (ec);
192 /// Tries to resolve the type of the attribute. Flags an error if it can't, and complain is true.
194 Type CheckAttributeType (EmitContext ec)
197 ResolvePossibleAttributeTypes (ec, out t1, out t2);
199 string NameAttribute = Name + "Attribute";
201 String err0616 = null;
202 if (t1 != null && ! t1.IsSubclassOf (TypeManager.attribute_type)) {
204 err0616 = "'" + Name + "': is not an attribute class";
206 if (t2 != null && ! t2.IsSubclassOf (TypeManager.attribute_type)) {
208 err0616 = (err0616 != null)
209 ? "Neither '" + Name + "' nor '" + NameAttribute +"' is an attribute class"
210 : "'" + Name + "Attribute': is not an attribute class";
213 if (t1 != null && t2 != null) {
214 Report.Error(1614, Location, "'" + Name + "': is ambiguous; "
215 + " use either '@" + Name + "' or '" + NameAttribute + "'");
222 if (err0616 != null) {
223 Report.Error (616, Location, err0616);
227 Report.Error (246, Location,
228 "Could not find attribute '" + Name
229 + "' (are you missing a using directive or an assembly reference ?)");
231 resolve_error = true;
235 public virtual Type ResolveType (EmitContext ec)
237 if (Type == null && !resolve_error)
238 Type = CheckAttributeType (ec);
243 /// Validates the guid string
245 bool ValidateGuid (string guid)
251 Report.Error (647, Location, "Format of GUID is invalid: " + guid);
256 string GetFullMemberName (string member)
258 return Type.FullName + '.' + member;
262 // Given an expression, if the expression is a valid attribute-argument-expression
263 // returns an object that can be used to encode it, or null on failure.
265 public static bool GetAttributeArgumentExpression (Expression e, Location loc, Type arg_type, out object result)
267 if (e is EnumConstant) {
268 if (RootContext.StdLib)
269 result = ((EnumConstant)e).GetValueAsEnumType ();
271 result = ((EnumConstant)e).GetValue ();
276 Constant constant = e as Constant;
277 if (constant != null) {
278 if (e.Type != arg_type) {
279 constant = Const.ChangeType (loc, constant, arg_type);
280 if (constant == null) {
282 Error_AttributeArgumentNotValid (loc);
286 result = constant.GetValue ();
288 } else if (e is TypeOf) {
289 result = ((TypeOf) e).TypeArg;
291 } else if (e is ArrayCreation){
292 result = ((ArrayCreation) e).EncodeAsAttribute ();
295 } else if (e is EmptyCast) {
296 Expression child = ((EmptyCast)e).Child;
297 return GetAttributeArgumentExpression (child, loc, child.Type, out result);
301 Error_AttributeArgumentNotValid (loc);
305 public virtual CustomAttributeBuilder Resolve (EmitContext ec)
310 resolve_error = true;
315 Type = CheckAttributeType (ec); // TODO: I really don't think we need such expensive double check
317 if (oldType == null && Type == null)
319 if (oldType != null && oldType != Type){
320 Report.Error (-27, Location,
321 "Attribute {0} resolved to different types at different times: {1} vs. {2}",
322 Name, oldType, Type);
326 if (Type.IsAbstract) {
327 Report.Error (653, Location, "Cannot apply attribute class '{0}' because it is abstract", Name);
331 bool MethodImplAttr = false;
332 bool MarshalAsAttr = false;
333 bool GuidAttr = false;
334 bool usage_attr = false;
336 bool DoCompares = true;
339 // If we are a certain special attribute, we
340 // set the information accordingly
343 if (Type == TypeManager.attribute_usage_type)
345 else if (Type == TypeManager.methodimpl_attr_type)
346 MethodImplAttr = true;
347 else if (Type == TypeManager.marshal_as_attr_type)
348 MarshalAsAttr = true;
349 else if (Type == TypeManager.guid_attr_type)
354 // Now we extract the positional and named arguments
356 ArrayList pos_args = new ArrayList ();
357 ArrayList named_args = new ArrayList ();
358 int pos_arg_count = 0;
360 if (Arguments != null) {
361 pos_args = (ArrayList) Arguments [0];
362 if (pos_args != null)
363 pos_arg_count = pos_args.Count;
364 if (Arguments.Count > 1)
365 named_args = (ArrayList) Arguments [1];
368 pos_values = new object [pos_arg_count];
371 // First process positional arguments
375 for (i = 0; i < pos_arg_count; i++) {
376 Argument a = (Argument) pos_args [i];
379 if (!a.Resolve (ec, Location))
385 if (!GetAttributeArgumentExpression (e, Location, a.Type, out val))
388 pos_values [i] = val;
393 Report.Error (591, Location, "Invalid value for argument to 'System.AttributeUsage' attribute");
396 UsageAttribute = new AttributeUsageAttribute ((AttributeTargets)val);
397 } else if (MethodImplAttr) {
398 this.ImplOptions = (MethodImplOptions) val;
399 } else if (GuidAttr){
401 // we will later check the validity of the type
404 if (!ValidateGuid ((string) val))
408 } else if (MarshalAsAttr)
410 (System.Runtime.InteropServices.UnmanagedType) val;
415 // Now process named arguments
418 ArrayList field_infos = null;
419 ArrayList prop_infos = null;
420 ArrayList field_values = null;
421 ArrayList prop_values = null;
423 if (named_args.Count > 0) {
424 field_infos = new ArrayList ();
425 prop_infos = new ArrayList ();
426 field_values = new ArrayList ();
427 prop_values = new ArrayList ();
430 Hashtable seen_names = new Hashtable();
432 for (i = 0; i < named_args.Count; i++) {
433 DictionaryEntry de = (DictionaryEntry) named_args [i];
434 string member_name = (string) de.Key;
435 Argument a = (Argument) de.Value;
438 if (seen_names.Contains(member_name)) {
439 Report.Error(643, Location, "'" + member_name + "' duplicate named attribute argument");
442 seen_names.Add(member_name, 1);
444 if (!a.Resolve (ec, Location))
447 Expression member = Expression.MemberLookup (
448 ec, Type, member_name,
449 MemberTypes.Field | MemberTypes.Property,
450 BindingFlags.Public | BindingFlags.Instance,
453 if (member == null) {
454 member = Expression.MemberLookup (ec, Type, member_name,
455 MemberTypes.Field | MemberTypes.Property, BindingFlags.NonPublic | BindingFlags.Instance,
458 if (member != null) {
459 Report.Error (122, Location, "'{0}' is inaccessible due to its protection level", GetFullMemberName (member_name));
465 Report.Error (117, Location, "Attribute `{0}' does not contain a definition for `{1}'",
470 if (!(member is PropertyExpr || member is FieldExpr)) {
471 Error_InvalidNamedArgument (member_name);
476 if (e is TypeParameterExpr){
477 Error_TypeParameterInAttribute (Location);
481 if (member is PropertyExpr) {
482 PropertyExpr pe = (PropertyExpr) member;
483 PropertyInfo pi = pe.PropertyInfo;
485 if (!pi.CanWrite || !pi.CanRead) {
486 Report.SymbolRelatedToPreviousError (pi);
487 Error_InvalidNamedArgument (member_name);
492 if (!GetAttributeArgumentExpression (e, Location, pi.PropertyType, out value))
495 if (UsageAttribute != null) {
496 if (member_name == "AllowMultiple")
497 UsageAttribute.AllowMultiple = (bool) value;
498 if (member_name == "Inherited")
499 UsageAttribute.Inherited = (bool) value;
502 prop_values.Add (value);
505 } else if (member is FieldExpr) {
506 FieldExpr fe = (FieldExpr) member;
507 FieldInfo fi = fe.FieldInfo;
510 Error_InvalidNamedArgument (member_name);
515 if (!GetAttributeArgumentExpression (e, Location, fi.FieldType, out value))
518 field_values.Add (value);
520 field_infos.Add (fi);
524 Expression mg = Expression.MemberLookup (
525 ec, Type, ".ctor", MemberTypes.Constructor,
526 BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly,
530 Error_AttributeConstructorMismatch ();
534 MethodBase constructor = Invocation.OverloadResolve (
535 ec, (MethodGroupExpr) mg, pos_args, false, Location);
537 if (constructor == null) {
542 // Now we perform some checks on the positional args as they
543 // cannot be null for a constructor which expects a parameter
547 ParameterData pd = TypeManager.GetParameterData (constructor);
549 int last_real_param = pd.Count;
551 // When the params is not filled we need to put one
552 if (last_real_param > pos_arg_count) {
553 object [] new_pos_values = new object [pos_arg_count + 1];
554 pos_values.CopyTo (new_pos_values, 0);
555 new_pos_values [pos_arg_count] = new object [] {} ;
556 pos_values = new_pos_values;
561 for (int j = 0; j < pos_arg_count; ++j) {
562 Argument a = (Argument) pos_args [j];
564 if (a.Expr is NullLiteral && pd.ParameterType (j) == TypeManager.object_type) {
565 Error_AttributeArgumentNotValid (Location);
569 object value = pos_values [j];
570 if (value != null && a.Type != value.GetType () && a.Type.IsPrimitive) {
572 pos_values [j] = TypeManager.ChangeType (value, a.Type, out fail);
574 // TODO: Can failed ?
575 throw new NotImplementedException ();
579 if (j < last_real_param)
582 if (j == last_real_param) {
583 object [] array = new object [pos_arg_count - last_real_param];
584 array [0] = pos_values [j];
585 pos_values [j] = array;
589 object [] params_array = (object []) pos_values [last_real_param];
590 params_array [j - last_real_param] = pos_values [j];
593 // Adjust the size of the pos_values if it had params
594 if (last_real_param != pos_arg_count) {
595 object [] new_pos_values = new object [last_real_param + 1];
596 Array.Copy (pos_values, new_pos_values, last_real_param + 1);
597 pos_values = new_pos_values;
601 if (named_args.Count > 0) {
602 prop_info_arr = new PropertyInfo [prop_infos.Count];
603 field_info_arr = new FieldInfo [field_infos.Count];
604 field_values_arr = new object [field_values.Count];
605 prop_values_arr = new object [prop_values.Count];
607 field_infos.CopyTo (field_info_arr, 0);
608 field_values.CopyTo (field_values_arr, 0);
610 prop_values.CopyTo (prop_values_arr, 0);
611 prop_infos.CopyTo (prop_info_arr, 0);
613 cb = new CustomAttributeBuilder (
614 (ConstructorInfo) constructor, pos_values,
615 prop_info_arr, prop_values_arr,
616 field_info_arr, field_values_arr);
619 cb = new CustomAttributeBuilder (
620 (ConstructorInfo) constructor, pos_values);
621 } catch (Exception e) {
624 // using System.ComponentModel;
625 // [DefaultValue (CollectionChangeAction.Add)]
626 // class X { static void Main () {} }
628 Error_AttributeArgumentNotValid (Location);
633 UsageAttribute = DefaultUsageAttribute;
636 resolve_error = false;
641 /// Get a string containing a list of valid targets for the attribute 'attr'
643 public string GetValidTargets ()
645 StringBuilder sb = new StringBuilder ();
646 AttributeTargets targets = UsageAttribute.ValidOn;
648 if ((targets & AttributeTargets.Assembly) != 0)
649 sb.Append ("'assembly' ");
651 if ((targets & AttributeTargets.Class) != 0)
652 sb.Append ("'class' ");
654 if ((targets & AttributeTargets.Constructor) != 0)
655 sb.Append ("'constructor' ");
657 if ((targets & AttributeTargets.Delegate) != 0)
658 sb.Append ("'delegate' ");
660 if ((targets & AttributeTargets.Enum) != 0)
661 sb.Append ("'enum' ");
663 if ((targets & AttributeTargets.Event) != 0)
664 sb.Append ("'event' ");
666 if ((targets & AttributeTargets.Field) != 0)
667 sb.Append ("'field' ");
669 if ((targets & AttributeTargets.Interface) != 0)
670 sb.Append ("'interface' ");
672 if ((targets & AttributeTargets.Method) != 0)
673 sb.Append ("'method' ");
675 if ((targets & AttributeTargets.Module) != 0)
676 sb.Append ("'module' ");
678 if ((targets & AttributeTargets.Parameter) != 0)
679 sb.Append ("'parameter' ");
681 if ((targets & AttributeTargets.Property) != 0)
682 sb.Append ("'property' ");
684 if ((targets & AttributeTargets.ReturnValue) != 0)
685 sb.Append ("'return' ");
687 if ((targets & AttributeTargets.Struct) != 0)
688 sb.Append ("'struct' ");
690 return sb.ToString ();
695 /// Returns AttributeUsage attribute for this type
697 public AttributeUsageAttribute GetAttributeUsage (EmitContext ec)
699 AttributeUsageAttribute ua = usage_attr_cache [Type] as AttributeUsageAttribute;
703 Class attr_class = TypeManager.LookupClass (Type);
705 if (attr_class == null) {
706 object[] usage_attr = Type.GetCustomAttributes (TypeManager.attribute_usage_type, true);
707 ua = (AttributeUsageAttribute)usage_attr [0];
708 usage_attr_cache.Add (Type, ua);
712 ua = attr_class.ResolveAttributeUsage (ec);
713 usage_attr_cache.Add (Type, ua);
718 /// Returns custom name of indexer
720 public string GetIndexerAttributeValue (EmitContext ec)
722 if (pos_values == null)
723 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
724 // But because a lot of attribute class code must be rewritten will be better to wait...
727 return pos_values [0] as string;
731 /// Returns condition of ConditionalAttribute
733 public string GetConditionalAttributeValue (EmitContext ec)
735 if (pos_values == null)
736 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
737 // But because a lot of attribute class code must be rewritten will be better to wait...
740 // Some error occurred
741 if (pos_values [0] == null)
744 return (string)pos_values [0];
748 /// Creates the instance of ObsoleteAttribute from this attribute instance
750 public ObsoleteAttribute GetObsoleteAttribute (EmitContext ec)
752 if (pos_values == null)
753 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
754 // But because a lot of attribute class code must be rewritten will be better to wait...
757 // Some error occurred
758 if (pos_values == null)
761 if (pos_values.Length == 0)
762 return new ObsoleteAttribute ();
764 if (pos_values.Length == 1)
765 return new ObsoleteAttribute ((string)pos_values [0]);
767 return new ObsoleteAttribute ((string)pos_values [0], (bool)pos_values [1]);
771 /// Returns value of CLSCompliantAttribute contructor parameter but because the method can be called
772 /// before ApplyAttribute. We need to resolve the arguments.
773 /// This situation occurs when class deps is differs from Emit order.
775 public bool GetClsCompliantAttributeValue (EmitContext ec)
777 if (pos_values == null)
778 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
779 // But because a lot of attribute class code must be rewritten will be better to wait...
782 // Some error occurred
783 if (pos_values [0] == null)
786 return (bool)pos_values [0];
790 /// Tests permitted SecurityAction for assembly or other types
792 public bool CheckSecurityActionValidity (bool for_assembly)
794 SecurityAction action = GetSecurityActionValue ();
796 if ((action == SecurityAction.RequestMinimum || action == SecurityAction.RequestOptional || action == SecurityAction.RequestRefuse) && for_assembly)
800 if (action < SecurityAction.Demand || action > SecurityAction.InheritanceDemand) {
801 Error_AttributeEmitError ("SecurityAction is out of range");
805 if ((action != SecurityAction.RequestMinimum && action != SecurityAction.RequestOptional && action != SecurityAction.RequestRefuse) && !for_assembly)
809 Error_AttributeEmitError (String.Concat ("SecurityAction '", action, "' is not valid for this declaration"));
813 System.Security.Permissions.SecurityAction GetSecurityActionValue ()
815 return (SecurityAction)pos_values [0];
819 /// Creates instance of SecurityAttribute class and add result of CreatePermission method to permission table.
821 /// <returns></returns>
822 public void ExtractSecurityPermissionSet (ListDictionary permissions)
824 if (TypeManager.LookupDeclSpace (Type) != null && RootContext.StdLib) {
825 Error_AttributeEmitError ("security custom attributes can not be referenced from defining assembly");
829 SecurityAttribute sa;
830 // For all assemblies except corlib we can avoid all hacks
831 if (RootContext.StdLib) {
832 sa = (SecurityAttribute) Activator.CreateInstance (Type, pos_values);
834 if (prop_info_arr != null) {
835 for (int i = 0; i < prop_info_arr.Length; ++i) {
836 PropertyInfo pi = prop_info_arr [i];
837 pi.SetValue (sa, prop_values_arr [i], null);
841 Type temp_type = Type.GetType (Type.FullName);
842 // HACK: All mscorlib attributes have same ctor syntax
843 sa = (SecurityAttribute) Activator.CreateInstance (temp_type, new object[] { GetSecurityActionValue () } );
845 // All types are from newly created corlib but for invocation with old we need to convert them
846 if (prop_info_arr != null) {
847 for (int i = 0; i < prop_info_arr.Length; ++i) {
848 PropertyInfo emited_pi = prop_info_arr [i];
849 PropertyInfo pi = temp_type.GetProperty (emited_pi.Name, emited_pi.PropertyType);
851 object old_instance = pi.PropertyType.IsEnum ?
852 System.Enum.ToObject (pi.PropertyType, prop_values_arr [i]) :
855 pi.SetValue (sa, old_instance, null);
862 perm = sa.CreatePermission ();
864 catch (Exception e) {
865 Error_AttributeEmitError (String.Format ("{0} was thrown during attribute processing: {1}", e.GetType (), e.Message));
868 SecurityAction action = GetSecurityActionValue ();
870 // IS is correct because for corlib we are using an instance from old corlib
871 if (!(perm is System.Security.CodeAccessPermission)) {
873 case SecurityAction.Demand:
874 action = (SecurityAction)13;
876 case SecurityAction.LinkDemand:
877 action = (SecurityAction)14;
879 case SecurityAction.InheritanceDemand:
880 action = (SecurityAction)15;
885 PermissionSet ps = (PermissionSet)permissions [action];
887 if (sa is PermissionSetAttribute)
888 ps = new PermissionSet (sa.Unrestricted ? PermissionState.Unrestricted : PermissionState.None);
890 ps = new PermissionSet (PermissionState.None);
892 permissions.Add (action, ps);
893 } else if (!ps.IsUnrestricted () && sa.Unrestricted) {
894 ps = ps.Union (new PermissionSet (PermissionState.Unrestricted));
895 permissions [action] = ps;
897 ps.AddPermission (perm);
900 object GetValue (object value)
902 if (value is EnumConstant)
903 return ((EnumConstant) value).GetValue ();
908 public object GetPositionalValue (int i)
910 return (pos_values == null) ? null : pos_values[i];
913 object GetFieldValue (string name)
916 if (field_info_arr == null)
919 foreach (FieldInfo fi in field_info_arr) {
921 return GetValue (field_values_arr [i]);
927 public UnmanagedMarshal GetMarshal (Attributable attr)
929 object value = GetFieldValue ("SizeParamIndex");
930 if (value != null && UnmanagedType != UnmanagedType.LPArray) {
931 Error_AttributeEmitError ("SizeParamIndex field is not valid for the specified unmanaged type");
935 object o = GetFieldValue ("ArraySubType");
936 UnmanagedType array_sub_type = o == null ? UnmanagedType.I4 : (UnmanagedType) o;
938 switch (UnmanagedType) {
939 case UnmanagedType.CustomMarshaler:
940 MethodInfo define_custom = typeof (UnmanagedMarshal).GetMethod ("DefineCustom",
941 BindingFlags.Static | BindingFlags.Public);
942 if (define_custom == null) {
943 Report.RuntimeMissingSupport (Location, "set marshal info");
947 object [] args = new object [4];
948 args [0] = GetFieldValue ("MarshalTypeRef");
949 args [1] = GetFieldValue ("MarshalCookie");
950 args [2] = GetFieldValue ("MarshalType");
951 args [3] = Guid.Empty;
952 return (UnmanagedMarshal) define_custom.Invoke (null, args);
954 case UnmanagedType.LPArray:
955 return UnmanagedMarshal.DefineLPArray (array_sub_type);
957 case UnmanagedType.SafeArray:
958 return UnmanagedMarshal.DefineSafeArray (array_sub_type);
960 case UnmanagedType.ByValArray:
961 FieldMember fm = attr as FieldMember;
963 Error_AttributeEmitError ("Specified unmanaged type is only valid on fields");
966 return UnmanagedMarshal.DefineByValArray ((int) GetFieldValue ("SizeConst"));
968 case UnmanagedType.ByValTStr:
969 return UnmanagedMarshal.DefineByValTStr ((int) GetFieldValue ("SizeConst"));
972 return UnmanagedMarshal.DefineUnmanagedMarshal (UnmanagedType);
976 public bool IsInternalCall
978 get { return ImplOptions == MethodImplOptions.InternalCall; }
982 /// Emit attribute for Attributable symbol
984 public void Emit (EmitContext ec, Attributable ias, ListDictionary emitted_attr)
986 CustomAttributeBuilder cb = Resolve (ec);
990 AttributeUsageAttribute usage_attr = GetAttributeUsage (ec);
991 if ((usage_attr.ValidOn & Target) == 0) {
992 Report.Error (592, Location, "Attribute '{0}' is not valid on this declaration type. It is valid on {1} declarations only.", Name, GetValidTargets ());
996 ias.ApplyAttributeBuilder (this, cb);
998 if (!usage_attr.AllowMultiple) {
999 ArrayList emitted_targets = (ArrayList)emitted_attr [Type];
1000 if (emitted_targets == null) {
1001 emitted_targets = new ArrayList ();
1002 emitted_attr.Add (Type, emitted_targets);
1003 } else if (emitted_targets.Contains (Target)) {
1004 Report.Error (579, Location, "Duplicate '" + Name + "' attribute");
1007 emitted_targets.Add (Target);
1010 if (!RootContext.VerifyClsCompliance)
1013 // Here we are testing attribute arguments for array usage (error 3016)
1014 if (ias.IsClsCompliaceRequired (ec.DeclSpace)) {
1015 if (Arguments == null)
1018 ArrayList pos_args = (ArrayList) Arguments [0];
1019 if (pos_args != null) {
1020 foreach (Argument arg in pos_args) {
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");
1032 if (Arguments.Count < 2)
1035 ArrayList named_args = (ArrayList) Arguments [1];
1036 foreach (DictionaryEntry de in named_args) {
1037 Argument arg = (Argument) de.Value;
1039 // Type is undefined (was error 246)
1040 if (arg.Type == null)
1043 if (arg.Type.IsArray) {
1044 Report.Error (3016, Location, "Arrays as attribute arguments are not CLS-compliant");
1051 public object GetValue (EmitContext ec, Constant c, Type target)
1053 if (Convert.ImplicitConversionExists (ec, c, target))
1054 return c.GetValue ();
1056 Convert.Error_CannotImplicitConversion (Location, c.Type, target);
1060 public MethodBuilder DefinePInvokeMethod (EmitContext ec, TypeBuilder builder, string name,
1061 MethodAttributes flags, Type ret_type, Type [] param_types)
1064 // We extract from the attribute the information we need
1067 if (Arguments == null) {
1068 Console.WriteLine ("Internal error : this is not supposed to happen !");
1076 ArrayList named_args = new ArrayList ();
1078 ArrayList pos_args = (ArrayList) Arguments [0];
1079 if (Arguments.Count > 1)
1080 named_args = (ArrayList) Arguments [1];
1083 string dll_name = null;
1085 Argument tmp = (Argument) pos_args [0];
1087 if (!tmp.Resolve (ec, Location))
1090 if (tmp.Expr is Constant)
1091 dll_name = (string) ((Constant) tmp.Expr).GetValue ();
1093 Error_AttributeArgumentNotValid (Location);
1096 if (dll_name == null || dll_name == ""){
1097 Error_AttributeArgumentNotValid (": DllImport requires a non-empty string", Location);
1101 // Now we process the named arguments
1102 CallingConvention cc = CallingConvention.Winapi;
1103 CharSet charset = CharSet.Ansi;
1104 bool preserve_sig = true;
1106 bool exact_spelling = false;
1108 bool set_last_err = false;
1109 string entry_point = null;
1111 for (int i = 0; i < named_args.Count; i++) {
1113 DictionaryEntry de = (DictionaryEntry) named_args [i];
1115 string member_name = (string) de.Key;
1116 Argument a = (Argument) de.Value;
1118 if (!a.Resolve (ec, Location))
1121 Expression member = Expression.MemberLookup (
1122 ec, Type, member_name,
1123 MemberTypes.Field | MemberTypes.Property,
1124 BindingFlags.Public | BindingFlags.Instance,
1127 if (member == null || !(member is FieldExpr)) {
1128 Error_InvalidNamedArgument (member_name);
1132 if (member is FieldExpr) {
1133 FieldExpr fe = (FieldExpr) member;
1134 FieldInfo fi = fe.FieldInfo;
1136 if (fi.IsInitOnly) {
1137 Error_InvalidNamedArgument (member_name);
1141 if (a.Expr is Constant) {
1142 Constant c = (Constant) a.Expr;
1145 if (member_name == "CallingConvention"){
1146 object val = GetValue (ec, c, typeof (CallingConvention));
1149 cc = (CallingConvention) val;
1150 } else if (member_name == "CharSet"){
1151 charset = (CharSet) c.GetValue ();
1152 } else if (member_name == "EntryPoint")
1153 entry_point = (string) c.GetValue ();
1154 else if (member_name == "SetLastError")
1155 set_last_err = (bool) c.GetValue ();
1157 else if (member_name == "ExactSpelling")
1158 exact_spelling = (bool) c.GetValue ();
1160 else if (member_name == "PreserveSig")
1161 preserve_sig = (bool) c.GetValue ();
1162 } catch (InvalidCastException){
1163 Error_InvalidNamedArgument (member_name);
1164 Error_AttributeArgumentNotValid (Location);
1167 Error_AttributeArgumentNotValid (Location);
1174 if (entry_point == null)
1177 charset = (CharSet)((int)charset | 0x40);
1179 MethodBuilder mb = builder.DefinePInvokeMethod (
1180 name, dll_name, entry_point, flags | MethodAttributes.HideBySig,
1181 CallingConventions.Standard,
1188 mb.SetImplementationFlags (MethodImplAttributes.PreserveSig);
1193 private Expression GetValue ()
1195 if ((Arguments == null) || (Arguments.Count < 1))
1197 ArrayList al = (ArrayList) Arguments [0];
1198 if ((al == null) || (al.Count < 1))
1200 Argument arg = (Argument) al [0];
1201 if ((arg == null) || (arg.Expr == null))
1206 public string GetString ()
1208 Expression e = GetValue ();
1209 if (e is StringLiteral)
1210 return (e as StringLiteral).Value;
1214 public bool GetBoolean ()
1216 Expression e = GetValue ();
1217 if (e is BoolLiteral)
1218 return (e as BoolLiteral).Value;
1225 /// For global attributes (assembly, module) we need special handling.
1226 /// Attributes can be located in the several files
1228 public class GlobalAttribute: Attribute
1230 public readonly NamespaceEntry ns;
1232 public GlobalAttribute (TypeContainer container, string target,
1233 Expression left_expr, string identifier, ArrayList args, Location loc):
1234 base (target, left_expr, identifier, args, loc)
1236 ns = container.NamespaceEntry;
1241 // RootContext.Tree.Types has a single NamespaceEntry which gets overwritten
1242 // each time a new file is parsed. However, we need to use the NamespaceEntry
1243 // in effect where the attribute was used. Since code elsewhere cannot assume
1244 // that the NamespaceEntry is right, just overwrite it.
1246 // Precondition: RootContext.Tree.Types == null
1248 if (RootContext.Tree.Types.NamespaceEntry != null)
1249 throw new InternalErrorException (Location + " non-null NamespaceEntry");
1251 RootContext.Tree.Types.NamespaceEntry = ns;
1256 RootContext.Tree.Types.NamespaceEntry = null;
1259 public override Type ResolveType (EmitContext ec)
1262 Type retval = base.ResolveType (ec);
1267 public override CustomAttributeBuilder Resolve (EmitContext ec)
1270 CustomAttributeBuilder retval = base.Resolve (ec);
1276 public class Attributes {
1277 public ArrayList Attrs;
1279 public Attributes (Attribute a)
1281 Attrs = new ArrayList ();
1285 public Attributes (ArrayList attrs)
1290 public void AddAttributes (ArrayList attrs)
1292 Attrs.AddRange (attrs);
1296 /// Checks whether attribute target is valid for the current element
1298 public bool CheckTargets (Attributable member)
1300 string[] valid_targets = member.ValidAttributeTargets;
1301 foreach (Attribute a in Attrs) {
1302 if (a.ExplicitTarget == null || a.ExplicitTarget == valid_targets [0]) {
1303 a.Target = member.AttributeTargets;
1307 // TODO: we can skip the first item
1308 if (((IList) valid_targets).Contains (a.ExplicitTarget)) {
1309 switch (a.ExplicitTarget) {
1310 case "return": a.Target = AttributeTargets.ReturnValue; continue;
1311 case "param": a.Target = AttributeTargets.Parameter; continue;
1312 case "field": a.Target = AttributeTargets.Field; continue;
1313 case "method": a.Target = AttributeTargets.Method; continue;
1314 case "property": a.Target = AttributeTargets.Property; continue;
1316 throw new InternalErrorException ("Unknown explicit target: " + a.ExplicitTarget);
1319 StringBuilder sb = new StringBuilder ();
1320 foreach (string s in valid_targets) {
1324 sb.Remove (sb.Length - 2, 2);
1325 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 ());
1331 public Attribute Search (Type t, EmitContext ec)
1333 foreach (Attribute a in Attrs) {
1334 if (a.ResolveType (ec) == t)
1341 /// Returns all attributes of type 't'. Use it when attribute is AllowMultiple = true
1343 public Attribute[] SearchMulti (Type t, EmitContext ec)
1345 ArrayList ar = null;
1347 foreach (Attribute a in Attrs) {
1348 if (a.ResolveType (ec) == t) {
1350 ar = new ArrayList ();
1355 return ar == null ? null : ar.ToArray (typeof (Attribute)) as Attribute[];
1358 public void Emit (EmitContext ec, Attributable ias)
1360 if (!CheckTargets (ias))
1363 ListDictionary ld = new ListDictionary ();
1365 foreach (Attribute a in Attrs)
1366 a.Emit (ec, ias, ld);
1369 public bool Contains (Type t, EmitContext ec)
1371 return Search (t, ec) != null;
1376 /// Helper class for attribute verification routine.
1378 sealed class AttributeTester
1380 static PtrHashtable analyzed_types = new PtrHashtable ();
1381 static PtrHashtable analyzed_types_obsolete = new PtrHashtable ();
1382 static PtrHashtable analyzed_member_obsolete = new PtrHashtable ();
1383 static PtrHashtable analyzed_method_excluded = new PtrHashtable ();
1384 static PtrHashtable fixed_buffer_cache = new PtrHashtable ();
1386 static object TRUE = new object ();
1387 static object FALSE = new object ();
1389 private AttributeTester ()
1394 /// Returns true if parameters of two compared methods are CLS-Compliant.
1395 /// It tests differing only in ref or out, or in array rank.
1397 public static bool AreOverloadedMethodParamsClsCompliant (Type[] types_a, Type[] types_b)
1399 if (types_a == null || types_b == null)
1402 if (types_a.Length != types_b.Length)
1405 for (int i = 0; i < types_b.Length; ++i) {
1406 Type aType = types_a [i];
1407 Type bType = types_b [i];
1409 if (aType.IsArray && bType.IsArray && aType.GetArrayRank () != bType.GetArrayRank () && aType.GetElementType () == bType.GetElementType ()) {
1413 Type aBaseType = aType;
1414 bool is_either_ref_or_out = false;
1416 if (aType.IsByRef || aType.IsPointer) {
1417 aBaseType = aType.GetElementType ();
1418 is_either_ref_or_out = true;
1421 Type bBaseType = bType;
1422 if (bType.IsByRef || bType.IsPointer)
1424 bBaseType = bType.GetElementType ();
1425 is_either_ref_or_out = !is_either_ref_or_out;
1428 if (aBaseType != bBaseType)
1431 if (is_either_ref_or_out)
1438 /// Goes through all parameters and test if they are CLS-Compliant.
1440 public static bool AreParametersCompliant (Parameter[] fixedParameters, Location loc)
1442 if (fixedParameters == null)
1445 foreach (Parameter arg in fixedParameters) {
1446 if (!AttributeTester.IsClsCompliant (arg.ParameterType)) {
1447 Report.Error (3001, loc, "Argument type '{0}' is not CLS-compliant", arg.GetSignatureForError ());
1456 /// This method tests the CLS compliance of external types. It doesn't test type visibility.
1458 public static bool IsClsCompliant (Type type)
1463 object type_compliance = analyzed_types[type];
1464 if (type_compliance != null)
1465 return type_compliance == TRUE;
1467 if (type.IsPointer) {
1468 analyzed_types.Add (type, null);
1473 if (type.IsArray || type.IsByRef) {
1474 result = IsClsCompliant (TypeManager.GetElementType (type));
1476 result = AnalyzeTypeCompliance (type);
1478 analyzed_types.Add (type, result ? TRUE : FALSE);
1483 /// Returns IFixedBuffer implementation if field is fixed buffer else null.
1485 public static IFixedBuffer GetFixedBuffer (FieldInfo fi)
1487 FieldBase fb = TypeManager.GetField (fi);
1489 return fb as IFixedBuffer;
1492 object o = fixed_buffer_cache [fi];
1494 if (System.Attribute.GetCustomAttribute (fi, TypeManager.fixed_buffer_attr_type) == null) {
1495 fixed_buffer_cache.Add (fi, FALSE);
1499 IFixedBuffer iff = new FixedFieldExternal (fi);
1500 fixed_buffer_cache.Add (fi, iff);
1507 return (IFixedBuffer)o;
1510 public static void VerifyModulesClsCompliance ()
1512 Module[] modules = TypeManager.Modules;
1513 if (modules == null)
1516 // The first module is generated assembly
1517 for (int i = 1; i < modules.Length; ++i) {
1518 Module module = modules [i];
1519 if (!IsClsCompliant (module)) {
1520 Report.Error (3013, "Added modules must be marked with the CLSCompliant attribute to match the assembly", module.Name);
1527 /// Tests container name for CLS-Compliant name (differing only in case)
1529 public static void VerifyTopLevelNameClsCompliance ()
1531 Hashtable locase_table = new Hashtable ();
1533 // Convert imported type names to lower case and ignore not cls compliant
1534 foreach (DictionaryEntry de in TypeManager.all_imported_types) {
1535 Type t = (Type)de.Value;
1536 if (!AttributeTester.IsClsCompliant (t))
1539 locase_table.Add (((string)de.Key).ToLower (System.Globalization.CultureInfo.InvariantCulture), t);
1542 foreach (DictionaryEntry de in RootContext.Tree.Decls) {
1543 DeclSpace decl = (DeclSpace)de.Value;
1544 if (!decl.IsClsCompliaceRequired (decl))
1547 string lcase = decl.Name.ToLower (System.Globalization.CultureInfo.InvariantCulture);
1548 if (!locase_table.Contains (lcase)) {
1549 locase_table.Add (lcase, decl);
1553 object conflict = locase_table [lcase];
1554 if (conflict is Type)
1555 Report.SymbolRelatedToPreviousError ((Type)conflict);
1557 Report.SymbolRelatedToPreviousError ((MemberCore)conflict);
1559 Report.Error (3005, decl.Location, "Identifier '{0}' differing only in case is not CLS-compliant", decl.GetSignatureForError ());
1563 static bool IsClsCompliant (ICustomAttributeProvider attribute_provider)
1565 object[] CompliantAttribute = attribute_provider.GetCustomAttributes (TypeManager.cls_compliant_attribute_type, false);
1566 if (CompliantAttribute.Length == 0)
1569 return ((CLSCompliantAttribute)CompliantAttribute[0]).IsCompliant;
1572 static bool AnalyzeTypeCompliance (Type type)
1574 DeclSpace ds = TypeManager.LookupDeclSpace (type);
1576 return ds.IsClsCompliaceRequired (ds.Parent);
1579 if (type.IsGenericParameter || type.IsGenericInstance)
1582 object[] CompliantAttribute = type.GetCustomAttributes (TypeManager.cls_compliant_attribute_type, false);
1583 if (CompliantAttribute.Length == 0)
1584 return IsClsCompliant (type.Assembly);
1586 return ((CLSCompliantAttribute)CompliantAttribute[0]).IsCompliant;
1590 /// Returns instance of ObsoleteAttribute when type is obsolete
1592 public static ObsoleteAttribute GetObsoleteAttribute (Type type)
1594 object type_obsolete = analyzed_types_obsolete [type];
1595 if (type_obsolete == FALSE)
1598 if (type_obsolete != null)
1599 return (ObsoleteAttribute)type_obsolete;
1601 ObsoleteAttribute result = null;
1602 if (type.IsByRef || type.IsArray || type.IsPointer) {
1603 result = GetObsoleteAttribute (TypeManager.GetElementType (type));
1604 } else if (type.IsGenericParameter || type.IsGenericInstance)
1607 DeclSpace type_ds = TypeManager.LookupDeclSpace (type);
1609 // Type is external, we can get attribute directly
1610 if (type_ds == null) {
1611 object[] attribute = type.GetCustomAttributes (TypeManager.obsolete_attribute_type, false);
1612 if (attribute.Length == 1)
1613 result = (ObsoleteAttribute)attribute [0];
1615 result = type_ds.GetObsoleteAttribute (type_ds);
1619 analyzed_types_obsolete.Add (type, result == null ? FALSE : result);
1624 /// Returns instance of ObsoleteAttribute when method is obsolete
1626 public static ObsoleteAttribute GetMethodObsoleteAttribute (MethodBase mb)
1628 IMethodData mc = TypeManager.GetMethod (mb);
1630 return mc.GetObsoleteAttribute ();
1632 // compiler generated methods are not registered by AddMethod
1633 if (mb.DeclaringType is TypeBuilder)
1636 PropertyInfo pi = PropertyExpr.AccessorTable [mb] as PropertyInfo;
1638 return GetMemberObsoleteAttribute (pi);
1640 return GetMemberObsoleteAttribute (mb);
1644 /// Returns instance of ObsoleteAttribute when member is obsolete
1646 public static ObsoleteAttribute GetMemberObsoleteAttribute (MemberInfo mi)
1648 object type_obsolete = analyzed_member_obsolete [mi];
1649 if (type_obsolete == FALSE)
1652 if (type_obsolete != null)
1653 return (ObsoleteAttribute)type_obsolete;
1655 if ((mi.DeclaringType is TypeBuilder) || mi.DeclaringType.IsGenericInstance)
1658 ObsoleteAttribute oa = System.Attribute.GetCustomAttribute (mi, TypeManager.obsolete_attribute_type, false) as ObsoleteAttribute;
1659 analyzed_member_obsolete.Add (mi, oa == null ? FALSE : oa);
1664 /// Common method for Obsolete error/warning reporting.
1666 public static void Report_ObsoleteMessage (ObsoleteAttribute oa, string member, Location loc)
1669 Report.Error (619, loc, "'{0}' is obsolete: '{1}'", member, oa.Message);
1673 if (oa.Message == null) {
1674 Report.Warning (612, loc, "'{0}' is obsolete", member);
1677 if (RootContext.WarningLevel >= 2)
1678 Report.Warning (618, loc, "'{0}' is obsolete: '{1}'", member, oa.Message);
1681 public static bool IsConditionalMethodExcluded (MethodBase mb)
1683 object excluded = analyzed_method_excluded [mb];
1684 if (excluded != null)
1685 return excluded == TRUE ? true : false;
1687 if (mb.Mono_IsInflatedMethod)
1690 ConditionalAttribute[] attrs = mb.GetCustomAttributes (TypeManager.conditional_attribute_type, true) as ConditionalAttribute[];
1691 if (attrs.Length == 0) {
1692 analyzed_method_excluded.Add (mb, FALSE);
1696 foreach (ConditionalAttribute a in attrs) {
1697 if (RootContext.AllDefines.Contains (a.ConditionString)) {
1698 analyzed_method_excluded.Add (mb, FALSE);
1702 analyzed_method_excluded.Add (mb, TRUE);