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 IsClsComplianceRequired (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 readonly bool nameEscaped;
90 static AttributeUsageAttribute DefaultUsageAttribute = new AttributeUsageAttribute (AttributeTargets.All);
91 static Assembly orig_sec_assembly;
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, bool nameEscaped)
104 LeftExpr = left_expr;
105 Identifier = identifier;
106 Name = LeftExpr == null ? identifier : LeftExpr + "." + identifier;
109 ExplicitTarget = target;
110 this.nameEscaped = nameEscaped;
113 void Error_InvalidNamedArgument (string name)
115 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",
119 void Error_InvalidNamedAgrumentType (string name)
121 Report.Error (655, Location, "`{0}' is not a valid named attribute argument because it is not a valid attribute parameter type", name);
124 static void Error_AttributeArgumentNotValid (string extra, Location loc)
126 Report.Error (182, loc,
127 "An attribute argument must be a constant expression, typeof " +
128 "expression or array creation expression" + extra);
131 static void Error_AttributeArgumentNotValid (Location loc)
133 Error_AttributeArgumentNotValid ("", loc);
136 static void Error_TypeParameterInAttribute (Location loc)
139 -202, loc, "Can not use a type parameter in an attribute");
143 /// This is rather hack. We report many emit attribute error with same error to be compatible with
144 /// csc. But because csc has to report them this way because error came from ilasm we needn't.
146 public void Error_AttributeEmitError (string inner)
148 Report.Error (647, Location, "Error during emitting `{0}' attribute. The reason is `{1}'", TypeManager.CSharpName (Type), inner);
151 public void Error_InvalidSecurityParent ()
153 Error_AttributeEmitError ("it is attached to invalid parent");
156 protected virtual FullNamedExpression ResolveAsTypeTerminal (Expression expr, EmitContext ec, bool silent)
158 return expr.ResolveAsTypeTerminal (ec, silent);
161 protected virtual FullNamedExpression ResolveAsTypeStep (Expression expr, EmitContext ec, bool silent)
163 return expr.ResolveAsTypeStep (ec, silent);
166 Type ResolvePossibleAttributeType (EmitContext ec, string name, bool silent, ref bool is_attr)
168 FullNamedExpression fn;
169 if (LeftExpr == null) {
170 fn = ResolveAsTypeTerminal (new SimpleName (name, Location), ec, silent);
172 fn = ResolveAsTypeStep (LeftExpr, ec, silent);
175 fn = new MemberAccess (fn, name, Location).ResolveAsTypeTerminal (ec, silent);
178 TypeExpr te = fn as TypeExpr;
183 if (t.IsSubclassOf (TypeManager.attribute_type)) {
185 } else if (!silent) {
186 Report.SymbolRelatedToPreviousError (t);
187 Report.Error (616, Location, "`{0}': is not an attribute class", TypeManager.CSharpName (t));
193 /// Tries to resolve the type of the attribute. Flags an error if it can't, and complain is true.
195 void ResolveAttributeType (EmitContext ec)
197 bool t1_is_attr = false;
198 Type t1 = ResolvePossibleAttributeType (ec, Identifier, true, ref t1_is_attr);
199 // FIXME: Shouldn't do this for quoted attributes: [@A]
200 bool t2_is_attr = false;
201 Type t2 = ResolvePossibleAttributeType (ec, Identifier + "Attribute", true, ref t2_is_attr);
203 if (t1_is_attr && t2_is_attr && !nameEscaped) {
204 Report.Error (1614, Location, "`{0}' is ambiguous between `{0}' and `{0}Attribute'. Use either `@{0}' or `{0}Attribute'", GetSignatureForError ());
205 resolve_error = true;
218 if (t1 == null && t2 == null)
219 ResolvePossibleAttributeType (ec, Identifier, false, ref t1_is_attr);
221 ResolvePossibleAttributeType (ec, Identifier, false, ref t1_is_attr);
223 ResolvePossibleAttributeType (ec, Identifier + "Attribute", false, ref t2_is_attr);
224 resolve_error = true;
227 public virtual Type ResolveType (EmitContext ec)
229 if (Type == null && !resolve_error)
230 ResolveAttributeType (ec);
234 public string GetSignatureForError ()
236 return LeftExpr == null ? Identifier : LeftExpr.GetSignatureForError () + "." + Identifier;
240 // Given an expression, if the expression is a valid attribute-argument-expression
241 // returns an object that can be used to encode it, or null on failure.
243 public static bool GetAttributeArgumentExpression (Expression e, Location loc, Type arg_type, out object result)
245 if (e is EnumConstant) {
246 if (RootContext.StdLib)
247 result = ((EnumConstant)e).GetValueAsEnumType ();
249 result = ((EnumConstant)e).GetValue ();
254 Constant constant = e as Constant;
255 if (constant != null) {
256 if (e.Type != arg_type) {
257 constant = Const.ChangeType (loc, constant, arg_type);
258 if (constant == null) {
260 Error_AttributeArgumentNotValid (loc);
264 result = constant.GetValue ();
266 } else if (e is TypeOf) {
267 result = ((TypeOf) e).TypeArg;
269 } else if (e is ArrayCreation){
270 result = ((ArrayCreation) e).EncodeAsAttribute ();
273 } else if (e is EmptyCast) {
274 Expression child = ((EmptyCast)e).Child;
275 return GetAttributeArgumentExpression (child, loc, child.Type, out result);
279 Error_AttributeArgumentNotValid (loc);
283 bool IsValidArgumentType (Type t)
285 return TypeManager.IsPrimitiveType (t) ||
286 (t.IsArray && TypeManager.IsPrimitiveType (t.GetElementType ())) ||
287 TypeManager.IsEnumType (t) ||
288 t == TypeManager.string_type ||
289 t == TypeManager.object_type ||
290 t == TypeManager.type_type;
293 // Cache for parameter-less attributes
294 static PtrHashtable att_cache = new PtrHashtable ();
296 public CustomAttributeBuilder Resolve (EmitContext ec)
301 resolve_error = true;
304 ResolveAttributeType (ec);
309 if (Type.IsAbstract) {
310 Report.Error (653, Location, "Cannot apply attribute class `{0}' because it is abstract", GetSignatureForError ());
314 if (Arguments == null) {
315 object o = att_cache [Type];
317 resolve_error = false;
318 return (CustomAttributeBuilder)o;
322 ConstructorInfo ctor = ResolveArguments (ec);
326 CustomAttributeBuilder cb;
329 if (prop_info_arr != null || field_info_arr != null) {
330 cb = new CustomAttributeBuilder (
332 prop_info_arr, prop_values_arr,
333 field_info_arr, field_values_arr);
335 cb = new CustomAttributeBuilder (
338 if (pos_values.Length == 0)
339 att_cache.Add (Type, cb);
343 Error_AttributeArgumentNotValid (Location);
347 resolve_error = false;
351 protected virtual ConstructorInfo ResolveArguments (EmitContext ec)
353 // Now we extract the positional and named arguments
355 ArrayList pos_args = null;
356 ArrayList named_args = null;
357 int pos_arg_count = 0;
358 int named_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];
366 named_arg_count = named_args.Count;
370 pos_values = new object [pos_arg_count];
373 // First process positional arguments
377 for (i = 0; i < pos_arg_count; i++) {
378 Argument a = (Argument) pos_args [i];
381 if (!a.Resolve (ec, Location))
387 if (!GetAttributeArgumentExpression (e, Location, a.Type, out val))
390 pos_values [i] = val;
392 if (i == 0 && Type == TypeManager.attribute_usage_type && (int)val == 0) {
393 Report.Error (591, Location, "Invalid value for argument to 'System.AttributeUsage' attribute");
399 // Now process named arguments
402 ArrayList field_infos = null;
403 ArrayList prop_infos = null;
404 ArrayList field_values = null;
405 ArrayList prop_values = null;
406 Hashtable seen_names = null;
408 if (named_arg_count > 0) {
409 field_infos = new ArrayList ();
410 prop_infos = new ArrayList ();
411 field_values = new ArrayList ();
412 prop_values = new ArrayList ();
414 seen_names = new Hashtable();
417 for (i = 0; i < named_arg_count; i++) {
418 DictionaryEntry de = (DictionaryEntry) named_args [i];
419 string member_name = (string) de.Key;
420 Argument a = (Argument) de.Value;
423 if (seen_names.Contains(member_name)) {
424 Report.Error(643, Location, "'" + member_name + "' duplicate named attribute argument");
427 seen_names.Add(member_name, 1);
429 if (!a.Resolve (ec, Location))
432 Expression member = Expression.MemberLookup (
433 ec, Type, member_name,
434 MemberTypes.Field | MemberTypes.Property,
435 BindingFlags.Public | BindingFlags.Instance,
438 if (member == null) {
439 member = Expression.MemberLookup (ec, Type, member_name,
440 MemberTypes.Field | MemberTypes.Property, BindingFlags.NonPublic | BindingFlags.Instance,
443 if (member != null) {
444 Expression.ErrorIsInaccesible (Location, member.GetSignatureForError ());
450 Report.Error (117, Location, "`{0}' does not contain a definition for `{1}'",
455 if (!(member is PropertyExpr || member is FieldExpr)) {
456 Error_InvalidNamedArgument (member_name);
461 if (e is TypeParameterExpr){
462 Error_TypeParameterInAttribute (Location);
466 if (member is PropertyExpr) {
467 PropertyExpr pe = (PropertyExpr) member;
468 PropertyInfo pi = pe.PropertyInfo;
470 if (!pi.CanWrite || !pi.CanRead) {
471 Report.SymbolRelatedToPreviousError (pi);
472 Error_InvalidNamedArgument (member_name);
476 if (!IsValidArgumentType (pi.PropertyType)) {
477 Report.SymbolRelatedToPreviousError (pi);
478 Error_InvalidNamedAgrumentType (member_name);
483 if (!GetAttributeArgumentExpression (e, Location, pi.PropertyType, out value))
486 prop_values.Add (value);
489 } else if (member is FieldExpr) {
490 FieldExpr fe = (FieldExpr) member;
491 FieldInfo fi = fe.FieldInfo;
494 Error_InvalidNamedArgument (member_name);
498 if (!IsValidArgumentType (fi.FieldType)) {
499 Report.SymbolRelatedToPreviousError (fi);
500 Error_InvalidNamedAgrumentType (member_name);
505 if (!GetAttributeArgumentExpression (e, Location, fi.FieldType, out value))
508 field_values.Add (value);
510 field_infos.Add (fi);
514 Expression mg = Expression.MemberLookup (
515 ec, Type, ".ctor", MemberTypes.Constructor,
516 BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly,
519 MethodBase constructor = Invocation.OverloadResolve (
520 ec, (MethodGroupExpr) mg, pos_args, false, Location);
522 if (constructor == null) {
527 // Here we do the checks which should be done by corlib or by runtime.
528 // However Zoltan doesn't like it and every Mono compiler has to do it again.
530 if (Type == TypeManager.guid_attr_type) {
532 new Guid ((string)pos_values [0]);
534 catch (Exception e) {
535 Error_AttributeEmitError (e.Message);
539 // if (Type == TypeManager.methodimpl_attr_type &&
540 // pos_values.Length == 1 && ((Argument)pos_args [0]).Type == TypeManager.short_type &&
541 // !System.Enum.IsDefined (TypeManager.method_impl_options, pos_values [0])) {
542 // Error_AttributeEmitError ("Incorrect argument value.");
546 // Now we perform some checks on the positional args as they
547 // cannot be null for a constructor which expects a parameter
551 ParameterData pd = TypeManager.GetParameterData (constructor);
553 int last_real_param = pd.Count;
555 // When the params is not filled we need to put one
556 if (last_real_param > pos_arg_count) {
557 object [] new_pos_values = new object [pos_arg_count + 1];
558 pos_values.CopyTo (new_pos_values, 0);
559 new_pos_values [pos_arg_count] = new object [] {} ;
560 pos_values = new_pos_values;
565 for (int j = 0; j < pos_arg_count; ++j) {
566 Argument a = (Argument) pos_args [j];
568 if (a.Expr is NullLiteral && pd.ParameterType (j) == TypeManager.object_type) {
569 Error_AttributeArgumentNotValid (Location);
573 object value = pos_values [j];
574 if (value != null && a.Type != value.GetType () && TypeManager.IsPrimitiveType (a.Type)) {
576 pos_values [j] = TypeManager.ChangeType (value, a.Type, out fail);
578 // TODO: Can failed ?
579 throw new NotImplementedException ();
583 if (j < last_real_param)
586 if (j == last_real_param) {
587 object [] array = new object [pos_arg_count - last_real_param];
588 array [0] = pos_values [j];
589 pos_values [j] = array;
593 object [] params_array = (object []) pos_values [last_real_param];
594 params_array [j - last_real_param] = pos_values [j];
597 // Adjust the size of the pos_values if it had params
598 if (last_real_param != pos_arg_count) {
599 object [] new_pos_values = new object [last_real_param + 1];
600 Array.Copy (pos_values, new_pos_values, last_real_param + 1);
601 pos_values = new_pos_values;
604 if (named_arg_count > 0) {
605 prop_info_arr = new PropertyInfo [prop_infos.Count];
606 field_info_arr = new FieldInfo [field_infos.Count];
607 field_values_arr = new object [field_values.Count];
608 prop_values_arr = new object [prop_values.Count];
610 field_infos.CopyTo (field_info_arr, 0);
611 field_values.CopyTo (field_values_arr, 0);
613 prop_values.CopyTo (prop_values_arr, 0);
614 prop_infos.CopyTo (prop_info_arr, 0);
617 return (ConstructorInfo) constructor;
621 /// Get a string containing a list of valid targets for the attribute 'attr'
623 public string GetValidTargets ()
625 StringBuilder sb = new StringBuilder ();
626 AttributeTargets targets = GetAttributeUsage (null).ValidOn;
628 if ((targets & AttributeTargets.Assembly) != 0)
629 sb.Append ("assembly, ");
631 if ((targets & AttributeTargets.Module) != 0)
632 sb.Append ("module, ");
634 if ((targets & AttributeTargets.Class) != 0)
635 sb.Append ("class, ");
637 if ((targets & AttributeTargets.Struct) != 0)
638 sb.Append ("struct, ");
640 if ((targets & AttributeTargets.Enum) != 0)
641 sb.Append ("enum, ");
643 if ((targets & AttributeTargets.Constructor) != 0)
644 sb.Append ("constructor, ");
646 if ((targets & AttributeTargets.Method) != 0)
647 sb.Append ("method, ");
649 if ((targets & AttributeTargets.Property) != 0)
650 sb.Append ("property, indexer, ");
652 if ((targets & AttributeTargets.Field) != 0)
653 sb.Append ("field, ");
655 if ((targets & AttributeTargets.Event) != 0)
656 sb.Append ("event, ");
658 if ((targets & AttributeTargets.Interface) != 0)
659 sb.Append ("interface, ");
661 if ((targets & AttributeTargets.Parameter) != 0)
662 sb.Append ("parameter, ");
664 if ((targets & AttributeTargets.Delegate) != 0)
665 sb.Append ("delegate, ");
667 if ((targets & AttributeTargets.ReturnValue) != 0)
668 sb.Append ("return, ");
670 if ((targets & AttributeTargets.GenericParameter) != 0)
671 sb.Append ("type parameter, ");
672 return sb.Remove (sb.Length - 2, 2).ToString ();
676 /// Returns AttributeUsage attribute for this type
678 AttributeUsageAttribute GetAttributeUsage (EmitContext ec)
680 AttributeUsageAttribute ua = usage_attr_cache [Type] as AttributeUsageAttribute;
684 Class attr_class = TypeManager.LookupClass (Type);
686 if (attr_class == null) {
687 object[] usage_attr = Type.GetCustomAttributes (TypeManager.attribute_usage_type, true);
688 ua = (AttributeUsageAttribute)usage_attr [0];
689 usage_attr_cache.Add (Type, ua);
693 Attribute a = attr_class.OptAttributes == null
695 : attr_class.OptAttributes.Search (TypeManager.attribute_usage_type, attr_class.EmitContext);
698 ? DefaultUsageAttribute
699 : a.GetAttributeUsageAttribute (attr_class.EmitContext);
701 usage_attr_cache.Add (Type, ua);
705 AttributeUsageAttribute GetAttributeUsageAttribute (EmitContext ec)
707 if (pos_values == null)
708 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
709 // But because a lot of attribute class code must be rewritten will be better to wait...
713 return DefaultUsageAttribute;
715 AttributeUsageAttribute usage_attribute = new AttributeUsageAttribute ((AttributeTargets)pos_values [0]);
717 object field = GetPropertyValue ("AllowMultiple");
719 usage_attribute.AllowMultiple = (bool)field;
721 field = GetPropertyValue ("Inherited");
723 usage_attribute.Inherited = (bool)field;
725 return usage_attribute;
729 /// Returns custom name of indexer
731 public string GetIndexerAttributeValue (EmitContext ec)
733 if (pos_values == null)
734 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
735 // But because a lot of attribute class code must be rewritten will be better to wait...
741 return pos_values [0] as string;
745 /// Returns condition of ConditionalAttribute
747 public string GetConditionalAttributeValue (EmitContext ec)
749 if (pos_values == null)
750 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
751 // But because a lot of attribute class code must be rewritten will be better to wait...
757 return (string)pos_values [0];
761 /// Creates the instance of ObsoleteAttribute from this attribute instance
763 public ObsoleteAttribute GetObsoleteAttribute (EmitContext ec)
765 if (pos_values == null)
766 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
767 // But because a lot of attribute class code must be rewritten will be better to wait...
773 if (pos_values == null || pos_values.Length == 0)
774 return new ObsoleteAttribute ();
776 if (pos_values.Length == 1)
777 return new ObsoleteAttribute ((string)pos_values [0]);
779 return new ObsoleteAttribute ((string)pos_values [0], (bool)pos_values [1]);
783 /// Returns value of CLSCompliantAttribute contructor parameter but because the method can be called
784 /// before ApplyAttribute. We need to resolve the arguments.
785 /// This situation occurs when class deps is differs from Emit order.
787 public bool GetClsCompliantAttributeValue (EmitContext ec)
789 if (pos_values == null)
790 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
791 // But because a lot of attribute class code must be rewritten will be better to wait...
797 return (bool)pos_values [0];
801 /// Tests permitted SecurityAction for assembly or other types
803 public bool CheckSecurityActionValidity (bool for_assembly)
805 SecurityAction action = GetSecurityActionValue ();
808 case SecurityAction.Demand:
809 case SecurityAction.Assert:
810 case SecurityAction.Deny:
811 case SecurityAction.PermitOnly:
812 case SecurityAction.LinkDemand:
813 case SecurityAction.InheritanceDemand:
818 case SecurityAction.RequestMinimum:
819 case SecurityAction.RequestOptional:
820 case SecurityAction.RequestRefuse:
826 Error_AttributeEmitError ("SecurityAction is out of range X");
830 Error_AttributeEmitError (String.Concat ("SecurityAction '", action, "' is not valid for this declaration"));
834 System.Security.Permissions.SecurityAction GetSecurityActionValue ()
836 return (SecurityAction)pos_values [0];
840 /// Creates instance of SecurityAttribute class and add result of CreatePermission method to permission table.
842 /// <returns></returns>
843 public void ExtractSecurityPermissionSet (ListDictionary permissions)
845 Type orig_assembly_type = null;
847 if (TypeManager.LookupDeclSpace (Type) != null) {
848 if (!RootContext.StdLib) {
849 orig_assembly_type = Type.GetType (Type.FullName);
851 string orig_version_path = Environment.GetEnvironmentVariable ("__SECURITY_BOOTSTRAP_DB");
852 if (orig_version_path == null) {
853 Error_AttributeEmitError ("security custom attributes can not be referenced from defining assembly");
857 if (orig_sec_assembly == null) {
858 string file = Path.Combine (orig_version_path, Driver.OutputFile);
859 orig_sec_assembly = Assembly.LoadFile (file);
862 orig_assembly_type = orig_sec_assembly.GetType (Type.FullName, true);
863 if (orig_assembly_type == null) {
864 Report.Warning (-112, 1, Location, "Self-referenced security attribute `{0}' was not found in previous version of assembly");
870 SecurityAttribute sa;
871 // For all non-selfreferencing security attributes we can avoid all hacks
872 if (orig_assembly_type == null) {
873 sa = (SecurityAttribute) Activator.CreateInstance (Type, pos_values);
875 if (prop_info_arr != null) {
876 for (int i = 0; i < prop_info_arr.Length; ++i) {
877 PropertyInfo pi = prop_info_arr [i];
878 pi.SetValue (sa, prop_values_arr [i], null);
882 // HACK: All security attributes have same ctor syntax
883 sa = (SecurityAttribute) Activator.CreateInstance (orig_assembly_type, new object[] { GetSecurityActionValue () } );
885 // All types are from newly created assembly but for invocation with old one we need to convert them
886 if (prop_info_arr != null) {
887 for (int i = 0; i < prop_info_arr.Length; ++i) {
888 PropertyInfo emited_pi = prop_info_arr [i];
889 PropertyInfo pi = orig_assembly_type.GetProperty (emited_pi.Name, emited_pi.PropertyType);
891 object old_instance = pi.PropertyType.IsEnum ?
892 System.Enum.ToObject (pi.PropertyType, prop_values_arr [i]) :
895 pi.SetValue (sa, old_instance, null);
901 perm = sa.CreatePermission ();
902 SecurityAction action = GetSecurityActionValue ();
904 // IS is correct because for corlib we are using an instance from old corlib
905 if (!(perm is System.Security.CodeAccessPermission)) {
907 case SecurityAction.Demand:
908 action = (SecurityAction)13;
910 case SecurityAction.LinkDemand:
911 action = (SecurityAction)14;
913 case SecurityAction.InheritanceDemand:
914 action = (SecurityAction)15;
919 PermissionSet ps = (PermissionSet)permissions [action];
921 if (sa is PermissionSetAttribute)
922 ps = new PermissionSet (sa.Unrestricted ? PermissionState.Unrestricted : PermissionState.None);
924 ps = new PermissionSet (PermissionState.None);
926 permissions.Add (action, ps);
927 } else if (!ps.IsUnrestricted () && (sa is PermissionSetAttribute) && sa.Unrestricted) {
928 ps = ps.Union (new PermissionSet (PermissionState.Unrestricted));
929 permissions [action] = ps;
931 ps.AddPermission (perm);
934 object GetValue (object value)
936 if (value is EnumConstant)
937 return ((EnumConstant) value).GetValue ();
942 object GetPropertyValue (string name)
944 if (prop_info_arr == null)
947 for (int i = 0; i < prop_info_arr.Length; ++i) {
948 if (prop_info_arr [i].Name == name)
949 return prop_values_arr [i];
955 object GetFieldValue (string name)
958 if (field_info_arr == null)
961 foreach (FieldInfo fi in field_info_arr) {
963 return GetValue (field_values_arr [i]);
969 public UnmanagedMarshal GetMarshal (Attributable attr)
971 UnmanagedType UnmanagedType = (UnmanagedType)System.Enum.Parse (typeof (UnmanagedType), pos_values [0].ToString ());
973 object value = GetFieldValue ("SizeParamIndex");
974 if (value != null && UnmanagedType != UnmanagedType.LPArray) {
975 Error_AttributeEmitError ("SizeParamIndex field is not valid for the specified unmanaged type");
979 object o = GetFieldValue ("ArraySubType");
980 UnmanagedType array_sub_type = o == null ? UnmanagedType.I4 : (UnmanagedType) o;
982 switch (UnmanagedType) {
983 case UnmanagedType.CustomMarshaler: {
984 MethodInfo define_custom = typeof (UnmanagedMarshal).GetMethod ("DefineCustom",
985 BindingFlags.Static | BindingFlags.Public);
986 if (define_custom == null) {
987 Report.RuntimeMissingSupport (Location, "set marshal info");
991 object [] args = new object [4];
992 args [0] = GetFieldValue ("MarshalTypeRef");
993 args [1] = GetFieldValue ("MarshalCookie");
994 args [2] = GetFieldValue ("MarshalType");
995 args [3] = Guid.Empty;
996 return (UnmanagedMarshal) define_custom.Invoke (null, args);
998 case UnmanagedType.LPArray: {
999 object size_const = GetFieldValue ("SizeConst");
1000 object size_param_index = GetFieldValue ("SizeParamIndex");
1002 if ((size_const != null) || (size_param_index != null)) {
1003 MethodInfo define_array = typeof (UnmanagedMarshal).GetMethod ("DefineLPArrayInternal", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
1004 if (define_array == null) {
1005 Report.RuntimeMissingSupport (Location, "set marshal info");
1009 object [] args = new object [3];
1010 args [0] = array_sub_type;
1011 args [1] = size_const == null ? -1 : size_const;
1012 args [2] = size_param_index == null ? -1 : size_param_index;
1013 return (UnmanagedMarshal) define_array.Invoke (null, args);
1016 return UnmanagedMarshal.DefineLPArray (array_sub_type);
1018 case UnmanagedType.SafeArray:
1019 return UnmanagedMarshal.DefineSafeArray (array_sub_type);
1021 case UnmanagedType.ByValArray:
1022 FieldMember fm = attr as FieldMember;
1024 Error_AttributeEmitError ("Specified unmanaged type is only valid on fields");
1027 return UnmanagedMarshal.DefineByValArray ((int) GetFieldValue ("SizeConst"));
1029 case UnmanagedType.ByValTStr:
1030 return UnmanagedMarshal.DefineByValTStr ((int) GetFieldValue ("SizeConst"));
1033 return UnmanagedMarshal.DefineUnmanagedMarshal (UnmanagedType);
1037 public CharSet GetCharSetValue ()
1039 return (CharSet)System.Enum.Parse (typeof (CharSet), pos_values [0].ToString ());
1042 public MethodImplOptions GetMethodImplOptions ()
1044 return (MethodImplOptions)System.Enum.Parse (typeof (MethodImplOptions), pos_values [0].ToString ());
1047 public LayoutKind GetLayoutKindValue ()
1049 return (LayoutKind)System.Enum.Parse (typeof (LayoutKind), pos_values [0].ToString ());
1053 /// Emit attribute for Attributable symbol
1055 public void Emit (EmitContext ec, Attributable ias, ListDictionary emitted_attr)
1057 CustomAttributeBuilder cb = Resolve (ec);
1061 AttributeUsageAttribute usage_attr = GetAttributeUsage (ec);
1062 if ((usage_attr.ValidOn & Target) == 0) {
1063 Report.Error (592, Location, "Attribute `{0}' is not valid on this declaration type. It is valid on `{1}' declarations only",
1064 GetSignatureForError (), GetValidTargets ());
1069 ias.ApplyAttributeBuilder (this, cb);
1071 catch (Exception e) {
1072 Error_AttributeEmitError (e.Message);
1076 if (!usage_attr.AllowMultiple) {
1077 ArrayList emitted_targets = (ArrayList)emitted_attr [Type];
1078 if (emitted_targets == null) {
1079 emitted_targets = new ArrayList ();
1080 emitted_attr.Add (Type, emitted_targets);
1081 } else if (emitted_targets.Contains (Target)) {
1082 Report.Error (579, Location, "Duplicate `{0}' attribute", GetSignatureForError ());
1085 emitted_targets.Add (Target);
1088 if (!RootContext.VerifyClsCompliance)
1091 // Here we are testing attribute arguments for array usage (error 3016)
1092 if (ias.IsClsComplianceRequired (ec.DeclSpace)) {
1093 if (Arguments == null)
1096 ArrayList pos_args = (ArrayList) Arguments [0];
1097 if (pos_args != null) {
1098 foreach (Argument arg in pos_args) {
1099 // Type is undefined (was error 246)
1100 if (arg.Type == null)
1103 if (arg.Type.IsArray) {
1104 Report.Error (3016, Location, "Arrays as attribute arguments are not CLS-compliant");
1110 if (Arguments.Count < 2)
1113 ArrayList named_args = (ArrayList) Arguments [1];
1114 foreach (DictionaryEntry de in named_args) {
1115 Argument arg = (Argument) de.Value;
1117 // Type is undefined (was error 246)
1118 if (arg.Type == null)
1121 if (arg.Type.IsArray) {
1122 Report.Error (3016, Location, "Arrays as attribute arguments are not CLS-compliant");
1129 public MethodBuilder DefinePInvokeMethod (EmitContext ec, TypeBuilder builder, string name,
1130 MethodAttributes flags, Type ret_type, Type [] param_types)
1132 if (pos_values == null)
1133 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
1134 // But because a lot of attribute class code must be rewritten will be better to wait...
1140 string dll_name = (string)pos_values [0];
1143 CallingConvention cc = CallingConvention.Winapi;
1144 CharSet charset = CodeGen.Module.DefaultCharSet;
1145 bool preserve_sig = true;
1146 string entry_point = name;
1147 bool best_fit_mapping = false;
1148 bool throw_on_unmappable = false;
1149 bool exact_spelling = false;
1150 bool set_last_error = false;
1152 bool best_fit_mapping_set = false;
1153 bool throw_on_unmappable_set = false;
1154 bool exact_spelling_set = false;
1155 bool set_last_error_set = false;
1157 MethodInfo set_best_fit = null;
1158 MethodInfo set_throw_on = null;
1159 MethodInfo set_exact_spelling = null;
1160 MethodInfo set_set_last_error = null;
1162 if (field_info_arr != null) {
1164 for (int i = 0; i < field_info_arr.Length; i++) {
1165 switch (field_info_arr [i].Name) {
1166 case "BestFitMapping":
1167 best_fit_mapping = (bool) field_values_arr [i];
1168 best_fit_mapping_set = true;
1170 case "CallingConvention":
1171 cc = (CallingConvention) field_values_arr [i];
1174 charset = (CharSet) field_values_arr [i];
1177 entry_point = (string) field_values_arr [i];
1179 case "ExactSpelling":
1180 exact_spelling = (bool) field_values_arr [i];
1181 exact_spelling_set = true;
1184 preserve_sig = (bool) field_values_arr [i];
1186 case "SetLastError":
1187 set_last_error = (bool) field_values_arr [i];
1188 set_last_error_set = true;
1190 case "ThrowOnUnmappableChar":
1191 throw_on_unmappable = (bool) field_values_arr [i];
1192 throw_on_unmappable_set = true;
1195 throw new InternalErrorException (field_info_arr [i].ToString ());
1200 if (throw_on_unmappable_set || best_fit_mapping_set || exact_spelling_set || set_last_error_set) {
1201 set_best_fit = typeof (MethodBuilder).GetMethod ("set_BestFitMapping", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
1202 set_throw_on = typeof (MethodBuilder).GetMethod ("set_ThrowOnUnmappableChar", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
1203 set_exact_spelling = typeof (MethodBuilder).GetMethod ("set_ExactSpelling", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
1204 set_set_last_error = typeof (MethodBuilder).GetMethod ("set_SetLastError", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
1206 if ((set_best_fit == null) || (set_throw_on == null) || (set_exact_spelling == null) || (set_set_last_error == null)) {
1207 Report.Error (-1, Location,
1208 "The ThrowOnUnmappableChar, BestFitMapping, SetLastError, and ExactSpelling attributes can only be emitted when running on the mono runtime.");
1214 MethodBuilder mb = builder.DefinePInvokeMethod (
1215 name, dll_name, entry_point, flags | MethodAttributes.HideBySig | MethodAttributes.PinvokeImpl,
1216 CallingConventions.Standard, ret_type, param_types, cc, charset);
1219 mb.SetImplementationFlags (MethodImplAttributes.PreserveSig);
1221 if (throw_on_unmappable_set)
1222 set_throw_on.Invoke (mb, 0, null, new object [] { throw_on_unmappable }, null);
1223 if (best_fit_mapping_set)
1224 set_best_fit.Invoke (mb, 0, null, new object [] { best_fit_mapping }, null);
1225 if (exact_spelling_set)
1226 set_exact_spelling.Invoke (mb, 0, null, new object [] { exact_spelling }, null);
1227 if (set_last_error_set)
1228 set_set_last_error.Invoke (mb, 0, null, new object [] { set_last_error }, null);
1232 catch (ArgumentException e) {
1233 Error_AttributeEmitError (e.Message);
1238 private Expression GetValue ()
1240 if ((Arguments == null) || (Arguments.Count < 1))
1242 ArrayList al = (ArrayList) Arguments [0];
1243 if ((al == null) || (al.Count < 1))
1245 Argument arg = (Argument) al [0];
1246 if ((arg == null) || (arg.Expr == null))
1251 public string GetString ()
1253 Expression e = GetValue ();
1254 if (e is StringLiteral)
1255 return (e as StringLiteral).Value;
1259 public bool GetBoolean ()
1261 Expression e = GetValue ();
1262 if (e is BoolLiteral)
1263 return (e as BoolLiteral).Value;
1270 /// For global attributes (assembly, module) we need special handling.
1271 /// Attributes can be located in the several files
1273 public class GlobalAttribute: Attribute
1275 public readonly NamespaceEntry ns;
1277 public GlobalAttribute (TypeContainer container, string target,
1278 Expression left_expr, string identifier, ArrayList args, Location loc, bool nameEscaped):
1279 base (target, left_expr, identifier, args, loc, nameEscaped)
1281 ns = container.NamespaceEntry;
1286 // RootContext.Tree.Types has a single NamespaceEntry which gets overwritten
1287 // each time a new file is parsed. However, we need to use the NamespaceEntry
1288 // in effect where the attribute was used. Since code elsewhere cannot assume
1289 // that the NamespaceEntry is right, just overwrite it.
1291 // Precondition: RootContext.Tree.Types == null
1293 if (RootContext.Tree.Types.NamespaceEntry != null)
1294 throw new InternalErrorException (Location + " non-null NamespaceEntry");
1296 RootContext.Tree.Types.NamespaceEntry = ns;
1301 RootContext.Tree.Types.NamespaceEntry = null;
1304 protected override FullNamedExpression ResolveAsTypeStep (Expression expr, EmitContext ec, bool silent)
1308 return base.ResolveAsTypeStep (expr, ec, silent);
1316 protected override FullNamedExpression ResolveAsTypeTerminal (Expression expr, EmitContext ec, bool silent)
1320 return base.ResolveAsTypeTerminal (expr, ec, silent);
1327 protected override ConstructorInfo ResolveArguments (EmitContext ec)
1331 return base.ResolveArguments (ec);
1339 public class Attributes {
1340 public ArrayList Attrs;
1342 public Attributes (Attribute a)
1344 Attrs = new ArrayList ();
1348 public Attributes (ArrayList attrs)
1353 public void AddAttributes (ArrayList attrs)
1355 Attrs.AddRange (attrs);
1359 /// Checks whether attribute target is valid for the current element
1361 public bool CheckTargets (Attributable member)
1363 string[] valid_targets = member.ValidAttributeTargets;
1364 foreach (Attribute a in Attrs) {
1365 if (a.ExplicitTarget == null || a.ExplicitTarget == valid_targets [0]) {
1366 a.Target = member.AttributeTargets;
1370 // TODO: we can skip the first item
1371 if (((IList) valid_targets).Contains (a.ExplicitTarget)) {
1372 switch (a.ExplicitTarget) {
1373 case "return": a.Target = AttributeTargets.ReturnValue; continue;
1374 case "param": a.Target = AttributeTargets.Parameter; continue;
1375 case "field": a.Target = AttributeTargets.Field; continue;
1376 case "method": a.Target = AttributeTargets.Method; continue;
1377 case "property": a.Target = AttributeTargets.Property; continue;
1379 throw new InternalErrorException ("Unknown explicit target: " + a.ExplicitTarget);
1382 StringBuilder sb = new StringBuilder ();
1383 foreach (string s in valid_targets) {
1387 sb.Remove (sb.Length - 2, 2);
1388 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 ());
1394 public Attribute Search (Type t, EmitContext ec)
1396 foreach (Attribute a in Attrs) {
1397 if (a.ResolveType (ec) == t)
1404 /// Returns all attributes of type 't'. Use it when attribute is AllowMultiple = true
1406 public Attribute[] SearchMulti (Type t, EmitContext ec)
1408 ArrayList ar = null;
1410 foreach (Attribute a in Attrs) {
1411 if (a.ResolveType (ec) == t) {
1413 ar = new ArrayList ();
1418 return ar == null ? null : ar.ToArray (typeof (Attribute)) as Attribute[];
1421 public void Emit (EmitContext ec, Attributable ias)
1425 ListDictionary ld = new ListDictionary ();
1427 foreach (Attribute a in Attrs)
1428 a.Emit (ec, ias, ld);
1431 public bool Contains (Type t, EmitContext ec)
1433 return Search (t, ec) != null;
1438 /// Helper class for attribute verification routine.
1440 sealed class AttributeTester
1442 static PtrHashtable analyzed_types = new PtrHashtable ();
1443 static PtrHashtable analyzed_types_obsolete = new PtrHashtable ();
1444 static PtrHashtable analyzed_member_obsolete = new PtrHashtable ();
1445 static PtrHashtable analyzed_method_excluded = new PtrHashtable ();
1447 static PtrHashtable fixed_buffer_cache = new PtrHashtable ();
1449 static object TRUE = new object ();
1450 static object FALSE = new object ();
1452 private AttributeTester ()
1456 public enum Result {
1463 /// Returns true if parameters of two compared methods are CLS-Compliant.
1464 /// It tests differing only in ref or out, or in array rank.
1466 public static Result AreOverloadedMethodParamsClsCompliant (Type[] types_a, Type[] types_b)
1468 if (types_a == null || types_b == null)
1471 if (types_a.Length != types_b.Length)
1474 Result result = Result.Ok;
1475 for (int i = 0; i < types_b.Length; ++i) {
1476 Type aType = types_a [i];
1477 Type bType = types_b [i];
1479 if (aType.IsArray && bType.IsArray) {
1480 Type a_el_type = aType.GetElementType ();
1481 Type b_el_type = bType.GetElementType ();
1482 if (aType.GetArrayRank () != bType.GetArrayRank () && a_el_type == b_el_type) {
1483 result = Result.RefOutArrayError;
1487 if (a_el_type.IsArray || b_el_type.IsArray) {
1488 result = Result.ArrayArrayError;
1493 Type aBaseType = aType;
1494 bool is_either_ref_or_out = false;
1496 if (aType.IsByRef || aType.IsPointer) {
1497 aBaseType = aType.GetElementType ();
1498 is_either_ref_or_out = true;
1501 Type bBaseType = bType;
1502 if (bType.IsByRef || bType.IsPointer)
1504 bBaseType = bType.GetElementType ();
1505 is_either_ref_or_out = !is_either_ref_or_out;
1508 if (aBaseType != bBaseType)
1511 if (is_either_ref_or_out)
1512 result = Result.RefOutArrayError;
1518 /// Goes through all parameters and test if they are CLS-Compliant.
1520 public static bool AreParametersCompliant (Parameter[] fixedParameters, Location loc)
1522 if (fixedParameters == null)
1525 foreach (Parameter arg in fixedParameters) {
1526 if (!AttributeTester.IsClsCompliant (arg.ParameterType)) {
1527 Report.Error (3001, loc, "Argument type `{0}' is not CLS-compliant", arg.GetSignatureForError ());
1536 /// This method tests the CLS compliance of external types. It doesn't test type visibility.
1538 public static bool IsClsCompliant (Type type)
1543 object type_compliance = analyzed_types[type];
1544 if (type_compliance != null)
1545 return type_compliance == TRUE;
1547 if (type.IsPointer) {
1548 analyzed_types.Add (type, null);
1553 if (type.IsArray || type.IsByRef) {
1554 result = IsClsCompliant (TypeManager.GetElementType (type));
1556 result = AnalyzeTypeCompliance (type);
1558 analyzed_types.Add (type, result ? TRUE : FALSE);
1563 /// Returns IFixedBuffer implementation if field is fixed buffer else null.
1565 public static IFixedBuffer GetFixedBuffer (FieldInfo fi)
1567 FieldBase fb = TypeManager.GetField (fi);
1569 return fb as IFixedBuffer;
1572 object o = fixed_buffer_cache [fi];
1574 if (System.Attribute.GetCustomAttribute (fi, TypeManager.fixed_buffer_attr_type) == null) {
1575 fixed_buffer_cache.Add (fi, FALSE);
1579 IFixedBuffer iff = new FixedFieldExternal (fi);
1580 fixed_buffer_cache.Add (fi, iff);
1587 return (IFixedBuffer)o;
1590 public static void VerifyModulesClsCompliance ()
1592 Module[] modules = TypeManager.Modules;
1593 if (modules == null)
1596 // The first module is generated assembly
1597 for (int i = 1; i < modules.Length; ++i) {
1598 Module module = modules [i];
1599 if (!IsClsCompliant (module)) {
1600 Report.Error (3013, "Added modules must be marked with the CLSCompliant attribute to match the assembly", module.Name);
1606 public static Type GetImportedIgnoreCaseClsType (string name)
1608 foreach (Assembly a in TypeManager.GetAssemblies ()) {
1609 Type t = a.GetType (name, false, true);
1613 if (IsClsCompliant (t))
1619 static bool IsClsCompliant (ICustomAttributeProvider attribute_provider)
1621 object[] CompliantAttribute = attribute_provider.GetCustomAttributes (TypeManager.cls_compliant_attribute_type, false);
1622 if (CompliantAttribute.Length == 0)
1625 return ((CLSCompliantAttribute)CompliantAttribute[0]).IsCompliant;
1628 static bool AnalyzeTypeCompliance (Type type)
1630 if (type.IsGenericInstance)
1631 type = type.GetGenericTypeDefinition ();
1632 DeclSpace ds = TypeManager.LookupDeclSpace (type);
1634 return ds.IsClsComplianceRequired (ds);
1636 if (type.IsGenericParameter)
1639 object[] CompliantAttribute = type.GetCustomAttributes (TypeManager.cls_compliant_attribute_type, false);
1640 if (CompliantAttribute.Length == 0)
1641 return IsClsCompliant (type.Assembly);
1643 return ((CLSCompliantAttribute)CompliantAttribute[0]).IsCompliant;
1647 /// Returns instance of ObsoleteAttribute when type is obsolete
1649 public static ObsoleteAttribute GetObsoleteAttribute (Type type)
1651 object type_obsolete = analyzed_types_obsolete [type];
1652 if (type_obsolete == FALSE)
1655 if (type_obsolete != null)
1656 return (ObsoleteAttribute)type_obsolete;
1658 ObsoleteAttribute result = null;
1659 if (type.IsByRef || type.IsArray || type.IsPointer) {
1660 result = GetObsoleteAttribute (TypeManager.GetElementType (type));
1661 } else if (type.IsGenericParameter || type.IsGenericInstance)
1664 DeclSpace type_ds = TypeManager.LookupDeclSpace (type);
1666 // Type is external, we can get attribute directly
1667 if (type_ds == null) {
1668 object[] attribute = type.GetCustomAttributes (TypeManager.obsolete_attribute_type, false);
1669 if (attribute.Length == 1)
1670 result = (ObsoleteAttribute)attribute [0];
1672 result = type_ds.GetObsoleteAttribute (type_ds);
1676 analyzed_types_obsolete.Add (type, result == null ? FALSE : result);
1681 /// Returns instance of ObsoleteAttribute when method is obsolete
1683 public static ObsoleteAttribute GetMethodObsoleteAttribute (MethodBase mb)
1685 IMethodData mc = TypeManager.GetMethod (mb);
1687 return mc.GetObsoleteAttribute ();
1689 // compiler generated methods are not registered by AddMethod
1690 if (mb.DeclaringType is TypeBuilder)
1693 PropertyInfo pi = PropertyExpr.AccessorTable [mb] as PropertyInfo;
1695 return GetMemberObsoleteAttribute (pi);
1697 return GetMemberObsoleteAttribute (mb);
1701 /// Returns instance of ObsoleteAttribute when member is obsolete
1703 public static ObsoleteAttribute GetMemberObsoleteAttribute (MemberInfo mi)
1705 object type_obsolete = analyzed_member_obsolete [mi];
1706 if (type_obsolete == FALSE)
1709 if (type_obsolete != null)
1710 return (ObsoleteAttribute)type_obsolete;
1712 if ((mi.DeclaringType is TypeBuilder) || mi.DeclaringType.IsGenericInstance)
1715 ObsoleteAttribute oa = System.Attribute.GetCustomAttribute (mi, TypeManager.obsolete_attribute_type, false) as ObsoleteAttribute;
1716 analyzed_member_obsolete.Add (mi, oa == null ? FALSE : oa);
1721 /// Common method for Obsolete error/warning reporting.
1723 public static void Report_ObsoleteMessage (ObsoleteAttribute oa, string member, Location loc)
1726 Report.Error (619, loc, "`{0}' is obsolete: `{1}'", member, oa.Message);
1730 if (oa.Message == null) {
1731 Report.Warning (612, loc, "`{0}' is obsolete", member);
1734 if (RootContext.WarningLevel >= 2)
1735 Report.Warning (618, loc, "`{0}' is obsolete: `{1}'", member, oa.Message);
1738 public static bool IsConditionalMethodExcluded (MethodBase mb)
1740 object excluded = analyzed_method_excluded [mb];
1741 if (excluded != null)
1742 return excluded == TRUE ? true : false;
1744 if (mb.Mono_IsInflatedMethod)
1747 ConditionalAttribute[] attrs = mb.GetCustomAttributes (TypeManager.conditional_attribute_type, true) as ConditionalAttribute[];
1748 if (attrs.Length == 0) {
1749 analyzed_method_excluded.Add (mb, FALSE);
1753 foreach (ConditionalAttribute a in attrs) {
1754 if (RootContext.AllDefines.Contains (a.ConditionString)) {
1755 analyzed_method_excluded.Add (mb, FALSE);
1759 analyzed_method_excluded.Add (mb, TRUE);
1764 /// Analyzes class whether it has attribute which has ConditionalAttribute
1765 /// and its condition is not defined.
1767 public static bool IsAttributeExcluded (Type type)
1772 Class class_decl = TypeManager.LookupDeclSpace (type) as Class;
1774 // TODO: add caching
1775 // TODO: merge all Type bases attribute caching to one cache to save memory
1776 if (class_decl == null) {
1777 object[] attributes = type.GetCustomAttributes (TypeManager.conditional_attribute_type, false);
1778 foreach (ConditionalAttribute ca in attributes) {
1779 if (RootContext.AllDefines.Contains (ca.ConditionString))
1782 return attributes.Length > 0;
1785 return class_decl.IsExcluded ();