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 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);
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 during emitting `{0}' attribute. The reason is `{1}'", TypeManager.CSharpName (Type), inner);
146 public void Error_InvalidSecurityParent ()
148 Error_AttributeEmitError ("it is attached to invalid parent");
151 protected virtual FullNamedExpression ResolveAsTypeTerminal (Expression expr, EmitContext ec, bool silent)
153 return expr.ResolveAsTypeTerminal (ec, silent);
156 protected virtual FullNamedExpression ResolveAsTypeStep (Expression expr, EmitContext ec, bool silent)
158 return expr.ResolveAsTypeStep (ec, silent);
161 Type ResolvePossibleAttributeType (EmitContext ec, string name, bool silent, ref bool is_attr)
163 FullNamedExpression fn;
164 if (LeftExpr == null) {
165 fn = ResolveAsTypeTerminal (new SimpleName (name, Location), ec, silent);
167 fn = ResolveAsTypeStep (LeftExpr, ec, silent);
170 fn = new MemberAccess (fn, name, Location).ResolveAsTypeTerminal (ec, silent);
173 TypeExpr te = fn as TypeExpr;
178 if (t.IsSubclassOf (TypeManager.attribute_type)) {
180 } else if (!silent) {
181 Report.SymbolRelatedToPreviousError (t);
182 Report.Error (616, Location, "`{0}': is not an attribute class", TypeManager.CSharpName (t));
188 /// Tries to resolve the type of the attribute. Flags an error if it can't, and complain is true.
190 void ResolveAttributeType (EmitContext ec)
192 bool t1_is_attr = false;
193 Type t1 = ResolvePossibleAttributeType (ec, Identifier, true, ref t1_is_attr);
195 bool t2_is_attr = false;
196 Type t2 = nameEscaped ? null :
197 ResolvePossibleAttributeType (ec, Identifier + "Attribute", true, ref t2_is_attr);
199 if (t1_is_attr && t2_is_attr) {
200 Report.Error (1614, Location, "`{0}' is ambiguous between `{0}' and `{0}Attribute'. Use either `@{0}' or `{0}Attribute'", GetSignatureForError ());
201 resolve_error = true;
215 if (t1 == null && t2 == null)
216 ResolvePossibleAttributeType (ec, Identifier, false, ref t1_is_attr);
218 ResolvePossibleAttributeType (ec, Identifier, false, ref t1_is_attr);
220 ResolvePossibleAttributeType (ec, Identifier + "Attribute", false, ref t2_is_attr);
222 resolve_error = true;
225 public virtual Type ResolveType (EmitContext ec)
227 if (Type == null && !resolve_error)
228 ResolveAttributeType (ec);
232 public string GetSignatureForError ()
234 return LeftExpr == null ? Identifier : LeftExpr.GetSignatureForError () + "." + Identifier;
238 // Given an expression, if the expression is a valid attribute-argument-expression
239 // returns an object that can be used to encode it, or null on failure.
241 public static bool GetAttributeArgumentExpression (Expression e, Location loc, Type arg_type, out object result)
243 Constant constant = e as Constant;
244 if (constant != null) {
245 constant = constant.ToType (arg_type, loc);
246 if (constant == null) {
250 result = constant.GetTypedValue ();
252 } else if (e is TypeOf) {
253 result = ((TypeOf) e).TypeArg;
255 } else if (e is ArrayCreation){
256 result = ((ArrayCreation) e).EncodeAsAttribute ();
259 } else if (e is EmptyCast) {
260 Expression child = ((EmptyCast)e).Child;
261 return GetAttributeArgumentExpression (child, loc, child.Type, out result);
262 } else if (e is As) {
264 return GetAttributeArgumentExpression (as_e.Expr, loc, as_e.ProbeType.Type, out result);
268 Error_AttributeArgumentNotValid (loc);
272 bool IsValidArgumentType (Type t)
275 t = t.GetElementType ();
277 return TypeManager.IsPrimitiveType (t) ||
278 TypeManager.IsEnumType (t) ||
279 t == TypeManager.string_type ||
280 t == TypeManager.object_type ||
281 t == TypeManager.type_type;
284 // Cache for parameter-less attributes
285 static PtrHashtable att_cache = new PtrHashtable ();
287 public CustomAttributeBuilder Resolve (EmitContext ec)
292 resolve_error = true;
295 ResolveAttributeType (ec);
300 if (Type.IsAbstract) {
301 Report.Error (653, Location, "Cannot apply attribute class `{0}' because it is abstract", GetSignatureForError ());
305 if (Arguments == null) {
306 object o = att_cache [Type];
308 resolve_error = false;
309 return (CustomAttributeBuilder)o;
313 ConstructorInfo ctor = ResolveArguments (ec);
317 CustomAttributeBuilder cb;
320 if (prop_info_arr != null || field_info_arr != null) {
321 cb = new CustomAttributeBuilder (
323 prop_info_arr, prop_values_arr,
324 field_info_arr, field_values_arr);
326 cb = new CustomAttributeBuilder (
329 if (pos_values.Length == 0)
330 att_cache.Add (Type, cb);
334 Error_AttributeArgumentNotValid (Location);
338 resolve_error = false;
342 protected virtual ConstructorInfo ResolveArguments (EmitContext ec)
344 // Now we extract the positional and named arguments
346 ArrayList pos_args = null;
347 ArrayList named_args = null;
348 int pos_arg_count = 0;
349 int named_arg_count = 0;
351 if (Arguments != null) {
352 pos_args = (ArrayList) Arguments [0];
353 if (pos_args != null)
354 pos_arg_count = pos_args.Count;
355 if (Arguments.Count > 1) {
356 named_args = (ArrayList) Arguments [1];
357 named_arg_count = named_args.Count;
361 pos_values = new object [pos_arg_count];
364 // First process positional arguments
368 for (i = 0; i < pos_arg_count; i++) {
369 Argument a = (Argument) pos_args [i];
372 if (!a.Resolve (ec, Location))
378 if (!GetAttributeArgumentExpression (e, Location, a.Type, out val))
381 pos_values [i] = val;
383 if (i == 0 && Type == TypeManager.attribute_usage_type && (int)val == 0) {
384 Report.Error (591, Location, "Invalid value for argument to 'System.AttributeUsage' attribute");
390 // Now process named arguments
393 ArrayList field_infos = null;
394 ArrayList prop_infos = null;
395 ArrayList field_values = null;
396 ArrayList prop_values = null;
397 Hashtable seen_names = null;
399 if (named_arg_count > 0) {
400 field_infos = new ArrayList ();
401 prop_infos = new ArrayList ();
402 field_values = new ArrayList ();
403 prop_values = new ArrayList ();
405 seen_names = new Hashtable();
408 for (i = 0; i < named_arg_count; i++) {
409 DictionaryEntry de = (DictionaryEntry) named_args [i];
410 string member_name = (string) de.Key;
411 Argument a = (Argument) de.Value;
414 if (seen_names.Contains(member_name)) {
415 Report.Error(643, Location, "'" + member_name + "' duplicate named attribute argument");
418 seen_names.Add(member_name, 1);
420 if (!a.Resolve (ec, Location))
423 Expression member = Expression.MemberLookup (
424 ec, Type, member_name,
425 MemberTypes.Field | MemberTypes.Property,
426 BindingFlags.Public | BindingFlags.Instance,
429 if (member == null) {
430 member = Expression.MemberLookup (ec, Type, member_name,
431 MemberTypes.Field | MemberTypes.Property, BindingFlags.NonPublic | BindingFlags.Instance,
434 if (member != null) {
435 Expression.ErrorIsInaccesible (Location, member.GetSignatureForError ());
441 Report.Error (117, Location, "`{0}' does not contain a definition for `{1}'",
446 if (!(member is PropertyExpr || member is FieldExpr)) {
447 Error_InvalidNamedArgument (member_name);
452 if (member is PropertyExpr) {
453 PropertyExpr pe = (PropertyExpr) member;
454 PropertyInfo pi = pe.PropertyInfo;
456 if (!pi.CanWrite || !pi.CanRead) {
457 Report.SymbolRelatedToPreviousError (pi);
458 Error_InvalidNamedArgument (member_name);
462 if (!IsValidArgumentType (pi.PropertyType)) {
463 Report.SymbolRelatedToPreviousError (pi);
464 Error_InvalidNamedAgrumentType (member_name);
469 if (!GetAttributeArgumentExpression (e, Location, pi.PropertyType, out value))
472 prop_values.Add (value);
475 } else if (member is FieldExpr) {
476 FieldExpr fe = (FieldExpr) member;
477 FieldInfo fi = fe.FieldInfo;
480 Error_InvalidNamedArgument (member_name);
484 if (!IsValidArgumentType (fi.FieldType)) {
485 Report.SymbolRelatedToPreviousError (fi);
486 Error_InvalidNamedAgrumentType (member_name);
491 if (!GetAttributeArgumentExpression (e, Location, fi.FieldType, out value))
494 field_values.Add (value);
495 field_infos.Add (fi);
499 Expression mg = Expression.MemberLookup (
500 ec, Type, ".ctor", MemberTypes.Constructor,
501 BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly,
504 MethodBase constructor = Invocation.OverloadResolve (
505 ec, (MethodGroupExpr) mg, pos_args, false, Location);
507 if (constructor == null) {
512 // Here we do the checks which should be done by corlib or by runtime.
513 // However Zoltan doesn't like it and every Mono compiler has to do it again.
515 if (Type == TypeManager.guid_attr_type) {
517 new Guid ((string)pos_values [0]);
519 catch (Exception e) {
520 Error_AttributeEmitError (e.Message);
524 // if (Type == TypeManager.methodimpl_attr_type &&
525 // pos_values.Length == 1 && ((Argument)pos_args [0]).Type == TypeManager.short_type &&
526 // !System.Enum.IsDefined (TypeManager.method_impl_options, pos_values [0])) {
527 // Error_AttributeEmitError ("Incorrect argument value.");
531 // Now we perform some checks on the positional args as they
532 // cannot be null for a constructor which expects a parameter
536 ParameterData pd = TypeManager.GetParameterData (constructor);
538 int last_real_param = pd.Count;
540 // When the params is not filled we need to put one
541 if (last_real_param > pos_arg_count) {
542 object [] new_pos_values = new object [pos_arg_count + 1];
543 pos_values.CopyTo (new_pos_values, 0);
544 new_pos_values [pos_arg_count] = new object [] {} ;
545 pos_values = new_pos_values;
550 for (int j = 0; j < pos_arg_count; ++j) {
551 Argument a = (Argument) pos_args [j];
553 if (a.Expr is NullLiteral && pd.ParameterType (j) == TypeManager.object_type) {
554 Error_AttributeArgumentNotValid (Location);
558 object value = pos_values [j];
559 if (value != null && a.Type != value.GetType () && TypeManager.IsPrimitiveType (a.Type)) {
561 pos_values [j] = TypeManager.ChangeType (value, a.Type, out fail);
563 // TODO: Can failed ?
564 throw new NotImplementedException ();
568 if (j < last_real_param)
571 if (j == last_real_param) {
572 object [] array = new object [pos_arg_count - last_real_param];
573 array [0] = pos_values [j];
574 pos_values [j] = array;
578 object [] params_array = (object []) pos_values [last_real_param];
579 params_array [j - last_real_param] = pos_values [j];
582 // Adjust the size of the pos_values if it had params
583 if (last_real_param != pos_arg_count) {
584 object [] new_pos_values = new object [last_real_param + 1];
585 Array.Copy (pos_values, new_pos_values, last_real_param + 1);
586 pos_values = new_pos_values;
589 if (named_arg_count > 0) {
590 prop_info_arr = new PropertyInfo [prop_infos.Count];
591 field_info_arr = new FieldInfo [field_infos.Count];
592 field_values_arr = new object [field_values.Count];
593 prop_values_arr = new object [prop_values.Count];
595 field_infos.CopyTo (field_info_arr, 0);
596 field_values.CopyTo (field_values_arr, 0);
598 prop_values.CopyTo (prop_values_arr, 0);
599 prop_infos.CopyTo (prop_info_arr, 0);
602 return (ConstructorInfo) constructor;
606 /// Get a string containing a list of valid targets for the attribute 'attr'
608 public string GetValidTargets ()
610 StringBuilder sb = new StringBuilder ();
611 AttributeTargets targets = GetAttributeUsage (null).ValidOn;
613 if ((targets & AttributeTargets.Assembly) != 0)
614 sb.Append ("assembly, ");
616 if ((targets & AttributeTargets.Module) != 0)
617 sb.Append ("module, ");
619 if ((targets & AttributeTargets.Class) != 0)
620 sb.Append ("class, ");
622 if ((targets & AttributeTargets.Struct) != 0)
623 sb.Append ("struct, ");
625 if ((targets & AttributeTargets.Enum) != 0)
626 sb.Append ("enum, ");
628 if ((targets & AttributeTargets.Constructor) != 0)
629 sb.Append ("constructor, ");
631 if ((targets & AttributeTargets.Method) != 0)
632 sb.Append ("method, ");
634 if ((targets & AttributeTargets.Property) != 0)
635 sb.Append ("property, indexer, ");
637 if ((targets & AttributeTargets.Field) != 0)
638 sb.Append ("field, ");
640 if ((targets & AttributeTargets.Event) != 0)
641 sb.Append ("event, ");
643 if ((targets & AttributeTargets.Interface) != 0)
644 sb.Append ("interface, ");
646 if ((targets & AttributeTargets.Parameter) != 0)
647 sb.Append ("parameter, ");
649 if ((targets & AttributeTargets.Delegate) != 0)
650 sb.Append ("delegate, ");
652 if ((targets & AttributeTargets.ReturnValue) != 0)
653 sb.Append ("return, ");
656 if ((targets & AttributeTargets.GenericParameter) != 0)
657 sb.Append ("type parameter, ");
659 return sb.Remove (sb.Length - 2, 2).ToString ();
663 /// Returns AttributeUsage attribute for this type
665 AttributeUsageAttribute GetAttributeUsage (EmitContext ec)
667 AttributeUsageAttribute ua = usage_attr_cache [Type] as AttributeUsageAttribute;
671 Class attr_class = TypeManager.LookupClass (Type);
673 if (attr_class == null) {
674 object[] usage_attr = Type.GetCustomAttributes (TypeManager.attribute_usage_type, true);
675 ua = (AttributeUsageAttribute)usage_attr [0];
676 usage_attr_cache.Add (Type, ua);
680 Attribute a = attr_class.OptAttributes == null
682 : attr_class.OptAttributes.Search (TypeManager.attribute_usage_type, attr_class.EmitContext);
685 ? DefaultUsageAttribute
686 : a.GetAttributeUsageAttribute (attr_class.EmitContext);
688 usage_attr_cache.Add (Type, ua);
692 AttributeUsageAttribute GetAttributeUsageAttribute (EmitContext ec)
694 if (pos_values == null)
695 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
696 // But because a lot of attribute class code must be rewritten will be better to wait...
700 return DefaultUsageAttribute;
702 AttributeUsageAttribute usage_attribute = new AttributeUsageAttribute ((AttributeTargets)pos_values [0]);
704 object field = GetPropertyValue ("AllowMultiple");
706 usage_attribute.AllowMultiple = (bool)field;
708 field = GetPropertyValue ("Inherited");
710 usage_attribute.Inherited = (bool)field;
712 return usage_attribute;
716 /// Returns custom name of indexer
718 public string GetIndexerAttributeValue (EmitContext ec)
720 if (pos_values == null)
721 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
722 // But because a lot of attribute class code must be rewritten will be better to wait...
728 return pos_values [0] as string;
732 /// Returns condition of ConditionalAttribute
734 public string GetConditionalAttributeValue (EmitContext ec)
736 if (pos_values == null)
737 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
738 // But because a lot of attribute class code must be rewritten will be better to wait...
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...
760 if (pos_values == null || pos_values.Length == 0)
761 return new ObsoleteAttribute ();
763 if (pos_values.Length == 1)
764 return new ObsoleteAttribute ((string)pos_values [0]);
766 return new ObsoleteAttribute ((string)pos_values [0], (bool)pos_values [1]);
770 /// Returns value of CLSCompliantAttribute contructor parameter but because the method can be called
771 /// before ApplyAttribute. We need to resolve the arguments.
772 /// This situation occurs when class deps is differs from Emit order.
774 public bool GetClsCompliantAttributeValue (EmitContext ec)
776 if (pos_values == null)
777 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
778 // But because a lot of attribute class code must be rewritten will be better to wait...
784 return (bool)pos_values [0];
788 /// Tests permitted SecurityAction for assembly or other types
790 public bool CheckSecurityActionValidity (bool for_assembly)
792 SecurityAction action = GetSecurityActionValue ();
794 if ((action == SecurityAction.RequestMinimum || action == SecurityAction.RequestOptional || action == SecurityAction.RequestRefuse) && for_assembly)
798 if (action < SecurityAction.Demand || action > SecurityAction.InheritanceDemand) {
799 Error_AttributeEmitError ("SecurityAction is out of range");
803 if ((action != SecurityAction.RequestMinimum && action != SecurityAction.RequestOptional && action != SecurityAction.RequestRefuse) && !for_assembly)
807 Error_AttributeEmitError (String.Concat ("SecurityAction '", action, "' is not valid for this declaration"));
811 System.Security.Permissions.SecurityAction GetSecurityActionValue ()
813 return (SecurityAction)pos_values [0];
817 /// Creates instance of SecurityAttribute class and add result of CreatePermission method to permission table.
819 /// <returns></returns>
820 public void ExtractSecurityPermissionSet (ListDictionary permissions)
822 Type orig_assembly_type = null;
824 if (TypeManager.LookupDeclSpace (Type) != null) {
825 if (!RootContext.StdLib) {
826 orig_assembly_type = Type.GetType (Type.FullName);
828 string orig_version_path = Environment.GetEnvironmentVariable ("__SECURITY_BOOTSTRAP_DB");
829 if (orig_version_path == null) {
830 Error_AttributeEmitError ("security custom attributes can not be referenced from defining assembly");
834 if (orig_sec_assembly == null) {
835 string file = Path.Combine (orig_version_path, Driver.OutputFile);
836 orig_sec_assembly = Assembly.LoadFile (file);
839 orig_assembly_type = orig_sec_assembly.GetType (Type.FullName, true);
840 if (orig_assembly_type == null) {
841 Report.Warning (-112, 1, Location, "Self-referenced security attribute `{0}' was not found in previous version of assembly");
847 SecurityAttribute sa;
848 // For all non-selfreferencing security attributes we can avoid all hacks
849 if (orig_assembly_type == null) {
850 sa = (SecurityAttribute) Activator.CreateInstance (Type, pos_values);
852 if (prop_info_arr != null) {
853 for (int i = 0; i < prop_info_arr.Length; ++i) {
854 PropertyInfo pi = prop_info_arr [i];
855 pi.SetValue (sa, prop_values_arr [i], null);
859 // HACK: All security attributes have same ctor syntax
860 sa = (SecurityAttribute) Activator.CreateInstance (orig_assembly_type, new object[] { GetSecurityActionValue () } );
862 // All types are from newly created assembly but for invocation with old one we need to convert them
863 if (prop_info_arr != null) {
864 for (int i = 0; i < prop_info_arr.Length; ++i) {
865 PropertyInfo emited_pi = prop_info_arr [i];
866 PropertyInfo pi = orig_assembly_type.GetProperty (emited_pi.Name, emited_pi.PropertyType);
868 object old_instance = pi.PropertyType.IsEnum ?
869 System.Enum.ToObject (pi.PropertyType, prop_values_arr [i]) :
872 pi.SetValue (sa, old_instance, null);
878 perm = sa.CreatePermission ();
879 SecurityAction action = GetSecurityActionValue ();
881 // IS is correct because for corlib we are using an instance from old corlib
882 if (!(perm is System.Security.CodeAccessPermission)) {
884 case SecurityAction.Demand:
885 action = (SecurityAction)13;
887 case SecurityAction.LinkDemand:
888 action = (SecurityAction)14;
890 case SecurityAction.InheritanceDemand:
891 action = (SecurityAction)15;
896 PermissionSet ps = (PermissionSet)permissions [action];
898 if (sa is PermissionSetAttribute)
899 ps = new PermissionSet (sa.Unrestricted ? PermissionState.Unrestricted : PermissionState.None);
901 ps = new PermissionSet (PermissionState.None);
903 permissions.Add (action, ps);
904 } else if (!ps.IsUnrestricted () && (sa is PermissionSetAttribute) && sa.Unrestricted) {
905 ps = ps.Union (new PermissionSet (PermissionState.Unrestricted));
906 permissions [action] = ps;
908 ps.AddPermission (perm);
911 object GetValue (object value)
913 if (value is EnumConstant)
914 return ((EnumConstant) value).GetValue ();
919 object GetPropertyValue (string name)
921 if (prop_info_arr == null)
924 for (int i = 0; i < prop_info_arr.Length; ++i) {
925 if (prop_info_arr [i].Name == name)
926 return prop_values_arr [i];
932 object GetFieldValue (string name)
935 if (field_info_arr == null)
938 foreach (FieldInfo fi in field_info_arr) {
940 return GetValue (field_values_arr [i]);
947 // Theoretically, we can get rid of this, since FieldBuilder.SetCustomAttribute()
948 // and ParameterBuilder.SetCustomAttribute() are supposed to handle this attribute.
949 // However, we can't, since it appears that the .NET 1.1 SRE hangs when given a MarshalAsAttribute.
951 public UnmanagedMarshal GetMarshal (Attributable attr)
953 UnmanagedType UnmanagedType;
954 if (!RootContext.StdLib || pos_values [0].GetType () != typeof (UnmanagedType))
955 UnmanagedType = (UnmanagedType) System.Enum.ToObject (typeof (UnmanagedType), pos_values [0]);
957 UnmanagedType = (UnmanagedType) pos_values [0];
959 object value = GetFieldValue ("SizeParamIndex");
960 if (value != null && UnmanagedType != UnmanagedType.LPArray) {
961 Error_AttributeEmitError ("SizeParamIndex field is not valid for the specified unmanaged type");
965 object o = GetFieldValue ("ArraySubType");
966 UnmanagedType array_sub_type = o == null ? (UnmanagedType) 0x50 /* NATIVE_MAX */ : (UnmanagedType) o;
968 switch (UnmanagedType) {
969 case UnmanagedType.CustomMarshaler: {
970 MethodInfo define_custom = typeof (UnmanagedMarshal).GetMethod ("DefineCustom",
971 BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
972 if (define_custom == null) {
973 Report.RuntimeMissingSupport (Location, "set marshal info");
977 object [] args = new object [4];
978 args [0] = GetFieldValue ("MarshalTypeRef");
979 args [1] = GetFieldValue ("MarshalCookie");
980 args [2] = GetFieldValue ("MarshalType");
981 args [3] = Guid.Empty;
982 return (UnmanagedMarshal) define_custom.Invoke (null, args);
984 case UnmanagedType.LPArray: {
985 object size_const = GetFieldValue ("SizeConst");
986 object size_param_index = GetFieldValue ("SizeParamIndex");
988 if ((size_const != null) || (size_param_index != null)) {
989 MethodInfo define_array = typeof (UnmanagedMarshal).GetMethod ("DefineLPArrayInternal",
990 BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
991 if (define_array == null) {
992 Report.RuntimeMissingSupport (Location, "set marshal info");
996 object [] args = new object [3];
997 args [0] = array_sub_type;
998 args [1] = size_const == null ? -1 : size_const;
999 args [2] = size_param_index == null ? -1 : size_param_index;
1000 return (UnmanagedMarshal) define_array.Invoke (null, args);
1003 return UnmanagedMarshal.DefineLPArray (array_sub_type);
1005 case UnmanagedType.SafeArray:
1006 return UnmanagedMarshal.DefineSafeArray (array_sub_type);
1008 case UnmanagedType.ByValArray:
1009 FieldMember fm = attr as FieldMember;
1011 Error_AttributeEmitError ("Specified unmanaged type is only valid on fields");
1014 return UnmanagedMarshal.DefineByValArray ((int) GetFieldValue ("SizeConst"));
1016 case UnmanagedType.ByValTStr:
1017 return UnmanagedMarshal.DefineByValTStr ((int) GetFieldValue ("SizeConst"));
1020 return UnmanagedMarshal.DefineUnmanagedMarshal (UnmanagedType);
1024 public CharSet GetCharSetValue ()
1026 return (CharSet)System.Enum.Parse (typeof (CharSet), pos_values [0].ToString ());
1029 public MethodImplOptions GetMethodImplOptions ()
1031 if (pos_values [0].GetType () != typeof (MethodImplOptions))
1032 return (MethodImplOptions)System.Enum.ToObject (typeof (MethodImplOptions), pos_values [0]);
1033 return (MethodImplOptions)pos_values [0];
1036 public LayoutKind GetLayoutKindValue ()
1038 if (!RootContext.StdLib || pos_values [0].GetType () != typeof (LayoutKind))
1039 return (LayoutKind)System.Enum.ToObject (typeof (LayoutKind), pos_values [0]);
1041 return (LayoutKind)pos_values [0];
1045 /// Emit attribute for Attributable symbol
1047 public void Emit (EmitContext ec, Attributable ias, ListDictionary emitted_attr)
1049 CustomAttributeBuilder cb = Resolve (ec);
1053 AttributeUsageAttribute usage_attr = GetAttributeUsage (ec);
1054 if ((usage_attr.ValidOn & Target) == 0) {
1055 Report.Error (592, Location, "Attribute `{0}' is not valid on this declaration type. It is valid on `{1}' declarations only",
1056 GetSignatureForError (), GetValidTargets ());
1061 ias.ApplyAttributeBuilder (this, cb);
1063 catch (Exception e) {
1064 Error_AttributeEmitError (e.Message);
1068 if (!usage_attr.AllowMultiple) {
1069 ArrayList emitted_targets = (ArrayList)emitted_attr [Type];
1070 if (emitted_targets == null) {
1071 emitted_targets = new ArrayList ();
1072 emitted_attr.Add (Type, emitted_targets);
1073 } else if (emitted_targets.Contains (Target)) {
1074 Report.Error (579, Location, "Duplicate `{0}' attribute", GetSignatureForError ());
1077 emitted_targets.Add (Target);
1080 if (!RootContext.VerifyClsCompliance)
1083 // Here we are testing attribute arguments for array usage (error 3016)
1084 if (ias.IsClsCompliaceRequired (ec.DeclSpace)) {
1085 if (Arguments == null)
1088 ArrayList pos_args = (ArrayList) Arguments [0];
1089 if (pos_args != null) {
1090 foreach (Argument arg in pos_args) {
1091 // Type is undefined (was error 246)
1092 if (arg.Type == null)
1095 if (arg.Type.IsArray) {
1096 Report.Error (3016, Location, "Arrays as attribute arguments are not CLS-compliant");
1102 if (Arguments.Count < 2)
1105 ArrayList named_args = (ArrayList) Arguments [1];
1106 foreach (DictionaryEntry de in named_args) {
1107 Argument arg = (Argument) de.Value;
1109 // Type is undefined (was error 246)
1110 if (arg.Type == null)
1113 if (arg.Type.IsArray) {
1114 Report.Error (3016, Location, "Arrays as attribute arguments are not CLS-compliant");
1121 public MethodBuilder DefinePInvokeMethod (EmitContext ec, TypeBuilder builder, string name,
1122 MethodAttributes flags, Type ret_type, Type [] param_types)
1124 if (pos_values == null)
1125 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
1126 // But because a lot of attribute class code must be rewritten will be better to wait...
1132 string dll_name = (string)pos_values [0];
1135 CallingConvention cc = CallingConvention.Winapi;
1136 CharSet charset = CodeGen.Module.DefaultCharSet;
1137 bool preserve_sig = true;
1138 string entry_point = name;
1139 bool best_fit_mapping = false;
1140 bool throw_on_unmappable = false;
1141 bool exact_spelling = false;
1142 bool set_last_error = false;
1144 bool best_fit_mapping_set = false;
1145 bool throw_on_unmappable_set = false;
1146 bool exact_spelling_set = false;
1147 bool set_last_error_set = false;
1149 MethodInfo set_best_fit = null;
1150 MethodInfo set_throw_on = null;
1151 MethodInfo set_exact_spelling = null;
1152 MethodInfo set_set_last_error = null;
1154 if (field_info_arr != null) {
1156 for (int i = 0; i < field_info_arr.Length; i++) {
1157 switch (field_info_arr [i].Name) {
1158 case "BestFitMapping":
1159 best_fit_mapping = (bool) field_values_arr [i];
1160 best_fit_mapping_set = true;
1162 case "CallingConvention":
1163 cc = (CallingConvention) field_values_arr [i];
1166 charset = (CharSet) field_values_arr [i];
1169 entry_point = (string) field_values_arr [i];
1171 case "ExactSpelling":
1172 exact_spelling = (bool) field_values_arr [i];
1173 exact_spelling_set = true;
1176 preserve_sig = (bool) field_values_arr [i];
1178 case "SetLastError":
1179 set_last_error = (bool) field_values_arr [i];
1180 set_last_error_set = true;
1182 case "ThrowOnUnmappableChar":
1183 throw_on_unmappable = (bool) field_values_arr [i];
1184 throw_on_unmappable_set = true;
1187 throw new InternalErrorException (field_info_arr [i].ToString ());
1192 if (throw_on_unmappable_set || best_fit_mapping_set || exact_spelling_set || set_last_error_set) {
1193 set_best_fit = typeof (MethodBuilder).GetMethod ("set_BestFitMapping", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
1194 set_throw_on = typeof (MethodBuilder).GetMethod ("set_ThrowOnUnmappableChar", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
1195 set_exact_spelling = typeof (MethodBuilder).GetMethod ("set_ExactSpelling", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
1196 set_set_last_error = typeof (MethodBuilder).GetMethod ("set_SetLastError", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
1198 if ((set_best_fit == null) || (set_throw_on == null) || (set_exact_spelling == null) || (set_set_last_error == null)) {
1199 Report.Error (-1, Location,
1200 "The ThrowOnUnmappableChar, BestFitMapping, SetLastError, and ExactSpelling attributes can only be emitted when running on the mono runtime.");
1206 MethodBuilder mb = builder.DefinePInvokeMethod (
1207 name, dll_name, entry_point, flags | MethodAttributes.HideBySig | MethodAttributes.PinvokeImpl,
1208 CallingConventions.Standard, ret_type, param_types, cc, charset);
1211 mb.SetImplementationFlags (MethodImplAttributes.PreserveSig);
1213 if (throw_on_unmappable_set)
1214 set_throw_on.Invoke (mb, 0, null, new object [] { throw_on_unmappable }, null);
1215 if (best_fit_mapping_set)
1216 set_best_fit.Invoke (mb, 0, null, new object [] { best_fit_mapping }, null);
1217 if (exact_spelling_set)
1218 set_exact_spelling.Invoke (mb, 0, null, new object [] { exact_spelling }, null);
1219 if (set_last_error_set)
1220 set_set_last_error.Invoke (mb, 0, null, new object [] { set_last_error }, null);
1224 catch (ArgumentException e) {
1225 Error_AttributeEmitError (e.Message);
1230 private Expression GetValue ()
1232 if ((Arguments == null) || (Arguments.Count < 1))
1234 ArrayList al = (ArrayList) Arguments [0];
1235 if ((al == null) || (al.Count < 1))
1237 Argument arg = (Argument) al [0];
1238 if ((arg == null) || (arg.Expr == null))
1243 public string GetString ()
1245 Expression e = GetValue ();
1246 if (e is StringLiteral)
1247 return (e as StringLiteral).Value;
1251 public bool GetBoolean ()
1253 Expression e = GetValue ();
1254 if (e is BoolLiteral)
1255 return (e as BoolLiteral).Value;
1262 /// For global attributes (assembly, module) we need special handling.
1263 /// Attributes can be located in the several files
1265 public class GlobalAttribute: Attribute
1267 public readonly NamespaceEntry ns;
1269 public GlobalAttribute (TypeContainer container, string target,
1270 Expression left_expr, string identifier, ArrayList args, Location loc, bool nameEscaped):
1271 base (target, left_expr, identifier, args, loc, nameEscaped)
1273 ns = container.NamespaceEntry;
1278 // RootContext.Tree.Types has a single NamespaceEntry which gets overwritten
1279 // each time a new file is parsed. However, we need to use the NamespaceEntry
1280 // in effect where the attribute was used. Since code elsewhere cannot assume
1281 // that the NamespaceEntry is right, just overwrite it.
1283 // Precondition: RootContext.Tree.Types == null
1285 if (RootContext.Tree.Types.NamespaceEntry != null)
1286 throw new InternalErrorException (Location + " non-null NamespaceEntry");
1288 RootContext.Tree.Types.NamespaceEntry = ns;
1293 RootContext.Tree.Types.NamespaceEntry = null;
1296 protected override FullNamedExpression ResolveAsTypeStep (Expression expr, EmitContext ec, bool silent)
1300 return base.ResolveAsTypeStep (expr, ec, silent);
1308 protected override FullNamedExpression ResolveAsTypeTerminal (Expression expr, EmitContext ec, bool silent)
1312 return base.ResolveAsTypeTerminal (expr, ec, silent);
1319 protected override ConstructorInfo ResolveArguments (EmitContext ec)
1323 return base.ResolveArguments (ec);
1331 public class Attributes {
1332 public ArrayList Attrs;
1334 public Attributes (Attribute a)
1336 Attrs = new ArrayList ();
1340 public Attributes (ArrayList attrs)
1345 public void AddAttributes (ArrayList attrs)
1347 Attrs.AddRange (attrs);
1351 /// Checks whether attribute target is valid for the current element
1353 public bool CheckTargets (Attributable member)
1355 string[] valid_targets = member.ValidAttributeTargets;
1356 foreach (Attribute a in Attrs) {
1357 if (a.ExplicitTarget == null || a.ExplicitTarget == valid_targets [0]) {
1358 a.Target = member.AttributeTargets;
1362 // TODO: we can skip the first item
1363 if (((IList) valid_targets).Contains (a.ExplicitTarget)) {
1364 switch (a.ExplicitTarget) {
1365 case "return": a.Target = AttributeTargets.ReturnValue; continue;
1366 case "param": a.Target = AttributeTargets.Parameter; continue;
1367 case "field": a.Target = AttributeTargets.Field; continue;
1368 case "method": a.Target = AttributeTargets.Method; continue;
1369 case "property": a.Target = AttributeTargets.Property; continue;
1371 throw new InternalErrorException ("Unknown explicit target: " + a.ExplicitTarget);
1374 StringBuilder sb = new StringBuilder ();
1375 foreach (string s in valid_targets) {
1379 sb.Remove (sb.Length - 2, 2);
1380 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 ());
1386 public Attribute Search (Type t, EmitContext ec)
1388 foreach (Attribute a in Attrs) {
1389 if (a.ResolveType (ec) == t)
1396 /// Returns all attributes of type 't'. Use it when attribute is AllowMultiple = true
1398 public Attribute[] SearchMulti (Type t, EmitContext ec)
1400 ArrayList ar = null;
1402 foreach (Attribute a in Attrs) {
1403 if (a.ResolveType (ec) == t) {
1405 ar = new ArrayList ();
1410 return ar == null ? null : ar.ToArray (typeof (Attribute)) as Attribute[];
1413 public void Emit (EmitContext ec, Attributable ias)
1417 ListDictionary ld = new ListDictionary ();
1419 foreach (Attribute a in Attrs)
1420 a.Emit (ec, ias, ld);
1423 public bool Contains (Type t, EmitContext ec)
1425 return Search (t, ec) != null;
1430 /// Helper class for attribute verification routine.
1432 sealed class AttributeTester
1434 static PtrHashtable analyzed_types = new PtrHashtable ();
1435 static PtrHashtable analyzed_types_obsolete = new PtrHashtable ();
1436 static PtrHashtable analyzed_member_obsolete = new PtrHashtable ();
1437 static PtrHashtable analyzed_method_excluded = new PtrHashtable ();
1440 static PtrHashtable fixed_buffer_cache = new PtrHashtable ();
1443 static object TRUE = new object ();
1444 static object FALSE = new object ();
1446 private AttributeTester ()
1450 public enum Result {
1457 /// Returns true if parameters of two compared methods are CLS-Compliant.
1458 /// It tests differing only in ref or out, or in array rank.
1460 public static Result AreOverloadedMethodParamsClsCompliant (Type[] types_a, Type[] types_b)
1462 if (types_a == null || types_b == null)
1465 if (types_a.Length != types_b.Length)
1468 Result result = Result.Ok;
1469 for (int i = 0; i < types_b.Length; ++i) {
1470 Type aType = types_a [i];
1471 Type bType = types_b [i];
1473 if (aType.IsArray && bType.IsArray) {
1474 Type a_el_type = aType.GetElementType ();
1475 Type b_el_type = bType.GetElementType ();
1476 if (aType.GetArrayRank () != bType.GetArrayRank () && a_el_type == b_el_type) {
1477 result = Result.RefOutArrayError;
1481 if (a_el_type.IsArray || b_el_type.IsArray) {
1482 result = Result.ArrayArrayError;
1487 Type aBaseType = aType;
1488 bool is_either_ref_or_out = false;
1490 if (aType.IsByRef || aType.IsPointer) {
1491 aBaseType = aType.GetElementType ();
1492 is_either_ref_or_out = true;
1495 Type bBaseType = bType;
1496 if (bType.IsByRef || bType.IsPointer)
1498 bBaseType = bType.GetElementType ();
1499 is_either_ref_or_out = !is_either_ref_or_out;
1502 if (aBaseType != bBaseType)
1505 if (is_either_ref_or_out)
1506 result = Result.RefOutArrayError;
1512 /// Goes through all parameters and test if they are CLS-Compliant.
1514 public static bool AreParametersCompliant (Parameter[] fixedParameters, Location loc)
1516 if (fixedParameters == null)
1519 foreach (Parameter arg in fixedParameters) {
1520 if (!AttributeTester.IsClsCompliant (arg.ParameterType)) {
1521 Report.Error (3001, loc, "Argument type `{0}' is not CLS-compliant", arg.GetSignatureForError ());
1530 /// This method tests the CLS compliance of external types. It doesn't test type visibility.
1532 public static bool IsClsCompliant (Type type)
1537 object type_compliance = analyzed_types[type];
1538 if (type_compliance != null)
1539 return type_compliance == TRUE;
1541 if (type.IsPointer) {
1542 analyzed_types.Add (type, null);
1547 if (type.IsArray || type.IsByRef) {
1548 result = IsClsCompliant (TypeManager.GetElementType (type));
1550 result = AnalyzeTypeCompliance (type);
1552 analyzed_types.Add (type, result ? TRUE : FALSE);
1557 /// Returns IFixedBuffer implementation if field is fixed buffer else null.
1559 public static IFixedBuffer GetFixedBuffer (FieldInfo fi)
1561 FieldBase fb = TypeManager.GetField (fi);
1563 return fb as IFixedBuffer;
1567 object o = fixed_buffer_cache [fi];
1569 if (System.Attribute.GetCustomAttribute (fi, TypeManager.fixed_buffer_attr_type) == null) {
1570 fixed_buffer_cache.Add (fi, FALSE);
1574 IFixedBuffer iff = new FixedFieldExternal (fi);
1575 fixed_buffer_cache.Add (fi, iff);
1582 return (IFixedBuffer)o;
1588 public static void VerifyModulesClsCompliance ()
1590 Module[] modules = TypeManager.Modules;
1591 if (modules == null)
1594 // The first module is generated assembly
1595 for (int i = 1; i < modules.Length; ++i) {
1596 Module module = modules [i];
1597 if (!IsClsCompliant (module)) {
1598 Report.Error (3013, "Added modules must be marked with the CLSCompliant attribute to match the assembly", module.Name);
1604 public static Type GetImportedIgnoreCaseClsType (string name)
1606 foreach (Assembly a in TypeManager.GetAssemblies ()) {
1607 Type t = a.GetType (name, false, true);
1611 if (IsClsCompliant (t))
1617 static bool IsClsCompliant (ICustomAttributeProvider attribute_provider)
1619 object[] CompliantAttribute = attribute_provider.GetCustomAttributes (TypeManager.cls_compliant_attribute_type, false);
1620 if (CompliantAttribute.Length == 0)
1623 return ((CLSCompliantAttribute)CompliantAttribute[0]).IsCompliant;
1626 static bool AnalyzeTypeCompliance (Type type)
1628 DeclSpace ds = TypeManager.LookupDeclSpace (type);
1630 return ds.IsClsCompliaceRequired (ds.Parent);
1633 object[] CompliantAttribute = type.GetCustomAttributes (TypeManager.cls_compliant_attribute_type, false);
1634 if (CompliantAttribute.Length == 0)
1635 return IsClsCompliant (type.Assembly);
1637 return ((CLSCompliantAttribute)CompliantAttribute[0]).IsCompliant;
1641 /// Returns instance of ObsoleteAttribute when type is obsolete
1643 public static ObsoleteAttribute GetObsoleteAttribute (Type type)
1645 object type_obsolete = analyzed_types_obsolete [type];
1646 if (type_obsolete == FALSE)
1649 if (type_obsolete != null)
1650 return (ObsoleteAttribute)type_obsolete;
1652 ObsoleteAttribute result = null;
1653 if (type.IsByRef || type.IsArray || type.IsPointer) {
1654 result = GetObsoleteAttribute (TypeManager.GetElementType (type));
1656 DeclSpace type_ds = TypeManager.LookupDeclSpace (type);
1658 // Type is external, we can get attribute directly
1659 if (type_ds == null) {
1660 object[] attribute = type.GetCustomAttributes (TypeManager.obsolete_attribute_type, false);
1661 if (attribute.Length == 1)
1662 result = (ObsoleteAttribute)attribute [0];
1664 result = type_ds.GetObsoleteAttribute (type_ds);
1668 analyzed_types_obsolete.Add (type, result == null ? FALSE : result);
1673 /// Returns instance of ObsoleteAttribute when method is obsolete
1675 public static ObsoleteAttribute GetMethodObsoleteAttribute (MethodBase mb)
1677 IMethodData mc = TypeManager.GetMethod (mb);
1679 return mc.GetObsoleteAttribute ();
1681 // compiler generated methods are not registered by AddMethod
1682 if (mb.DeclaringType is TypeBuilder)
1685 if (mb.IsSpecialName) {
1686 PropertyInfo pi = PropertyExpr.AccessorTable [mb] as PropertyInfo;
1688 // FIXME: This is buggy as properties from this assembly are included as well
1690 //return GetMemberObsoleteAttribute (pi);
1694 return GetMemberObsoleteAttribute (mb);
1698 /// Returns instance of ObsoleteAttribute when member is obsolete
1700 public static ObsoleteAttribute GetMemberObsoleteAttribute (MemberInfo mi)
1702 object type_obsolete = analyzed_member_obsolete [mi];
1703 if (type_obsolete == FALSE)
1706 if (type_obsolete != null)
1707 return (ObsoleteAttribute)type_obsolete;
1709 ObsoleteAttribute oa = System.Attribute.GetCustomAttribute (mi, TypeManager.obsolete_attribute_type, false) as ObsoleteAttribute;
1710 analyzed_member_obsolete.Add (mi, oa == null ? FALSE : oa);
1715 /// Common method for Obsolete error/warning reporting.
1717 public static void Report_ObsoleteMessage (ObsoleteAttribute oa, string member, Location loc)
1720 Report.Error (619, loc, "`{0}' is obsolete: `{1}'", member, oa.Message);
1724 if (oa.Message == null) {
1725 Report.Warning (612, loc, "`{0}' is obsolete", member);
1728 if (RootContext.WarningLevel >= 2)
1729 Report.Warning (618, loc, "`{0}' is obsolete: `{1}'", member, oa.Message);
1732 public static bool IsConditionalMethodExcluded (MethodBase mb)
1734 object excluded = analyzed_method_excluded [mb];
1735 if (excluded != null)
1736 return excluded == TRUE ? true : false;
1738 ConditionalAttribute[] attrs = mb.GetCustomAttributes (TypeManager.conditional_attribute_type, true) as ConditionalAttribute[];
1739 if (attrs.Length == 0) {
1740 analyzed_method_excluded.Add (mb, FALSE);
1744 foreach (ConditionalAttribute a in attrs) {
1745 if (RootContext.AllDefines.Contains (a.ConditionString)) {
1746 analyzed_method_excluded.Add (mb, FALSE);
1750 analyzed_method_excluded.Add (mb, TRUE);
1755 /// Analyzes class whether it has attribute which has ConditionalAttribute
1756 /// and its condition is not defined.
1758 public static bool IsAttributeExcluded (Type type)
1763 Class class_decl = TypeManager.LookupDeclSpace (type) as Class;
1765 // TODO: add caching
1766 // TODO: merge all Type bases attribute caching to one cache to save memory
1767 if (class_decl == null) {
1768 object[] attributes = type.GetCustomAttributes (TypeManager.conditional_attribute_type, false);
1769 foreach (ConditionalAttribute ca in attributes) {
1770 if (RootContext.AllDefines.Contains (ca.ConditionString))
1773 return attributes.Length > 0;
1776 return class_decl.IsExcluded ();