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;
26 namespace Mono.CSharp {
29 /// Base class for objects that can have Attributes applied to them.
31 public abstract class Attributable {
33 /// Attributes for this type
35 Attributes attributes;
37 public Attributable (Attributes attrs)
42 public Attributes OptAttributes
53 /// Use member-specific procedure to apply attribute @a in @cb to the entity being built in @builder
55 public abstract void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb);
58 /// Returns one AttributeTarget for this element.
60 public abstract AttributeTargets AttributeTargets { get; }
62 public abstract bool IsClsCompliaceRequired (DeclSpace ds);
65 /// Gets list of valid attribute targets for explicit target declaration.
66 /// The first array item is default target. Don't break this rule.
68 public abstract string[] ValidAttributeTargets { get; }
71 public class Attribute {
72 public readonly string ExplicitTarget;
73 public AttributeTargets Target;
75 // TODO: remove this member
76 public readonly string Name;
77 public readonly Expression LeftExpr;
78 public readonly string Identifier;
80 public readonly ArrayList Arguments;
82 public readonly Location Location;
88 static AttributeUsageAttribute DefaultUsageAttribute = new AttributeUsageAttribute (AttributeTargets.All);
89 static Assembly orig_sec_assembly;
91 // non-null if named args present after Resolve () is called
92 PropertyInfo [] prop_info_arr;
93 FieldInfo [] field_info_arr;
94 object [] field_values_arr;
95 object [] prop_values_arr;
98 static PtrHashtable usage_attr_cache = new PtrHashtable ();
100 public Attribute (string target, Expression left_expr, string identifier, ArrayList args, Location loc)
102 LeftExpr = left_expr;
103 Identifier = identifier;
104 Name = LeftExpr == null ? identifier : LeftExpr + "." + identifier;
107 ExplicitTarget = target;
110 void Error_InvalidNamedArgument (string name)
112 Report.Error (617, Location, "`{0}' is not a valid named attribute argument. Named attribute arguments must be fields which are not readonly, static, const or read-write properties which are public and not static",
116 void Error_InvalidNamedAgrumentType (string name)
118 Report.Error (655, Location, "`{0}' is not a valid named attribute argument because it is not a valid attribute parameter type", name);
121 static void Error_AttributeArgumentNotValid (string extra, Location loc)
123 Report.Error (182, loc,
124 "An attribute argument must be a constant expression, typeof " +
125 "expression or array creation expression" + extra);
128 static void Error_AttributeArgumentNotValid (Location loc)
130 Error_AttributeArgumentNotValid ("", loc);
135 /// This is rather hack. We report many emit attribute error with same error to be compatible with
136 /// csc. But because csc has to report them this way because error came from ilasm we needn't.
138 public void Error_AttributeEmitError (string inner)
140 Report.Error (647, Location, "Error during emitting `{0}' attribute. The reason is `{1}'", TypeManager.CSharpName (Type), inner);
143 public void Error_InvalidSecurityParent ()
145 Error_AttributeEmitError ("it is attached to invalid parent");
148 protected virtual FullNamedExpression ResolveAsTypeTerminal (Expression expr, EmitContext ec, bool silent)
150 return expr.ResolveAsTypeTerminal (ec, silent);
153 protected virtual FullNamedExpression ResolveAsTypeStep (Expression expr, EmitContext ec, bool silent)
155 return expr.ResolveAsTypeStep (ec, silent);
158 Type ResolvePossibleAttributeType (EmitContext ec, string name, bool silent, ref bool is_attr)
160 FullNamedExpression fn;
161 if (LeftExpr == null) {
162 fn = ResolveAsTypeTerminal (new SimpleName (name, Location), ec, silent);
164 fn = ResolveAsTypeStep (LeftExpr, ec, silent);
167 fn = new MemberAccess (fn, name, Location).ResolveAsTypeTerminal (ec, silent);
170 TypeExpr te = fn as TypeExpr;
175 if (t.IsSubclassOf (TypeManager.attribute_type)) {
177 } else if (!silent) {
178 Report.SymbolRelatedToPreviousError (t);
179 Report.Error (616, Location, "`{0}': is not an attribute class", TypeManager.CSharpName (t));
185 /// Tries to resolve the type of the attribute. Flags an error if it can't, and complain is true.
187 void ResolveAttributeType (EmitContext ec)
189 bool t1_is_attr = false;
190 Type t1 = ResolvePossibleAttributeType (ec, Identifier, true, ref t1_is_attr);
192 // FIXME: Shouldn't do this for quoted attributes: [@A]
193 bool t2_is_attr = false;
194 Type t2 = ResolvePossibleAttributeType (ec, Identifier + "Attribute", true, ref t2_is_attr);
196 if (t1_is_attr && t2_is_attr) {
197 Report.Error (1614, Location, "`{0}' is ambiguous between `{0}' and `{0}Attribute'. Use either `@{0}' or `{0}Attribute'", GetSignatureForError ());
198 resolve_error = true;
212 if (t1 == null && t2 == null)
213 ResolvePossibleAttributeType (ec, Identifier, false, ref t1_is_attr);
215 ResolvePossibleAttributeType (ec, Identifier, false, ref t1_is_attr);
217 ResolvePossibleAttributeType (ec, Identifier + "Attribute", false, ref t2_is_attr);
219 resolve_error = true;
222 public virtual Type ResolveType (EmitContext ec)
224 if (Type == null && !resolve_error)
225 ResolveAttributeType (ec);
229 public string GetSignatureForError ()
231 return LeftExpr == null ? Identifier : LeftExpr.GetSignatureForError () + "." + Identifier;
235 // Given an expression, if the expression is a valid attribute-argument-expression
236 // returns an object that can be used to encode it, or null on failure.
238 public static bool GetAttributeArgumentExpression (Expression e, Location loc, Type arg_type, out object result)
240 if (e is EnumConstant) {
241 if (RootContext.StdLib)
242 result = ((EnumConstant)e).GetValueAsEnumType ();
244 result = ((EnumConstant)e).GetValue ();
249 Constant constant = e as Constant;
250 if (constant != null) {
251 if (e.Type != arg_type) {
252 constant = Const.ChangeType (loc, constant, arg_type);
253 if (constant == null) {
255 Error_AttributeArgumentNotValid (loc);
259 result = constant.GetValue ();
261 } else if (e is TypeOf) {
262 result = ((TypeOf) e).TypeArg;
264 } else if (e is ArrayCreation){
265 result = ((ArrayCreation) e).EncodeAsAttribute ();
268 } else if (e is EmptyCast) {
269 Expression child = ((EmptyCast)e).Child;
270 return GetAttributeArgumentExpression (child, loc, child.Type, out result);
274 Error_AttributeArgumentNotValid (loc);
278 bool IsValidArgumentType (Type t)
280 return TypeManager.IsPrimitiveType (t) ||
281 (t.IsArray && TypeManager.IsPrimitiveType (t.GetElementType ())) ||
282 TypeManager.IsEnumType (t) ||
283 t == TypeManager.string_type ||
284 t == TypeManager.object_type ||
285 t == TypeManager.type_type;
288 // Cache for parameter-less attributes
289 static PtrHashtable att_cache = new PtrHashtable ();
291 public CustomAttributeBuilder Resolve (EmitContext ec)
296 resolve_error = true;
299 ResolveAttributeType (ec);
304 if (Type.IsAbstract) {
305 Report.Error (653, Location, "Cannot apply attribute class `{0}' because it is abstract", GetSignatureForError ());
309 if (Arguments == null) {
310 object o = att_cache [Type];
312 resolve_error = false;
313 return (CustomAttributeBuilder)o;
317 ConstructorInfo ctor = ResolveArguments (ec);
321 CustomAttributeBuilder cb;
324 if (prop_info_arr != null || field_info_arr != null) {
325 cb = new CustomAttributeBuilder (
327 prop_info_arr, prop_values_arr,
328 field_info_arr, field_values_arr);
330 cb = new CustomAttributeBuilder (
333 if (pos_values.Length == 0)
334 att_cache.Add (Type, cb);
338 Error_AttributeArgumentNotValid (Location);
342 resolve_error = false;
346 protected virtual ConstructorInfo ResolveArguments (EmitContext ec)
348 // Now we extract the positional and named arguments
350 ArrayList pos_args = null;
351 ArrayList named_args = null;
352 int pos_arg_count = 0;
353 int named_arg_count = 0;
355 if (Arguments != null) {
356 pos_args = (ArrayList) Arguments [0];
357 if (pos_args != null)
358 pos_arg_count = pos_args.Count;
359 if (Arguments.Count > 1) {
360 named_args = (ArrayList) Arguments [1];
361 named_arg_count = named_args.Count;
365 pos_values = new object [pos_arg_count];
368 // First process positional arguments
372 for (i = 0; i < pos_arg_count; i++) {
373 Argument a = (Argument) pos_args [i];
376 if (!a.Resolve (ec, Location))
382 if (!GetAttributeArgumentExpression (e, Location, a.Type, out val))
385 pos_values [i] = val;
387 if (i == 0 && Type == TypeManager.attribute_usage_type && (int)val == 0) {
388 Report.Error (591, Location, "Invalid value for argument to 'System.AttributeUsage' attribute");
394 // Now process named arguments
397 ArrayList field_infos = null;
398 ArrayList prop_infos = null;
399 ArrayList field_values = null;
400 ArrayList prop_values = null;
401 Hashtable seen_names = null;
403 if (named_arg_count > 0) {
404 field_infos = new ArrayList ();
405 prop_infos = new ArrayList ();
406 field_values = new ArrayList ();
407 prop_values = new ArrayList ();
409 seen_names = new Hashtable();
412 for (i = 0; i < named_arg_count; i++) {
413 DictionaryEntry de = (DictionaryEntry) named_args [i];
414 string member_name = (string) de.Key;
415 Argument a = (Argument) de.Value;
418 if (seen_names.Contains(member_name)) {
419 Report.Error(643, Location, "'" + member_name + "' duplicate named attribute argument");
422 seen_names.Add(member_name, 1);
424 if (!a.Resolve (ec, Location))
427 Expression member = Expression.MemberLookup (
428 ec, Type, member_name,
429 MemberTypes.Field | MemberTypes.Property,
430 BindingFlags.Public | BindingFlags.Instance,
433 if (member == null) {
434 member = Expression.MemberLookup (ec, Type, member_name,
435 MemberTypes.Field | MemberTypes.Property, BindingFlags.NonPublic | BindingFlags.Instance,
438 if (member != null) {
439 Expression.ErrorIsInaccesible (Location, member.GetSignatureForError ());
445 Report.Error (117, Location, "`{0}' does not contain a definition for `{1}'",
450 if (!(member is PropertyExpr || member is FieldExpr)) {
451 Error_InvalidNamedArgument (member_name);
456 if (member is PropertyExpr) {
457 PropertyExpr pe = (PropertyExpr) member;
458 PropertyInfo pi = pe.PropertyInfo;
460 if (!pi.CanWrite || !pi.CanRead) {
461 Report.SymbolRelatedToPreviousError (pi);
462 Error_InvalidNamedArgument (member_name);
466 if (!IsValidArgumentType (pi.PropertyType)) {
467 Report.SymbolRelatedToPreviousError (pi);
468 Error_InvalidNamedAgrumentType (member_name);
473 if (!GetAttributeArgumentExpression (e, Location, pi.PropertyType, out value))
476 prop_values.Add (value);
479 } else if (member is FieldExpr) {
480 FieldExpr fe = (FieldExpr) member;
481 FieldInfo fi = fe.FieldInfo;
484 Error_InvalidNamedArgument (member_name);
488 if (!IsValidArgumentType (fi.FieldType)) {
489 Report.SymbolRelatedToPreviousError (fi);
490 Error_InvalidNamedAgrumentType (member_name);
495 if (!GetAttributeArgumentExpression (e, Location, fi.FieldType, out value))
498 field_values.Add (value);
499 field_infos.Add (fi);
503 Expression mg = Expression.MemberLookup (
504 ec, Type, ".ctor", MemberTypes.Constructor,
505 BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly,
508 MethodBase constructor = Invocation.OverloadResolve (
509 ec, (MethodGroupExpr) mg, pos_args, false, Location);
511 if (constructor == null) {
516 // Here we do the checks which should be done by corlib or by runtime.
517 // However Zoltan doesn't like it and every Mono compiler has to do it again.
519 if (Type == TypeManager.guid_attr_type) {
521 new Guid ((string)pos_values [0]);
523 catch (Exception e) {
524 Error_AttributeEmitError (e.Message);
528 // if (Type == TypeManager.methodimpl_attr_type &&
529 // pos_values.Length == 1 && ((Argument)pos_args [0]).Type == TypeManager.short_type &&
530 // !System.Enum.IsDefined (TypeManager.method_impl_options, pos_values [0])) {
531 // Error_AttributeEmitError ("Incorrect argument value.");
535 // Now we perform some checks on the positional args as they
536 // cannot be null for a constructor which expects a parameter
540 ParameterData pd = TypeManager.GetParameterData (constructor);
542 int last_real_param = pd.Count;
544 // When the params is not filled we need to put one
545 if (last_real_param > pos_arg_count) {
546 object [] new_pos_values = new object [pos_arg_count + 1];
547 pos_values.CopyTo (new_pos_values, 0);
548 new_pos_values [pos_arg_count] = new object [] {} ;
549 pos_values = new_pos_values;
554 for (int j = 0; j < pos_arg_count; ++j) {
555 Argument a = (Argument) pos_args [j];
557 if (a.Expr is NullLiteral && pd.ParameterType (j) == TypeManager.object_type) {
558 Error_AttributeArgumentNotValid (Location);
562 object value = pos_values [j];
563 if (value != null && a.Type != value.GetType () && TypeManager.IsPrimitiveType (a.Type)) {
565 pos_values [j] = TypeManager.ChangeType (value, a.Type, out fail);
567 // TODO: Can failed ?
568 throw new NotImplementedException ();
572 if (j < last_real_param)
575 if (j == last_real_param) {
576 object [] array = new object [pos_arg_count - last_real_param];
577 array [0] = pos_values [j];
578 pos_values [j] = array;
582 object [] params_array = (object []) pos_values [last_real_param];
583 params_array [j - last_real_param] = pos_values [j];
586 // Adjust the size of the pos_values if it had params
587 if (last_real_param != pos_arg_count) {
588 object [] new_pos_values = new object [last_real_param + 1];
589 Array.Copy (pos_values, new_pos_values, last_real_param + 1);
590 pos_values = new_pos_values;
593 if (named_arg_count > 0) {
594 prop_info_arr = new PropertyInfo [prop_infos.Count];
595 field_info_arr = new FieldInfo [field_infos.Count];
596 field_values_arr = new object [field_values.Count];
597 prop_values_arr = new object [prop_values.Count];
599 field_infos.CopyTo (field_info_arr, 0);
600 field_values.CopyTo (field_values_arr, 0);
602 prop_values.CopyTo (prop_values_arr, 0);
603 prop_infos.CopyTo (prop_info_arr, 0);
606 return (ConstructorInfo) constructor;
610 /// Get a string containing a list of valid targets for the attribute 'attr'
612 public string GetValidTargets ()
614 StringBuilder sb = new StringBuilder ();
615 AttributeTargets targets = GetAttributeUsage (null).ValidOn;
617 if ((targets & AttributeTargets.Assembly) != 0)
618 sb.Append ("assembly, ");
620 if ((targets & AttributeTargets.Module) != 0)
621 sb.Append ("module, ");
623 if ((targets & AttributeTargets.Class) != 0)
624 sb.Append ("class, ");
626 if ((targets & AttributeTargets.Struct) != 0)
627 sb.Append ("struct, ");
629 if ((targets & AttributeTargets.Enum) != 0)
630 sb.Append ("enum, ");
632 if ((targets & AttributeTargets.Constructor) != 0)
633 sb.Append ("constructor, ");
635 if ((targets & AttributeTargets.Method) != 0)
636 sb.Append ("method, ");
638 if ((targets & AttributeTargets.Property) != 0)
639 sb.Append ("property, indexer, ");
641 if ((targets & AttributeTargets.Field) != 0)
642 sb.Append ("field, ");
644 if ((targets & AttributeTargets.Event) != 0)
645 sb.Append ("event, ");
647 if ((targets & AttributeTargets.Interface) != 0)
648 sb.Append ("interface, ");
650 if ((targets & AttributeTargets.Parameter) != 0)
651 sb.Append ("parameter, ");
653 if ((targets & AttributeTargets.Delegate) != 0)
654 sb.Append ("delegate, ");
656 if ((targets & AttributeTargets.ReturnValue) != 0)
657 sb.Append ("return, ");
660 if ((targets & AttributeTargets.GenericParameter) != 0)
661 sb.Append ("type parameter, ");
663 return sb.Remove (sb.Length - 2, 2).ToString ();
667 /// Returns AttributeUsage attribute for this type
669 AttributeUsageAttribute GetAttributeUsage (EmitContext ec)
671 AttributeUsageAttribute ua = usage_attr_cache [Type] as AttributeUsageAttribute;
675 Class attr_class = TypeManager.LookupClass (Type);
677 if (attr_class == null) {
678 object[] usage_attr = Type.GetCustomAttributes (TypeManager.attribute_usage_type, true);
679 ua = (AttributeUsageAttribute)usage_attr [0];
680 usage_attr_cache.Add (Type, ua);
684 Attribute a = attr_class.OptAttributes == null
686 : attr_class.OptAttributes.Search (TypeManager.attribute_usage_type, attr_class.EmitContext);
689 ? DefaultUsageAttribute
690 : a.GetAttributeUsageAttribute (attr_class.EmitContext);
692 usage_attr_cache.Add (Type, ua);
696 AttributeUsageAttribute GetAttributeUsageAttribute (EmitContext ec)
698 if (pos_values == null)
699 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
700 // But because a lot of attribute class code must be rewritten will be better to wait...
704 return DefaultUsageAttribute;
706 AttributeUsageAttribute usage_attribute = new AttributeUsageAttribute ((AttributeTargets)pos_values [0]);
708 object field = GetPropertyValue ("AllowMultiple");
710 usage_attribute.AllowMultiple = (bool)field;
712 field = GetPropertyValue ("Inherited");
714 usage_attribute.Inherited = (bool)field;
716 return usage_attribute;
720 /// Returns custom name of indexer
722 public string GetIndexerAttributeValue (EmitContext ec)
724 if (pos_values == null)
725 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
726 // But because a lot of attribute class code must be rewritten will be better to wait...
732 return pos_values [0] as string;
736 /// Returns condition of ConditionalAttribute
738 public string GetConditionalAttributeValue (EmitContext ec)
740 if (pos_values == null)
741 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
742 // But because a lot of attribute class code must be rewritten will be better to wait...
748 return (string)pos_values [0];
752 /// Creates the instance of ObsoleteAttribute from this attribute instance
754 public ObsoleteAttribute GetObsoleteAttribute (EmitContext ec)
756 if (pos_values == null)
757 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
758 // But because a lot of attribute class code must be rewritten will be better to wait...
764 if (pos_values == null || pos_values.Length == 0)
765 return new ObsoleteAttribute ();
767 if (pos_values.Length == 1)
768 return new ObsoleteAttribute ((string)pos_values [0]);
770 return new ObsoleteAttribute ((string)pos_values [0], (bool)pos_values [1]);
774 /// Returns value of CLSCompliantAttribute contructor parameter but because the method can be called
775 /// before ApplyAttribute. We need to resolve the arguments.
776 /// This situation occurs when class deps is differs from Emit order.
778 public bool GetClsCompliantAttributeValue (EmitContext ec)
780 if (pos_values == null)
781 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
782 // But because a lot of attribute class code must be rewritten will be better to wait...
788 return (bool)pos_values [0];
792 /// Tests permitted SecurityAction for assembly or other types
794 public bool CheckSecurityActionValidity (bool for_assembly)
796 SecurityAction action = GetSecurityActionValue ();
798 if ((action == SecurityAction.RequestMinimum || action == SecurityAction.RequestOptional || action == SecurityAction.RequestRefuse) && for_assembly)
802 if (action < SecurityAction.Demand || action > SecurityAction.InheritanceDemand) {
803 Error_AttributeEmitError ("SecurityAction is out of range");
807 if ((action != SecurityAction.RequestMinimum && action != SecurityAction.RequestOptional && action != SecurityAction.RequestRefuse) && !for_assembly)
811 Error_AttributeEmitError (String.Concat ("SecurityAction '", action, "' is not valid for this declaration"));
815 System.Security.Permissions.SecurityAction GetSecurityActionValue ()
817 return (SecurityAction)pos_values [0];
821 /// Creates instance of SecurityAttribute class and add result of CreatePermission method to permission table.
823 /// <returns></returns>
824 public void ExtractSecurityPermissionSet (ListDictionary permissions)
826 Type orig_assembly_type = null;
828 if (TypeManager.LookupDeclSpace (Type) != null) {
829 if (!RootContext.StdLib) {
830 orig_assembly_type = Type.GetType (Type.FullName);
832 string orig_version_path = Environment.GetEnvironmentVariable ("__SECURITY_BOOTSTRAP_DB");
833 if (orig_version_path == null) {
834 Error_AttributeEmitError ("security custom attributes can not be referenced from defining assembly");
838 if (orig_sec_assembly == null) {
839 string file = Path.Combine (orig_version_path, Driver.OutputFile);
840 orig_sec_assembly = Assembly.LoadFile (file);
843 orig_assembly_type = orig_sec_assembly.GetType (Type.FullName, true);
844 if (orig_assembly_type == null) {
845 Report.Warning (-112, 1, Location, "Self-referenced security attribute `{0}' was not found in previous version of assembly");
851 SecurityAttribute sa;
852 // For all non-selfreferencing security attributes we can avoid all hacks
853 if (orig_assembly_type == null) {
854 sa = (SecurityAttribute) Activator.CreateInstance (Type, pos_values);
856 if (prop_info_arr != null) {
857 for (int i = 0; i < prop_info_arr.Length; ++i) {
858 PropertyInfo pi = prop_info_arr [i];
859 pi.SetValue (sa, prop_values_arr [i], null);
863 // HACK: All security attributes have same ctor syntax
864 sa = (SecurityAttribute) Activator.CreateInstance (orig_assembly_type, new object[] { GetSecurityActionValue () } );
866 // All types are from newly created assembly but for invocation with old one we need to convert them
867 if (prop_info_arr != null) {
868 for (int i = 0; i < prop_info_arr.Length; ++i) {
869 PropertyInfo emited_pi = prop_info_arr [i];
870 PropertyInfo pi = orig_assembly_type.GetProperty (emited_pi.Name, emited_pi.PropertyType);
872 object old_instance = pi.PropertyType.IsEnum ?
873 System.Enum.ToObject (pi.PropertyType, prop_values_arr [i]) :
876 pi.SetValue (sa, old_instance, null);
882 perm = sa.CreatePermission ();
883 SecurityAction action = GetSecurityActionValue ();
885 // IS is correct because for corlib we are using an instance from old corlib
886 if (!(perm is System.Security.CodeAccessPermission)) {
888 case SecurityAction.Demand:
889 action = (SecurityAction)13;
891 case SecurityAction.LinkDemand:
892 action = (SecurityAction)14;
894 case SecurityAction.InheritanceDemand:
895 action = (SecurityAction)15;
900 PermissionSet ps = (PermissionSet)permissions [action];
902 if (sa is PermissionSetAttribute)
903 ps = new PermissionSet (sa.Unrestricted ? PermissionState.Unrestricted : PermissionState.None);
905 ps = new PermissionSet (PermissionState.None);
907 permissions.Add (action, ps);
908 } else if (!ps.IsUnrestricted () && (sa is PermissionSetAttribute) && sa.Unrestricted) {
909 ps = ps.Union (new PermissionSet (PermissionState.Unrestricted));
910 permissions [action] = ps;
912 ps.AddPermission (perm);
915 object GetValue (object value)
917 if (value is EnumConstant)
918 return ((EnumConstant) value).GetValue ();
923 object GetPropertyValue (string name)
925 if (prop_info_arr == null)
928 for (int i = 0; i < prop_info_arr.Length; ++i) {
929 if (prop_info_arr [i].Name == name)
930 return prop_values_arr [i];
936 object GetFieldValue (string name)
939 if (field_info_arr == null)
942 foreach (FieldInfo fi in field_info_arr) {
944 return GetValue (field_values_arr [i]);
950 public UnmanagedMarshal GetMarshal (Attributable attr)
952 UnmanagedType UnmanagedType = (UnmanagedType)System.Enum.Parse (typeof (UnmanagedType), pos_values [0].ToString ());
954 object value = GetFieldValue ("SizeParamIndex");
955 if (value != null && UnmanagedType != UnmanagedType.LPArray) {
956 Error_AttributeEmitError ("SizeParamIndex field is not valid for the specified unmanaged type");
960 object o = GetFieldValue ("ArraySubType");
961 UnmanagedType array_sub_type = o == null ? UnmanagedType.I4 : (UnmanagedType) o;
963 switch (UnmanagedType) {
964 case UnmanagedType.CustomMarshaler: {
965 MethodInfo define_custom = typeof (UnmanagedMarshal).GetMethod ("DefineCustom",
966 BindingFlags.Static | BindingFlags.Public);
967 if (define_custom == null) {
968 Report.RuntimeMissingSupport (Location, "set marshal info");
972 object [] args = new object [4];
973 args [0] = GetFieldValue ("MarshalTypeRef");
974 args [1] = GetFieldValue ("MarshalCookie");
975 args [2] = GetFieldValue ("MarshalType");
976 args [3] = Guid.Empty;
977 return (UnmanagedMarshal) define_custom.Invoke (null, args);
979 case UnmanagedType.LPArray: {
980 object size_const = GetFieldValue ("SizeConst");
981 object size_param_index = GetFieldValue ("SizeParamIndex");
983 if ((size_const != null) || (size_param_index != null)) {
984 MethodInfo define_array = typeof (UnmanagedMarshal).GetMethod ("DefineLPArrayInternal", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
985 if (define_array == null) {
986 Report.RuntimeMissingSupport (Location, "set marshal info");
990 object [] args = new object [3];
991 args [0] = array_sub_type;
992 args [1] = size_const == null ? -1 : size_const;
993 args [2] = size_param_index == null ? -1 : size_param_index;
994 return (UnmanagedMarshal) define_array.Invoke (null, args);
997 return UnmanagedMarshal.DefineLPArray (array_sub_type);
999 case UnmanagedType.SafeArray:
1000 return UnmanagedMarshal.DefineSafeArray (array_sub_type);
1002 case UnmanagedType.ByValArray:
1003 FieldMember fm = attr as FieldMember;
1005 Error_AttributeEmitError ("Specified unmanaged type is only valid on fields");
1008 return UnmanagedMarshal.DefineByValArray ((int) GetFieldValue ("SizeConst"));
1010 case UnmanagedType.ByValTStr:
1011 return UnmanagedMarshal.DefineByValTStr ((int) GetFieldValue ("SizeConst"));
1014 return UnmanagedMarshal.DefineUnmanagedMarshal (UnmanagedType);
1018 public CharSet GetCharSetValue ()
1020 return (CharSet)System.Enum.Parse (typeof (CharSet), pos_values [0].ToString ());
1023 public MethodImplOptions GetMethodImplOptions ()
1025 return (MethodImplOptions)System.Enum.Parse (typeof (MethodImplOptions), pos_values [0].ToString ());
1028 public LayoutKind GetLayoutKindValue ()
1030 return (LayoutKind)System.Enum.Parse (typeof (LayoutKind), pos_values [0].ToString ());
1034 /// Emit attribute for Attributable symbol
1036 public void Emit (EmitContext ec, Attributable ias, ListDictionary emitted_attr)
1038 CustomAttributeBuilder cb = Resolve (ec);
1042 AttributeUsageAttribute usage_attr = GetAttributeUsage (ec);
1043 if ((usage_attr.ValidOn & Target) == 0) {
1044 Report.Error (592, Location, "Attribute `{0}' is not valid on this declaration type. It is valid on `{1}' declarations only",
1045 GetSignatureForError (), GetValidTargets ());
1050 ias.ApplyAttributeBuilder (this, cb);
1052 catch (Exception e) {
1053 Error_AttributeEmitError (e.Message);
1057 if (!usage_attr.AllowMultiple) {
1058 ArrayList emitted_targets = (ArrayList)emitted_attr [Type];
1059 if (emitted_targets == null) {
1060 emitted_targets = new ArrayList ();
1061 emitted_attr.Add (Type, emitted_targets);
1062 } else if (emitted_targets.Contains (Target)) {
1063 Report.Error (579, Location, "Duplicate `{0}' attribute", GetSignatureForError ());
1066 emitted_targets.Add (Target);
1069 if (!RootContext.VerifyClsCompliance)
1072 // Here we are testing attribute arguments for array usage (error 3016)
1073 if (ias.IsClsCompliaceRequired (ec.DeclSpace)) {
1074 if (Arguments == null)
1077 ArrayList pos_args = (ArrayList) Arguments [0];
1078 if (pos_args != null) {
1079 foreach (Argument arg in pos_args) {
1080 // Type is undefined (was error 246)
1081 if (arg.Type == null)
1084 if (arg.Type.IsArray) {
1085 Report.Error (3016, Location, "Arrays as attribute arguments are not CLS-compliant");
1091 if (Arguments.Count < 2)
1094 ArrayList named_args = (ArrayList) Arguments [1];
1095 foreach (DictionaryEntry de in named_args) {
1096 Argument arg = (Argument) de.Value;
1098 // Type is undefined (was error 246)
1099 if (arg.Type == null)
1102 if (arg.Type.IsArray) {
1103 Report.Error (3016, Location, "Arrays as attribute arguments are not CLS-compliant");
1110 public MethodBuilder DefinePInvokeMethod (EmitContext ec, TypeBuilder builder, string name,
1111 MethodAttributes flags, Type ret_type, Type [] param_types)
1113 if (pos_values == null)
1114 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
1115 // But because a lot of attribute class code must be rewritten will be better to wait...
1121 string dll_name = (string)pos_values [0];
1124 CallingConvention cc = CallingConvention.Winapi;
1125 CharSet charset = CodeGen.Module.DefaultCharSet;
1126 bool preserve_sig = true;
1127 string entry_point = name;
1128 bool best_fit_mapping = false;
1129 bool throw_on_unmappable = false;
1130 bool exact_spelling = false;
1131 bool set_last_error = false;
1133 bool best_fit_mapping_set = false;
1134 bool throw_on_unmappable_set = false;
1135 bool exact_spelling_set = false;
1136 bool set_last_error_set = false;
1138 MethodInfo set_best_fit = null;
1139 MethodInfo set_throw_on = null;
1140 MethodInfo set_exact_spelling = null;
1141 MethodInfo set_set_last_error = null;
1143 if (field_info_arr != null) {
1145 for (int i = 0; i < field_info_arr.Length; i++) {
1146 switch (field_info_arr [i].Name) {
1147 case "BestFitMapping":
1148 best_fit_mapping = (bool) field_values_arr [i];
1149 best_fit_mapping_set = true;
1151 case "CallingConvention":
1152 cc = (CallingConvention) field_values_arr [i];
1155 charset = (CharSet) field_values_arr [i];
1158 entry_point = (string) field_values_arr [i];
1160 case "ExactSpelling":
1161 exact_spelling = (bool) field_values_arr [i];
1162 exact_spelling_set = true;
1165 preserve_sig = (bool) field_values_arr [i];
1167 case "SetLastError":
1168 set_last_error = (bool) field_values_arr [i];
1169 set_last_error_set = true;
1171 case "ThrowOnUnmappableChar":
1172 throw_on_unmappable = (bool) field_values_arr [i];
1173 throw_on_unmappable_set = true;
1176 throw new InternalErrorException (field_info_arr [i].ToString ());
1181 if (throw_on_unmappable_set || best_fit_mapping_set || exact_spelling_set || set_last_error_set) {
1182 set_best_fit = typeof (MethodBuilder).GetMethod ("set_BestFitMapping", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
1183 set_throw_on = typeof (MethodBuilder).GetMethod ("set_ThrowOnUnmappableChar", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
1184 set_exact_spelling = typeof (MethodBuilder).GetMethod ("set_ExactSpelling", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
1185 set_set_last_error = typeof (MethodBuilder).GetMethod ("set_SetLastError", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
1187 if ((set_best_fit == null) || (set_throw_on == null) || (set_exact_spelling == null) || (set_set_last_error == null)) {
1188 Report.Error (-1, Location,
1189 "The ThrowOnUnmappableChar, BestFitMapping, SetLastError, and ExactSpelling attributes can only be emitted when running on the mono runtime.");
1195 MethodBuilder mb = builder.DefinePInvokeMethod (
1196 name, dll_name, entry_point, flags | MethodAttributes.HideBySig | MethodAttributes.PinvokeImpl,
1197 CallingConventions.Standard, ret_type, param_types, cc, charset);
1200 mb.SetImplementationFlags (MethodImplAttributes.PreserveSig);
1202 if (throw_on_unmappable_set)
1203 set_throw_on.Invoke (mb, 0, null, new object [] { throw_on_unmappable }, null);
1204 if (best_fit_mapping_set)
1205 set_best_fit.Invoke (mb, 0, null, new object [] { best_fit_mapping }, null);
1206 if (exact_spelling_set)
1207 set_exact_spelling.Invoke (mb, 0, null, new object [] { exact_spelling }, null);
1208 if (set_last_error_set)
1209 set_set_last_error.Invoke (mb, 0, null, new object [] { set_last_error }, null);
1213 catch (ArgumentException e) {
1214 Error_AttributeEmitError (e.Message);
1219 private Expression GetValue ()
1221 if ((Arguments == null) || (Arguments.Count < 1))
1223 ArrayList al = (ArrayList) Arguments [0];
1224 if ((al == null) || (al.Count < 1))
1226 Argument arg = (Argument) al [0];
1227 if ((arg == null) || (arg.Expr == null))
1232 public string GetString ()
1234 Expression e = GetValue ();
1235 if (e is StringLiteral)
1236 return (e as StringLiteral).Value;
1240 public bool GetBoolean ()
1242 Expression e = GetValue ();
1243 if (e is BoolLiteral)
1244 return (e as BoolLiteral).Value;
1251 /// For global attributes (assembly, module) we need special handling.
1252 /// Attributes can be located in the several files
1254 public class GlobalAttribute: Attribute
1256 public readonly NamespaceEntry ns;
1258 public GlobalAttribute (TypeContainer container, string target,
1259 Expression left_expr, string identifier, ArrayList args, Location loc):
1260 base (target, left_expr, identifier, args, loc)
1262 ns = container.NamespaceEntry;
1267 // RootContext.Tree.Types has a single NamespaceEntry which gets overwritten
1268 // each time a new file is parsed. However, we need to use the NamespaceEntry
1269 // in effect where the attribute was used. Since code elsewhere cannot assume
1270 // that the NamespaceEntry is right, just overwrite it.
1272 // Precondition: RootContext.Tree.Types == null
1274 if (RootContext.Tree.Types.NamespaceEntry != null)
1275 throw new InternalErrorException (Location + " non-null NamespaceEntry");
1277 RootContext.Tree.Types.NamespaceEntry = ns;
1282 RootContext.Tree.Types.NamespaceEntry = null;
1285 protected override FullNamedExpression ResolveAsTypeStep (Expression expr, EmitContext ec, bool silent)
1289 return base.ResolveAsTypeStep (expr, ec, silent);
1297 protected override FullNamedExpression ResolveAsTypeTerminal (Expression expr, EmitContext ec, bool silent)
1301 return base.ResolveAsTypeTerminal (expr, ec, silent);
1308 protected override ConstructorInfo ResolveArguments (EmitContext ec)
1312 return base.ResolveArguments (ec);
1320 public class Attributes {
1321 public ArrayList Attrs;
1323 public Attributes (Attribute a)
1325 Attrs = new ArrayList ();
1329 public Attributes (ArrayList attrs)
1334 public void AddAttributes (ArrayList attrs)
1336 Attrs.AddRange (attrs);
1340 /// Checks whether attribute target is valid for the current element
1342 public bool CheckTargets (Attributable member)
1344 string[] valid_targets = member.ValidAttributeTargets;
1345 foreach (Attribute a in Attrs) {
1346 if (a.ExplicitTarget == null || a.ExplicitTarget == valid_targets [0]) {
1347 a.Target = member.AttributeTargets;
1351 // TODO: we can skip the first item
1352 if (((IList) valid_targets).Contains (a.ExplicitTarget)) {
1353 switch (a.ExplicitTarget) {
1354 case "return": a.Target = AttributeTargets.ReturnValue; continue;
1355 case "param": a.Target = AttributeTargets.Parameter; continue;
1356 case "field": a.Target = AttributeTargets.Field; continue;
1357 case "method": a.Target = AttributeTargets.Method; continue;
1358 case "property": a.Target = AttributeTargets.Property; continue;
1360 throw new InternalErrorException ("Unknown explicit target: " + a.ExplicitTarget);
1363 StringBuilder sb = new StringBuilder ();
1364 foreach (string s in valid_targets) {
1368 sb.Remove (sb.Length - 2, 2);
1369 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 ());
1375 public Attribute Search (Type t, EmitContext ec)
1377 foreach (Attribute a in Attrs) {
1378 if (a.ResolveType (ec) == t)
1385 /// Returns all attributes of type 't'. Use it when attribute is AllowMultiple = true
1387 public Attribute[] SearchMulti (Type t, EmitContext ec)
1389 ArrayList ar = null;
1391 foreach (Attribute a in Attrs) {
1392 if (a.ResolveType (ec) == t) {
1394 ar = new ArrayList ();
1399 return ar == null ? null : ar.ToArray (typeof (Attribute)) as Attribute[];
1402 public void Emit (EmitContext ec, Attributable ias)
1406 ListDictionary ld = new ListDictionary ();
1408 foreach (Attribute a in Attrs)
1409 a.Emit (ec, ias, ld);
1412 public bool Contains (Type t, EmitContext ec)
1414 return Search (t, ec) != null;
1419 /// Helper class for attribute verification routine.
1421 sealed class AttributeTester
1423 static PtrHashtable analyzed_types = new PtrHashtable ();
1424 static PtrHashtable analyzed_types_obsolete = new PtrHashtable ();
1425 static PtrHashtable analyzed_member_obsolete = new PtrHashtable ();
1426 static PtrHashtable analyzed_method_excluded = new PtrHashtable ();
1429 static PtrHashtable fixed_buffer_cache = new PtrHashtable ();
1432 static object TRUE = new object ();
1433 static object FALSE = new object ();
1435 private AttributeTester ()
1439 public enum Result {
1446 /// Returns true if parameters of two compared methods are CLS-Compliant.
1447 /// It tests differing only in ref or out, or in array rank.
1449 public static Result AreOverloadedMethodParamsClsCompliant (Type[] types_a, Type[] types_b)
1451 if (types_a == null || types_b == null)
1454 if (types_a.Length != types_b.Length)
1457 Result result = Result.Ok;
1458 for (int i = 0; i < types_b.Length; ++i) {
1459 Type aType = types_a [i];
1460 Type bType = types_b [i];
1462 if (aType.IsArray && bType.IsArray) {
1463 Type a_el_type = aType.GetElementType ();
1464 Type b_el_type = bType.GetElementType ();
1465 if (aType.GetArrayRank () != bType.GetArrayRank () && a_el_type == b_el_type) {
1466 result = Result.RefOutArrayError;
1470 if (a_el_type.IsArray || b_el_type.IsArray) {
1471 result = Result.ArrayArrayError;
1476 Type aBaseType = aType;
1477 bool is_either_ref_or_out = false;
1479 if (aType.IsByRef || aType.IsPointer) {
1480 aBaseType = aType.GetElementType ();
1481 is_either_ref_or_out = true;
1484 Type bBaseType = bType;
1485 if (bType.IsByRef || bType.IsPointer)
1487 bBaseType = bType.GetElementType ();
1488 is_either_ref_or_out = !is_either_ref_or_out;
1491 if (aBaseType != bBaseType)
1494 if (is_either_ref_or_out)
1495 result = Result.RefOutArrayError;
1501 /// Goes through all parameters and test if they are CLS-Compliant.
1503 public static bool AreParametersCompliant (Parameter[] fixedParameters, Location loc)
1505 if (fixedParameters == null)
1508 foreach (Parameter arg in fixedParameters) {
1509 if (!AttributeTester.IsClsCompliant (arg.ParameterType)) {
1510 Report.Error (3001, loc, "Argument type `{0}' is not CLS-compliant", arg.GetSignatureForError ());
1519 /// This method tests the CLS compliance of external types. It doesn't test type visibility.
1521 public static bool IsClsCompliant (Type type)
1526 object type_compliance = analyzed_types[type];
1527 if (type_compliance != null)
1528 return type_compliance == TRUE;
1530 if (type.IsPointer) {
1531 analyzed_types.Add (type, null);
1536 if (type.IsArray || type.IsByRef) {
1537 result = IsClsCompliant (TypeManager.GetElementType (type));
1539 result = AnalyzeTypeCompliance (type);
1541 analyzed_types.Add (type, result ? TRUE : FALSE);
1546 /// Returns IFixedBuffer implementation if field is fixed buffer else null.
1548 public static IFixedBuffer GetFixedBuffer (FieldInfo fi)
1550 FieldBase fb = TypeManager.GetField (fi);
1552 return fb as IFixedBuffer;
1556 object o = fixed_buffer_cache [fi];
1558 if (System.Attribute.GetCustomAttribute (fi, TypeManager.fixed_buffer_attr_type) == null) {
1559 fixed_buffer_cache.Add (fi, FALSE);
1563 IFixedBuffer iff = new FixedFieldExternal (fi);
1564 fixed_buffer_cache.Add (fi, iff);
1571 return (IFixedBuffer)o;
1577 public static void VerifyModulesClsCompliance ()
1579 Module[] modules = TypeManager.Modules;
1580 if (modules == null)
1583 // The first module is generated assembly
1584 for (int i = 1; i < modules.Length; ++i) {
1585 Module module = modules [i];
1586 if (!IsClsCompliant (module)) {
1587 Report.Error (3013, "Added modules must be marked with the CLSCompliant attribute to match the assembly", module.Name);
1593 public static Type GetImportedIgnoreCaseClsType (string name)
1595 foreach (Assembly a in TypeManager.GetAssemblies ()) {
1596 Type t = a.GetType (name, false, true);
1600 if (IsClsCompliant (t))
1606 static bool IsClsCompliant (ICustomAttributeProvider attribute_provider)
1608 object[] CompliantAttribute = attribute_provider.GetCustomAttributes (TypeManager.cls_compliant_attribute_type, false);
1609 if (CompliantAttribute.Length == 0)
1612 return ((CLSCompliantAttribute)CompliantAttribute[0]).IsCompliant;
1615 static bool AnalyzeTypeCompliance (Type type)
1617 DeclSpace ds = TypeManager.LookupDeclSpace (type);
1619 return ds.IsClsCompliaceRequired (ds.Parent);
1622 object[] CompliantAttribute = type.GetCustomAttributes (TypeManager.cls_compliant_attribute_type, false);
1623 if (CompliantAttribute.Length == 0)
1624 return IsClsCompliant (type.Assembly);
1626 return ((CLSCompliantAttribute)CompliantAttribute[0]).IsCompliant;
1630 /// Returns instance of ObsoleteAttribute when type is obsolete
1632 public static ObsoleteAttribute GetObsoleteAttribute (Type type)
1634 object type_obsolete = analyzed_types_obsolete [type];
1635 if (type_obsolete == FALSE)
1638 if (type_obsolete != null)
1639 return (ObsoleteAttribute)type_obsolete;
1641 ObsoleteAttribute result = null;
1642 if (type.IsByRef || type.IsArray || type.IsPointer) {
1643 result = GetObsoleteAttribute (TypeManager.GetElementType (type));
1645 DeclSpace type_ds = TypeManager.LookupDeclSpace (type);
1647 // Type is external, we can get attribute directly
1648 if (type_ds == null) {
1649 object[] attribute = type.GetCustomAttributes (TypeManager.obsolete_attribute_type, false);
1650 if (attribute.Length == 1)
1651 result = (ObsoleteAttribute)attribute [0];
1653 result = type_ds.GetObsoleteAttribute (type_ds);
1657 analyzed_types_obsolete.Add (type, result == null ? FALSE : result);
1662 /// Returns instance of ObsoleteAttribute when method is obsolete
1664 public static ObsoleteAttribute GetMethodObsoleteAttribute (MethodBase mb)
1666 IMethodData mc = TypeManager.GetMethod (mb);
1668 return mc.GetObsoleteAttribute ();
1670 // compiler generated methods are not registered by AddMethod
1671 if (mb.DeclaringType is TypeBuilder)
1674 PropertyInfo pi = PropertyExpr.AccessorTable [mb] as PropertyInfo;
1676 return GetMemberObsoleteAttribute (pi);
1678 return GetMemberObsoleteAttribute (mb);
1682 /// Returns instance of ObsoleteAttribute when member is obsolete
1684 public static ObsoleteAttribute GetMemberObsoleteAttribute (MemberInfo mi)
1686 object type_obsolete = analyzed_member_obsolete [mi];
1687 if (type_obsolete == FALSE)
1690 if (type_obsolete != null)
1691 return (ObsoleteAttribute)type_obsolete;
1693 ObsoleteAttribute oa = System.Attribute.GetCustomAttribute (mi, TypeManager.obsolete_attribute_type, false) as ObsoleteAttribute;
1694 analyzed_member_obsolete.Add (mi, oa == null ? FALSE : oa);
1699 /// Common method for Obsolete error/warning reporting.
1701 public static void Report_ObsoleteMessage (ObsoleteAttribute oa, string member, Location loc)
1704 Report.Error (619, loc, "`{0}' is obsolete: `{1}'", member, oa.Message);
1708 if (oa.Message == null) {
1709 Report.Warning (612, loc, "`{0}' is obsolete", member);
1712 if (RootContext.WarningLevel >= 2)
1713 Report.Warning (618, loc, "`{0}' is obsolete: `{1}'", member, oa.Message);
1716 public static bool IsConditionalMethodExcluded (MethodBase mb)
1718 object excluded = analyzed_method_excluded [mb];
1719 if (excluded != null)
1720 return excluded == TRUE ? true : false;
1722 ConditionalAttribute[] attrs = mb.GetCustomAttributes (TypeManager.conditional_attribute_type, true) as ConditionalAttribute[];
1723 if (attrs.Length == 0) {
1724 analyzed_method_excluded.Add (mb, FALSE);
1728 foreach (ConditionalAttribute a in attrs) {
1729 if (RootContext.AllDefines.Contains (a.ConditionString)) {
1730 analyzed_method_excluded.Add (mb, FALSE);
1734 analyzed_method_excluded.Add (mb, TRUE);
1739 /// Analyzes class whether it has attribute which has ConditionalAttribute
1740 /// and its condition is not defined.
1742 public static bool IsAttributeExcluded (Type type)
1747 Class class_decl = TypeManager.LookupDeclSpace (type) as Class;
1749 // TODO: add caching
1750 // TODO: merge all Type bases attribute caching to one cache to save memory
1751 if (class_decl == null) {
1752 object[] attributes = type.GetCustomAttributes (TypeManager.conditional_attribute_type, false);
1753 foreach (ConditionalAttribute ca in attributes) {
1754 if (RootContext.AllDefines.Contains (ca.ConditionString))
1757 return attributes.Length > 0;
1760 return class_decl.IsExcluded ();