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 protected Attributes attributes;
37 public Attributable (Attributes attrs)
39 OptAttributes = attrs;
42 public Attributes OptAttributes
50 if (attributes != null) {
51 attributes.AttachTo (this);
57 /// Use member-specific procedure to apply attribute @a in @cb to the entity being built in @builder
59 public abstract void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb);
62 /// Returns one AttributeTarget for this element.
64 public abstract AttributeTargets AttributeTargets { get; }
66 public abstract IResolveContext ResolveContext { get; }
68 public abstract bool IsClsComplianceRequired ();
71 /// Gets list of valid attribute targets for explicit target declaration.
72 /// The first array item is default target. Don't break this rule.
74 public abstract string[] ValidAttributeTargets { get; }
77 public class Attribute {
78 public readonly string ExplicitTarget;
79 public AttributeTargets Target;
81 // TODO: remove this member
82 public readonly string Name;
83 public readonly Expression LeftExpr;
84 public readonly string Identifier;
86 readonly ArrayList PosArguments;
87 readonly ArrayList NamedArguments;
89 public readonly Location Location;
94 readonly bool nameEscaped;
97 static readonly AttributeUsageAttribute DefaultUsageAttribute = new AttributeUsageAttribute (AttributeTargets.All);
98 static Assembly orig_sec_assembly;
99 public static readonly object[] EmptyObject = new object [0];
101 // non-null if named args present after Resolve () is called
102 PropertyInfo [] prop_info_arr;
103 FieldInfo [] field_info_arr;
104 object [] field_values_arr;
105 object [] prop_values_arr;
106 object [] pos_values;
108 static PtrHashtable usage_attr_cache = new PtrHashtable ();
110 // Cache for parameter-less attributes
111 static PtrHashtable att_cache = new PtrHashtable ();
113 public Attribute (string target, Expression left_expr, string identifier, object[] args, Location loc, bool nameEscaped)
115 LeftExpr = left_expr;
116 Identifier = identifier;
117 Name = LeftExpr == null ? identifier : LeftExpr + "." + identifier;
119 PosArguments = (ArrayList)args [0];
120 NamedArguments = (ArrayList)args [1];
123 ExplicitTarget = target;
124 this.nameEscaped = nameEscaped;
127 public void AttachTo (Attributable owner)
132 void Error_InvalidNamedArgument (string name)
134 Report.Error (617, Location, "`{0}' is not a valid named attribute argument. Named attribute arguments " +
135 "must be fields which are not readonly, static, const or read-write properties which are " +
136 "public and not static",
140 void Error_InvalidNamedAgrumentType (string name)
142 Report.Error (655, Location, "`{0}' is not a valid named attribute argument because it is not a valid " +
143 "attribute parameter type", name);
146 public static void Error_AttributeArgumentNotValid (Location loc)
148 Report.Error (182, loc,
149 "An attribute argument must be a constant expression, typeof " +
150 "expression or array creation expression");
154 /// This is rather hack. We report many emit attribute error with same error to be compatible with
155 /// csc. But because csc has to report them this way because error came from ilasm we needn't.
157 public void Error_AttributeEmitError (string inner)
159 Report.Error (647, Location, "Error during emitting `{0}' attribute. The reason is `{1}'",
160 TypeManager.CSharpName (Type), inner);
163 public void Error_InvalidSecurityParent ()
165 Error_AttributeEmitError ("it is attached to invalid parent");
168 protected virtual TypeExpr ResolveAsTypeTerminal (Expression expr, IResolveContext ec, bool silent)
170 return expr.ResolveAsTypeTerminal (ec, silent);
173 Type ResolvePossibleAttributeType (string name, bool silent, ref bool is_attr)
175 IResolveContext rc = owner.ResolveContext;
178 if (LeftExpr == null) {
179 te = ResolveAsTypeTerminal (new SimpleName (name, Location), rc, silent);
181 te = ResolveAsTypeTerminal (new MemberAccess (LeftExpr, name), rc, silent);
188 if (TypeManager.IsSubclassOf (t, TypeManager.attribute_type)) {
190 } else if (!silent) {
191 Report.SymbolRelatedToPreviousError (t);
192 Report.Error (616, Location, "`{0}': is not an attribute class", TypeManager.CSharpName (t));
198 /// Tries to resolve the type of the attribute. Flags an error if it can't, and complain is true.
200 void ResolveAttributeType ()
202 bool t1_is_attr = false;
203 Type t1 = ResolvePossibleAttributeType (Identifier, true, ref t1_is_attr);
205 bool t2_is_attr = false;
206 Type t2 = nameEscaped ? null :
207 ResolvePossibleAttributeType (Identifier + "Attribute", true, ref t2_is_attr);
209 if (t1_is_attr && t2_is_attr) {
210 Report.Error (1614, Location, "`{0}' is ambiguous between `{0}' and `{0}Attribute'. " +
211 "Use either `@{0}' or `{0}Attribute'", GetSignatureForError ());
212 resolve_error = true;
226 if (t1 == null && t2 == null)
227 ResolvePossibleAttributeType (Identifier, false, ref t1_is_attr);
229 ResolvePossibleAttributeType (Identifier, false, ref t1_is_attr);
231 ResolvePossibleAttributeType (Identifier + "Attribute", false, ref t2_is_attr);
233 resolve_error = true;
236 public virtual Type ResolveType ()
238 if (Type == null && !resolve_error)
239 ResolveAttributeType ();
243 public string GetSignatureForError ()
246 return TypeManager.CSharpName (Type);
248 return LeftExpr == null ? Identifier : LeftExpr.GetSignatureForError () + "." + Identifier;
251 bool IsValidArgumentType (Type t)
254 t = t.GetElementType ();
256 return TypeManager.IsPrimitiveType (t) ||
257 TypeManager.IsEnumType (t) ||
258 t == TypeManager.string_type ||
259 t == TypeManager.object_type ||
260 t == TypeManager.type_type;
263 public CustomAttributeBuilder Resolve ()
268 resolve_error = true;
271 ResolveAttributeType ();
276 if (Type.IsAbstract) {
277 Report.Error (653, Location, "Cannot apply attribute class `{0}' because it is abstract", GetSignatureForError ());
281 ObsoleteAttribute obsolete_attr = AttributeTester.GetObsoleteAttribute (Type);
282 if (obsolete_attr != null) {
283 AttributeTester.Report_ObsoleteMessage (obsolete_attr, TypeManager.CSharpName (Type), Location);
286 if (PosArguments == null && NamedArguments == null) {
287 object o = att_cache [Type];
289 resolve_error = false;
290 return (CustomAttributeBuilder)o;
294 EmitContext ec = new EmitContext (owner.ResolveContext, owner.ResolveContext.DeclContainer, owner.ResolveContext.DeclContainer,
295 Location, null, null, owner.ResolveContext.DeclContainer.ModFlags, false);
297 ConstructorInfo ctor = ResolveConstructor (ec);
301 CustomAttributeBuilder cb;
304 if (NamedArguments == null) {
305 cb = new CustomAttributeBuilder (ctor, pos_values);
307 if (pos_values.Length == 0)
308 att_cache.Add (Type, cb);
310 resolve_error = false;
314 if (!ResolveNamedArguments (ec)) {
318 cb = new CustomAttributeBuilder (ctor, pos_values,
319 prop_info_arr, prop_values_arr,
320 field_info_arr, field_values_arr);
322 resolve_error = false;
326 Error_AttributeArgumentNotValid (Location);
331 protected virtual ConstructorInfo ResolveConstructor (EmitContext ec)
333 if (PosArguments != null) {
334 for (int i = 0; i < PosArguments.Count; i++) {
335 Argument a = (Argument) PosArguments [i];
337 if (!a.Resolve (ec, Location))
342 Expression mg = Expression.MemberLookup (ec.ContainerType,
343 Type, ".ctor", MemberTypes.Constructor,
344 BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly,
347 MethodBase constructor = Invocation.OverloadResolve (
348 ec, (MethodGroupExpr) mg, PosArguments, false, Location);
350 if (constructor == null)
353 ObsoleteAttribute oa = AttributeTester.GetMethodObsoleteAttribute (constructor);
354 if (oa != null && !owner.ResolveContext.IsInObsoleteScope) {
355 AttributeTester.Report_ObsoleteMessage (oa, mg.GetSignatureForError (), mg.Location);
358 if (PosArguments == null) {
359 pos_values = EmptyObject;
360 return (ConstructorInfo)constructor;
363 ParameterData pd = TypeManager.GetParameterData (constructor);
365 int pos_arg_count = PosArguments.Count;
366 int last_real_param = pd.Count;
368 pos_values = new object [pos_arg_count];
371 // When the params is not filled we need to put one
372 if (last_real_param > pos_arg_count) {
373 object [] new_pos_values = new object [pos_arg_count + 1];
374 pos_values.CopyTo (new_pos_values, 0);
375 new_pos_values [pos_arg_count] = new object [] {} ;
376 pos_values = new_pos_values;
381 for (int j = 0; j < pos_arg_count; ++j) {
382 Argument a = (Argument) PosArguments [j];
384 if (!a.Expr.GetAttributableValue (out pos_values [j]))
387 if (TypeManager.IsPrimitiveType (a.Type) && a.Type != pos_values [j].GetType ()) {
389 // This can happen only for constants in same range
390 pos_values [j] = TypeManager.ChangeType (pos_values [j], a.Type, out fail);
393 if (j < last_real_param)
396 if (j == last_real_param) {
397 object [] array = new object [pos_arg_count - last_real_param];
398 array [0] = pos_values [j];
399 pos_values [j] = array;
403 object [] params_array = (object []) pos_values [last_real_param];
404 params_array [j - last_real_param] = pos_values [j];
407 // Adjust the size of the pos_values if it had params
408 if (last_real_param != pos_arg_count) {
409 object [] new_pos_values = new object [last_real_param + 1];
410 Array.Copy (pos_values, new_pos_values, last_real_param + 1);
411 pos_values = new_pos_values;
414 // Here we do the checks which should be done by corlib or by runtime.
415 // However Zoltan doesn't like it and every Mono compiler has to do it again.
417 if (Type == TypeManager.guid_attr_type) {
419 new Guid ((string)pos_values [0]);
421 catch (Exception e) {
422 Error_AttributeEmitError (e.Message);
427 if (Type == TypeManager.attribute_usage_type && (int)pos_values [0] == 0) {
428 Report.Error (591, Location, "Invalid value for argument to 'System.AttributeUsage' attribute");
432 if (Type == TypeManager.methodimpl_attr_type && pos_values.Length == 1 &&
433 pd.ParameterType (0) == TypeManager.short_type &&
434 !System.Enum.IsDefined (typeof (MethodImplOptions), pos_values [0].ToString ())) {
435 Error_AttributeEmitError ("Incorrect argument value.");
439 return (ConstructorInfo)constructor;
442 protected virtual bool ResolveNamedArguments (EmitContext ec)
444 int named_arg_count = NamedArguments.Count;
446 ArrayList field_infos = new ArrayList (named_arg_count);
447 ArrayList prop_infos = new ArrayList (named_arg_count);
448 ArrayList field_values = new ArrayList (named_arg_count);
449 ArrayList prop_values = new ArrayList (named_arg_count);
451 ArrayList seen_names = new ArrayList(named_arg_count);
453 foreach (DictionaryEntry de in NamedArguments) {
454 string member_name = (string) de.Key;
456 if (seen_names.Contains(member_name)) {
457 Report.Error(643, Location, "'" + member_name + "' duplicate named attribute argument");
460 seen_names.Add(member_name);
462 Argument a = (Argument) de.Value;
463 if (!a.Resolve (ec, Location))
466 Expression member = Expression.MemberLookup (
467 ec.ContainerType, Type, member_name,
468 MemberTypes.Field | MemberTypes.Property,
469 BindingFlags.Public | BindingFlags.Instance,
472 if (member == null) {
473 member = Expression.MemberLookup (ec.ContainerType, Type, member_name,
474 MemberTypes.Field | MemberTypes.Property, BindingFlags.NonPublic | BindingFlags.Instance,
477 if (member != null) {
478 Expression.ErrorIsInaccesible (Location, member.GetSignatureForError ());
484 Report.Error (117, Location, "`{0}' does not contain a definition for `{1}'",
485 TypeManager.CSharpName (Type), member_name);
489 if (!(member is PropertyExpr || member is FieldExpr)) {
490 Error_InvalidNamedArgument (member_name);
494 ObsoleteAttribute obsolete_attr;
496 if (member is PropertyExpr) {
497 PropertyInfo pi = ((PropertyExpr) member).PropertyInfo;
499 if (!pi.CanWrite || !pi.CanRead) {
500 Report.SymbolRelatedToPreviousError (pi);
501 Error_InvalidNamedArgument (member_name);
505 if (!IsValidArgumentType (pi.PropertyType)) {
506 Report.SymbolRelatedToPreviousError (pi);
507 Error_InvalidNamedAgrumentType (member_name);
511 Expression e = Convert.ImplicitConversionRequired (ec, a.Expr, pi.PropertyType, a.Expr.Location);
516 if (!e.GetAttributableValue (out value))
519 PropertyBase pb = TypeManager.GetProperty (pi);
521 obsolete_attr = pb.GetObsoleteAttribute ();
523 obsolete_attr = AttributeTester.GetMemberObsoleteAttribute (pi);
525 prop_values.Add (value);
529 FieldInfo fi = ((FieldExpr) member).FieldInfo;
532 Error_InvalidNamedArgument (member_name);
536 if (!IsValidArgumentType (fi.FieldType)) {
537 Report.SymbolRelatedToPreviousError (fi);
538 Error_InvalidNamedAgrumentType (member_name);
542 Expression e = Convert.ImplicitConversionRequired (ec, a.Expr, fi.FieldType, a.Expr.Location);
547 if (!e.GetAttributableValue (out value))
550 FieldBase fb = TypeManager.GetField (fi);
552 obsolete_attr = fb.GetObsoleteAttribute ();
554 obsolete_attr = AttributeTester.GetMemberObsoleteAttribute (fi);
556 field_values.Add (value);
557 field_infos.Add (fi);
560 if (obsolete_attr != null && !owner.ResolveContext.IsInObsoleteScope)
561 AttributeTester.Report_ObsoleteMessage (obsolete_attr, member.GetSignatureForError (), member.Location);
564 prop_info_arr = new PropertyInfo [prop_infos.Count];
565 field_info_arr = new FieldInfo [field_infos.Count];
566 field_values_arr = new object [field_values.Count];
567 prop_values_arr = new object [prop_values.Count];
569 field_infos.CopyTo (field_info_arr, 0);
570 field_values.CopyTo (field_values_arr, 0);
572 prop_values.CopyTo (prop_values_arr, 0);
573 prop_infos.CopyTo (prop_info_arr, 0);
579 /// Get a string containing a list of valid targets for the attribute 'attr'
581 public string GetValidTargets ()
583 StringBuilder sb = new StringBuilder ();
584 AttributeTargets targets = GetAttributeUsage ().ValidOn;
586 if ((targets & AttributeTargets.Assembly) != 0)
587 sb.Append ("assembly, ");
589 if ((targets & AttributeTargets.Module) != 0)
590 sb.Append ("module, ");
592 if ((targets & AttributeTargets.Class) != 0)
593 sb.Append ("class, ");
595 if ((targets & AttributeTargets.Struct) != 0)
596 sb.Append ("struct, ");
598 if ((targets & AttributeTargets.Enum) != 0)
599 sb.Append ("enum, ");
601 if ((targets & AttributeTargets.Constructor) != 0)
602 sb.Append ("constructor, ");
604 if ((targets & AttributeTargets.Method) != 0)
605 sb.Append ("method, ");
607 if ((targets & AttributeTargets.Property) != 0)
608 sb.Append ("property, indexer, ");
610 if ((targets & AttributeTargets.Field) != 0)
611 sb.Append ("field, ");
613 if ((targets & AttributeTargets.Event) != 0)
614 sb.Append ("event, ");
616 if ((targets & AttributeTargets.Interface) != 0)
617 sb.Append ("interface, ");
619 if ((targets & AttributeTargets.Parameter) != 0)
620 sb.Append ("parameter, ");
622 if ((targets & AttributeTargets.Delegate) != 0)
623 sb.Append ("delegate, ");
625 if ((targets & AttributeTargets.ReturnValue) != 0)
626 sb.Append ("return, ");
629 if ((targets & AttributeTargets.GenericParameter) != 0)
630 sb.Append ("type parameter, ");
632 return sb.Remove (sb.Length - 2, 2).ToString ();
636 /// Returns AttributeUsage attribute for this type
638 AttributeUsageAttribute GetAttributeUsage ()
640 AttributeUsageAttribute ua = usage_attr_cache [Type] as AttributeUsageAttribute;
644 Class attr_class = TypeManager.LookupClass (Type);
646 if (attr_class == null) {
647 object[] usage_attr = Type.GetCustomAttributes (TypeManager.attribute_usage_type, true);
648 ua = (AttributeUsageAttribute)usage_attr [0];
649 usage_attr_cache.Add (Type, ua);
653 Attribute a = attr_class.OptAttributes == null
655 : attr_class.OptAttributes.Search (TypeManager.attribute_usage_type);
658 ? DefaultUsageAttribute
659 : a.GetAttributeUsageAttribute ();
661 usage_attr_cache.Add (Type, ua);
665 AttributeUsageAttribute GetAttributeUsageAttribute ()
667 if (pos_values == null)
668 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
669 // But because a lot of attribute class code must be rewritten will be better to wait...
673 return DefaultUsageAttribute;
675 AttributeUsageAttribute usage_attribute = new AttributeUsageAttribute ((AttributeTargets)pos_values [0]);
677 object field = GetPropertyValue ("AllowMultiple");
679 usage_attribute.AllowMultiple = (bool)field;
681 field = GetPropertyValue ("Inherited");
683 usage_attribute.Inherited = (bool)field;
685 return usage_attribute;
689 /// Returns custom name of indexer
691 public string GetIndexerAttributeValue ()
693 if (pos_values == null)
694 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
695 // But because a lot of attribute class code must be rewritten will be better to wait...
701 return pos_values [0] as string;
705 /// Returns condition of ConditionalAttribute
707 public string GetConditionalAttributeValue ()
709 if (pos_values == null)
710 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
711 // But because a lot of attribute class code must be rewritten will be better to wait...
717 return (string)pos_values [0];
721 /// Creates the instance of ObsoleteAttribute from this attribute instance
723 public ObsoleteAttribute GetObsoleteAttribute ()
725 if (pos_values == null)
726 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
727 // But because a lot of attribute class code must be rewritten will be better to wait...
733 if (pos_values == null || pos_values.Length == 0)
734 return new ObsoleteAttribute ();
736 if (pos_values.Length == 1)
737 return new ObsoleteAttribute ((string)pos_values [0]);
739 return new ObsoleteAttribute ((string)pos_values [0], (bool)pos_values [1]);
743 /// Returns value of CLSCompliantAttribute contructor parameter but because the method can be called
744 /// before ApplyAttribute. We need to resolve the arguments.
745 /// This situation occurs when class deps is differs from Emit order.
747 public bool GetClsCompliantAttributeValue ()
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 (bool)pos_values [0];
760 public Type GetCoClassAttributeValue ()
762 if (pos_values == null)
768 return (Type)pos_values [0];
771 public bool CheckTarget ()
773 string[] valid_targets = owner.ValidAttributeTargets;
774 if (ExplicitTarget == null || ExplicitTarget == valid_targets [0]) {
775 Target = owner.AttributeTargets;
779 // TODO: we can skip the first item
780 if (((IList) valid_targets).Contains (ExplicitTarget)) {
781 switch (ExplicitTarget) {
782 case "return": Target = AttributeTargets.ReturnValue; return true;
783 case "param": Target = AttributeTargets.Parameter; return true;
784 case "field": Target = AttributeTargets.Field; return true;
785 case "method": Target = AttributeTargets.Method; return true;
786 case "property": Target = AttributeTargets.Property; return true;
788 throw new InternalErrorException ("Unknown explicit target: " + ExplicitTarget);
791 StringBuilder sb = new StringBuilder ();
792 foreach (string s in valid_targets) {
796 sb.Remove (sb.Length - 2, 2);
797 Report.Error (657, Location, "`{0}' is not a valid attribute location for this declaration. " +
798 "Valid attribute locations for this declaration are `{1}'", ExplicitTarget, sb.ToString ());
803 /// Tests permitted SecurityAction for assembly or other types
805 public bool CheckSecurityActionValidity (bool for_assembly)
807 SecurityAction action = GetSecurityActionValue ();
809 if ((action == SecurityAction.RequestMinimum || action == SecurityAction.RequestOptional ||
810 action == SecurityAction.RequestRefuse) && for_assembly)
814 if (action < SecurityAction.Demand || action > SecurityAction.InheritanceDemand) {
815 Error_AttributeEmitError ("SecurityAction is out of range");
819 if ((action != SecurityAction.RequestMinimum && action != SecurityAction.RequestOptional &&
820 action != SecurityAction.RequestRefuse) && !for_assembly)
824 Error_AttributeEmitError (String.Concat ("SecurityAction `", action, "' is not valid for this declaration"));
828 System.Security.Permissions.SecurityAction GetSecurityActionValue ()
830 return (SecurityAction)pos_values [0];
834 /// Creates instance of SecurityAttribute class and add result of CreatePermission method to permission table.
836 /// <returns></returns>
837 public void ExtractSecurityPermissionSet (ListDictionary permissions)
839 Type orig_assembly_type = null;
841 if (TypeManager.LookupDeclSpace (Type) != null) {
842 if (!RootContext.StdLib) {
843 orig_assembly_type = Type.GetType (Type.FullName);
845 string orig_version_path = Environment.GetEnvironmentVariable ("__SECURITY_BOOTSTRAP_DB");
846 if (orig_version_path == null) {
847 Error_AttributeEmitError ("security custom attributes can not be referenced from defining assembly");
851 if (orig_sec_assembly == null) {
852 string file = Path.Combine (orig_version_path, Driver.OutputFile);
853 orig_sec_assembly = Assembly.LoadFile (file);
856 orig_assembly_type = orig_sec_assembly.GetType (Type.FullName, true);
857 if (orig_assembly_type == null) {
858 Report.Warning (-112, 1, Location, "Self-referenced security attribute `{0}' " +
859 "was not found in previous version of assembly");
865 SecurityAttribute sa;
866 // For all non-selfreferencing security attributes we can avoid all hacks
867 if (orig_assembly_type == null) {
868 sa = (SecurityAttribute) Activator.CreateInstance (Type, pos_values);
870 if (prop_info_arr != null) {
871 for (int i = 0; i < prop_info_arr.Length; ++i) {
872 PropertyInfo pi = prop_info_arr [i];
873 pi.SetValue (sa, prop_values_arr [i], null);
877 // HACK: All security attributes have same ctor syntax
878 sa = (SecurityAttribute) Activator.CreateInstance (orig_assembly_type, new object[] { GetSecurityActionValue () } );
880 // All types are from newly created assembly but for invocation with old one we need to convert them
881 if (prop_info_arr != null) {
882 for (int i = 0; i < prop_info_arr.Length; ++i) {
883 PropertyInfo emited_pi = prop_info_arr [i];
884 PropertyInfo pi = orig_assembly_type.GetProperty (emited_pi.Name, emited_pi.PropertyType);
886 object old_instance = pi.PropertyType.IsEnum ?
887 System.Enum.ToObject (pi.PropertyType, prop_values_arr [i]) :
890 pi.SetValue (sa, old_instance, null);
896 perm = sa.CreatePermission ();
897 SecurityAction action = GetSecurityActionValue ();
899 // IS is correct because for corlib we are using an instance from old corlib
900 if (!(perm is System.Security.CodeAccessPermission)) {
902 case SecurityAction.Demand:
903 action = (SecurityAction)13;
905 case SecurityAction.LinkDemand:
906 action = (SecurityAction)14;
908 case SecurityAction.InheritanceDemand:
909 action = (SecurityAction)15;
914 PermissionSet ps = (PermissionSet)permissions [action];
916 if (sa is PermissionSetAttribute)
917 ps = new PermissionSet (sa.Unrestricted ? PermissionState.Unrestricted : PermissionState.None);
919 ps = new PermissionSet (PermissionState.None);
921 permissions.Add (action, ps);
922 } else if (!ps.IsUnrestricted () && (sa is PermissionSetAttribute) && sa.Unrestricted) {
923 ps = ps.Union (new PermissionSet (PermissionState.Unrestricted));
924 permissions [action] = ps;
926 ps.AddPermission (perm);
929 static object GetValue (object value)
931 if (value is EnumConstant)
932 return ((EnumConstant) value).GetValue ();
937 public object GetPropertyValue (string name)
939 if (prop_info_arr == null)
942 for (int i = 0; i < prop_info_arr.Length; ++i) {
943 if (prop_info_arr [i].Name == name)
944 return prop_values_arr [i];
950 object GetFieldValue (string name)
953 if (field_info_arr == null)
956 foreach (FieldInfo fi in field_info_arr) {
958 return GetValue (field_values_arr [i]);
965 // Theoretically, we can get rid of this, since FieldBuilder.SetCustomAttribute()
966 // and ParameterBuilder.SetCustomAttribute() are supposed to handle this attribute.
967 // However, we can't, since it appears that the .NET 1.1 SRE hangs when given a MarshalAsAttribute.
969 public UnmanagedMarshal GetMarshal (Attributable attr)
971 UnmanagedType UnmanagedType;
972 if (!RootContext.StdLib || pos_values [0].GetType () != typeof (UnmanagedType))
973 UnmanagedType = (UnmanagedType) System.Enum.ToObject (typeof (UnmanagedType), pos_values [0]);
975 UnmanagedType = (UnmanagedType) pos_values [0];
977 object value = GetFieldValue ("SizeParamIndex");
978 if (value != null && UnmanagedType != UnmanagedType.LPArray) {
979 Error_AttributeEmitError ("SizeParamIndex field is not valid for the specified unmanaged type");
983 object o = GetFieldValue ("ArraySubType");
984 UnmanagedType array_sub_type = o == null ? (UnmanagedType) 0x50 /* NATIVE_MAX */ : (UnmanagedType) o;
986 switch (UnmanagedType) {
987 case UnmanagedType.CustomMarshaler: {
988 MethodInfo define_custom = typeof (UnmanagedMarshal).GetMethod ("DefineCustom",
989 BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
990 if (define_custom == null) {
991 Report.RuntimeMissingSupport (Location, "set marshal info");
995 object [] args = new object [4];
996 args [0] = GetFieldValue ("MarshalTypeRef");
997 args [1] = GetFieldValue ("MarshalCookie");
998 args [2] = GetFieldValue ("MarshalType");
999 args [3] = Guid.Empty;
1000 return (UnmanagedMarshal) define_custom.Invoke (null, args);
1002 case UnmanagedType.LPArray: {
1003 object size_const = GetFieldValue ("SizeConst");
1004 object size_param_index = GetFieldValue ("SizeParamIndex");
1006 if ((size_const != null) || (size_param_index != null)) {
1007 MethodInfo define_array = typeof (UnmanagedMarshal).GetMethod ("DefineLPArrayInternal",
1008 BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
1009 if (define_array == null) {
1010 Report.RuntimeMissingSupport (Location, "set marshal info");
1014 object [] args = new object [3];
1015 args [0] = array_sub_type;
1016 args [1] = size_const == null ? -1 : size_const;
1017 args [2] = size_param_index == null ? -1 : size_param_index;
1018 return (UnmanagedMarshal) define_array.Invoke (null, args);
1021 return UnmanagedMarshal.DefineLPArray (array_sub_type);
1023 case UnmanagedType.SafeArray:
1024 return UnmanagedMarshal.DefineSafeArray (array_sub_type);
1026 case UnmanagedType.ByValArray:
1027 FieldMember fm = attr as FieldMember;
1029 Error_AttributeEmitError ("Specified unmanaged type is only valid on fields");
1032 return UnmanagedMarshal.DefineByValArray ((int) GetFieldValue ("SizeConst"));
1034 case UnmanagedType.ByValTStr:
1035 return UnmanagedMarshal.DefineByValTStr ((int) GetFieldValue ("SizeConst"));
1038 return UnmanagedMarshal.DefineUnmanagedMarshal (UnmanagedType);
1042 public CharSet GetCharSetValue ()
1044 return (CharSet)System.Enum.Parse (typeof (CharSet), pos_values [0].ToString ());
1047 public MethodImplOptions GetMethodImplOptions ()
1049 if (pos_values [0].GetType () != typeof (MethodImplOptions))
1050 return (MethodImplOptions)System.Enum.ToObject (typeof (MethodImplOptions), pos_values [0]);
1051 return (MethodImplOptions)pos_values [0];
1054 public LayoutKind GetLayoutKindValue ()
1056 if (!RootContext.StdLib || pos_values [0].GetType () != typeof (LayoutKind))
1057 return (LayoutKind)System.Enum.ToObject (typeof (LayoutKind), pos_values [0]);
1059 return (LayoutKind)pos_values [0];
1062 public override bool Equals (object obj)
1064 Attribute a = obj as Attribute;
1068 return Type == a.Type && Target == a.Target;
1071 public override int GetHashCode ()
1073 return base.GetHashCode ();
1076 public object GetParameterDefaultValue ()
1078 return pos_values [0];
1082 /// Emit attribute for Attributable symbol
1084 public void Emit (ListDictionary allEmitted)
1086 CustomAttributeBuilder cb = Resolve ();
1090 AttributeUsageAttribute usage_attr = GetAttributeUsage ();
1091 if ((usage_attr.ValidOn & Target) == 0) {
1092 Report.Error (592, Location, "The attribute `{0}' is not valid on this declaration type. " +
1093 "It is valid on `{1}' declarations only",
1094 GetSignatureForError (), GetValidTargets ());
1099 owner.ApplyAttributeBuilder (this, cb);
1101 catch (Exception e) {
1102 Error_AttributeEmitError (e.Message);
1106 if (!usage_attr.AllowMultiple && allEmitted != null) {
1107 if (allEmitted.Contains (this)) {
1108 ArrayList a = allEmitted [this] as ArrayList;
1110 a = new ArrayList (2);
1111 allEmitted [this] = a;
1115 allEmitted.Add (this, null);
1119 if (!RootContext.VerifyClsCompliance)
1122 // Here we are testing attribute arguments for array usage (error 3016)
1123 if (owner.IsClsComplianceRequired ()) {
1124 if (PosArguments != null) {
1125 foreach (Argument arg in PosArguments) {
1126 // Type is undefined (was error 246)
1127 if (arg.Type == null)
1130 if (arg.Type.IsArray) {
1131 Report.Error (3016, Location, "Arrays as attribute arguments are not CLS-compliant");
1137 if (NamedArguments == null)
1140 foreach (DictionaryEntry de in NamedArguments) {
1141 Argument arg = (Argument) de.Value;
1143 // Type is undefined (was error 246)
1144 if (arg.Type == null)
1147 if (arg.Type.IsArray) {
1148 Report.Error (3016, Location, "Arrays as attribute arguments are not CLS-compliant");
1155 public MethodBuilder DefinePInvokeMethod (TypeBuilder builder, string name,
1156 MethodAttributes flags, Type ret_type, Type [] param_types)
1158 if (pos_values == null)
1159 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
1160 // But because a lot of attribute class code must be rewritten will be better to wait...
1166 string dll_name = (string)pos_values [0];
1169 CallingConvention cc = CallingConvention.Winapi;
1170 CharSet charset = CodeGen.Module.DefaultCharSet;
1171 bool preserve_sig = true;
1172 string entry_point = name;
1173 bool best_fit_mapping = false;
1174 bool throw_on_unmappable = false;
1175 bool exact_spelling = false;
1176 bool set_last_error = false;
1178 bool best_fit_mapping_set = false;
1179 bool throw_on_unmappable_set = false;
1180 bool exact_spelling_set = false;
1181 bool set_last_error_set = false;
1183 MethodInfo set_best_fit = null;
1184 MethodInfo set_throw_on = null;
1185 MethodInfo set_exact_spelling = null;
1186 MethodInfo set_set_last_error = null;
1188 if (field_info_arr != null) {
1190 for (int i = 0; i < field_info_arr.Length; i++) {
1191 switch (field_info_arr [i].Name) {
1192 case "BestFitMapping":
1193 best_fit_mapping = (bool) field_values_arr [i];
1194 best_fit_mapping_set = true;
1196 case "CallingConvention":
1197 cc = (CallingConvention) field_values_arr [i];
1200 charset = (CharSet) field_values_arr [i];
1203 entry_point = (string) field_values_arr [i];
1205 case "ExactSpelling":
1206 exact_spelling = (bool) field_values_arr [i];
1207 exact_spelling_set = true;
1210 preserve_sig = (bool) field_values_arr [i];
1212 case "SetLastError":
1213 set_last_error = (bool) field_values_arr [i];
1214 set_last_error_set = true;
1216 case "ThrowOnUnmappableChar":
1217 throw_on_unmappable = (bool) field_values_arr [i];
1218 throw_on_unmappable_set = true;
1221 throw new InternalErrorException (field_info_arr [i].ToString ());
1226 if (throw_on_unmappable_set || best_fit_mapping_set || exact_spelling_set || set_last_error_set) {
1227 set_best_fit = typeof (MethodBuilder).
1228 GetMethod ("set_BestFitMapping", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
1229 set_throw_on = typeof (MethodBuilder).
1230 GetMethod ("set_ThrowOnUnmappableChar", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
1231 set_exact_spelling = typeof (MethodBuilder).
1232 GetMethod ("set_ExactSpelling", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
1233 set_set_last_error = typeof (MethodBuilder).
1234 GetMethod ("set_SetLastError", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
1236 if ((set_best_fit == null) || (set_throw_on == null) ||
1237 (set_exact_spelling == null) || (set_set_last_error == null)) {
1238 Report.Error (-1, Location,
1239 "The ThrowOnUnmappableChar, BestFitMapping, SetLastError, " +
1240 "and ExactSpelling attributes can only be emitted when running on the mono runtime.");
1246 MethodBuilder mb = builder.DefinePInvokeMethod (
1247 name, dll_name, entry_point, flags | MethodAttributes.HideBySig | MethodAttributes.PinvokeImpl,
1248 CallingConventions.Standard, ret_type, param_types, cc, charset);
1251 mb.SetImplementationFlags (MethodImplAttributes.PreserveSig);
1253 if (throw_on_unmappable_set)
1254 set_throw_on.Invoke (mb, 0, null, new object [] { throw_on_unmappable }, null);
1255 if (best_fit_mapping_set)
1256 set_best_fit.Invoke (mb, 0, null, new object [] { best_fit_mapping }, null);
1257 if (exact_spelling_set)
1258 set_exact_spelling.Invoke (mb, 0, null, new object [] { exact_spelling }, null);
1259 if (set_last_error_set)
1260 set_set_last_error.Invoke (mb, 0, null, new object [] { set_last_error }, null);
1264 catch (ArgumentException e) {
1265 Error_AttributeEmitError (e.Message);
1270 private Expression GetValue ()
1272 if (PosArguments == null || PosArguments.Count < 1)
1275 return ((Argument) PosArguments [0]).Expr;
1278 public string GetString ()
1280 Expression e = GetValue ();
1281 if (e is StringLiteral)
1282 return (e as StringLiteral).Value;
1286 public bool GetBoolean ()
1288 Expression e = GetValue ();
1289 if (e is BoolLiteral)
1290 return (e as BoolLiteral).Value;
1297 /// For global attributes (assembly, module) we need special handling.
1298 /// Attributes can be located in the several files
1300 public class GlobalAttribute : Attribute
1302 public readonly NamespaceEntry ns;
1304 public GlobalAttribute (NamespaceEntry ns, string target,
1305 Expression left_expr, string identifier, object[] args, Location loc, bool nameEscaped):
1306 base (target, left_expr, identifier, args, loc, nameEscaped)
1313 // RootContext.Tree.Types has a single NamespaceEntry which gets overwritten
1314 // each time a new file is parsed. However, we need to use the NamespaceEntry
1315 // in effect where the attribute was used. Since code elsewhere cannot assume
1316 // that the NamespaceEntry is right, just overwrite it.
1318 // Precondition: RootContext.Tree.Types == null
1320 if (RootContext.Tree.Types.NamespaceEntry != null)
1321 throw new InternalErrorException (Location + " non-null NamespaceEntry");
1323 RootContext.Tree.Types.NamespaceEntry = ns;
1328 RootContext.Tree.Types.NamespaceEntry = null;
1331 protected override TypeExpr ResolveAsTypeTerminal (Expression expr, IResolveContext ec, bool silent)
1335 return base.ResolveAsTypeTerminal (expr, ec, silent);
1342 protected override ConstructorInfo ResolveConstructor (EmitContext ec)
1346 return base.ResolveConstructor (ec);
1353 protected override bool ResolveNamedArguments (EmitContext ec)
1357 return base.ResolveNamedArguments (ec);
1365 public class Attributes {
1366 public readonly ArrayList Attrs;
1368 public Attributes (Attribute a)
1370 Attrs = new ArrayList ();
1374 public Attributes (ArrayList attrs)
1379 public void AddAttributes (ArrayList attrs)
1381 Attrs.AddRange (attrs);
1384 public void AttachTo (Attributable attributable)
1386 foreach (Attribute a in Attrs)
1387 a.AttachTo (attributable);
1391 /// Checks whether attribute target is valid for the current element
1393 public bool CheckTargets ()
1395 foreach (Attribute a in Attrs) {
1396 if (!a.CheckTarget ())
1402 public Attribute Search (Type t)
1404 foreach (Attribute a in Attrs) {
1405 if (a.ResolveType () == t)
1412 /// Returns all attributes of type 't'. Use it when attribute is AllowMultiple = true
1414 public Attribute[] SearchMulti (Type t)
1416 ArrayList ar = null;
1418 foreach (Attribute a in Attrs) {
1419 if (a.ResolveType () == t) {
1421 ar = new ArrayList ();
1426 return ar == null ? null : ar.ToArray (typeof (Attribute)) as Attribute[];
1433 ListDictionary ld = Attrs.Count > 1 ? new ListDictionary () : null;
1435 foreach (Attribute a in Attrs)
1438 if (ld == null || ld.Count == 0)
1441 foreach (DictionaryEntry d in ld) {
1442 if (d.Value == null)
1445 foreach (Attribute collision in (ArrayList)d.Value)
1446 Report.SymbolRelatedToPreviousError (collision.Location, "");
1448 Attribute a = (Attribute)d.Key;
1449 Report.Error (579, a.Location, "The attribute `{0}' cannot be applied multiple times", a.GetSignatureForError ());
1453 public bool Contains (Type t)
1455 return Search (t) != null;
1460 /// Helper class for attribute verification routine.
1462 sealed class AttributeTester
1464 static PtrHashtable analyzed_types = new PtrHashtable ();
1465 static PtrHashtable analyzed_types_obsolete = new PtrHashtable ();
1466 static PtrHashtable analyzed_member_obsolete = new PtrHashtable ();
1467 static PtrHashtable analyzed_method_excluded = new PtrHashtable ();
1470 static PtrHashtable fixed_buffer_cache = new PtrHashtable ();
1473 static object TRUE = new object ();
1474 static object FALSE = new object ();
1476 private AttributeTester ()
1480 public enum Result {
1487 /// Returns true if parameters of two compared methods are CLS-Compliant.
1488 /// It tests differing only in ref or out, or in array rank.
1490 public static Result AreOverloadedMethodParamsClsCompliant (Type[] types_a, Type[] types_b)
1492 if (types_a == null || types_b == null)
1495 if (types_a.Length != types_b.Length)
1498 Result result = Result.Ok;
1499 for (int i = 0; i < types_b.Length; ++i) {
1500 Type aType = types_a [i];
1501 Type bType = types_b [i];
1503 if (aType.IsArray && bType.IsArray) {
1504 Type a_el_type = aType.GetElementType ();
1505 Type b_el_type = bType.GetElementType ();
1506 if (aType.GetArrayRank () != bType.GetArrayRank () && a_el_type == b_el_type) {
1507 result = Result.RefOutArrayError;
1511 if (a_el_type.IsArray || b_el_type.IsArray) {
1512 result = Result.ArrayArrayError;
1517 Type aBaseType = aType;
1518 bool is_either_ref_or_out = false;
1520 if (aType.IsByRef || aType.IsPointer) {
1521 aBaseType = aType.GetElementType ();
1522 is_either_ref_or_out = true;
1525 Type bBaseType = bType;
1526 if (bType.IsByRef || bType.IsPointer)
1528 bBaseType = bType.GetElementType ();
1529 is_either_ref_or_out = !is_either_ref_or_out;
1532 if (aBaseType != bBaseType)
1535 if (is_either_ref_or_out)
1536 result = Result.RefOutArrayError;
1542 /// This method tests the CLS compliance of external types. It doesn't test type visibility.
1544 public static bool IsClsCompliant (Type type)
1549 object type_compliance = analyzed_types[type];
1550 if (type_compliance != null)
1551 return type_compliance == TRUE;
1553 if (type.IsPointer) {
1554 analyzed_types.Add (type, null);
1559 if (type.IsArray || type.IsByRef) {
1560 result = IsClsCompliant (TypeManager.GetElementType (type));
1562 result = AnalyzeTypeCompliance (type);
1564 analyzed_types.Add (type, result ? TRUE : FALSE);
1569 /// Returns IFixedBuffer implementation if field is fixed buffer else null.
1571 public static IFixedBuffer GetFixedBuffer (FieldInfo fi)
1573 FieldBase fb = TypeManager.GetField (fi);
1575 return fb as IFixedBuffer;
1579 object o = fixed_buffer_cache [fi];
1581 if (System.Attribute.GetCustomAttribute (fi, TypeManager.fixed_buffer_attr_type) == null) {
1582 fixed_buffer_cache.Add (fi, FALSE);
1586 IFixedBuffer iff = new FixedFieldExternal (fi);
1587 fixed_buffer_cache.Add (fi, iff);
1594 return (IFixedBuffer)o;
1600 public static void VerifyModulesClsCompliance ()
1602 Module[] modules = RootNamespace.Global.Modules;
1603 if (modules == null)
1606 // The first module is generated assembly
1607 for (int i = 1; i < modules.Length; ++i) {
1608 Module module = modules [i];
1609 if (!IsClsCompliant (module)) {
1610 Report.Error (3013, "Added modules must be marked with the CLSCompliant attribute " +
1611 "to match the assembly", module.Name);
1617 public static Type GetImportedIgnoreCaseClsType (string name)
1619 foreach (Assembly a in RootNamespace.Global.Assemblies) {
1620 Type t = a.GetType (name, false, true);
1624 if (IsClsCompliant (t))
1630 static bool IsClsCompliant (ICustomAttributeProvider attribute_provider)
1632 object[] CompliantAttribute = attribute_provider.GetCustomAttributes (TypeManager.cls_compliant_attribute_type, false);
1633 if (CompliantAttribute.Length == 0)
1636 return ((CLSCompliantAttribute)CompliantAttribute[0]).IsCompliant;
1639 static bool AnalyzeTypeCompliance (Type type)
1641 DeclSpace ds = TypeManager.LookupDeclSpace (type);
1643 return ds.IsClsComplianceRequired ();
1646 object[] CompliantAttribute = type.GetCustomAttributes (TypeManager.cls_compliant_attribute_type, false);
1647 if (CompliantAttribute.Length == 0)
1648 return IsClsCompliant (type.Assembly);
1650 return ((CLSCompliantAttribute)CompliantAttribute[0]).IsCompliant;
1654 /// Returns instance of ObsoleteAttribute when type is obsolete
1656 public static ObsoleteAttribute GetObsoleteAttribute (Type type)
1658 object type_obsolete = analyzed_types_obsolete [type];
1659 if (type_obsolete == FALSE)
1662 if (type_obsolete != null)
1663 return (ObsoleteAttribute)type_obsolete;
1665 ObsoleteAttribute result = null;
1666 if (type.IsByRef || type.IsArray || type.IsPointer) {
1667 result = GetObsoleteAttribute (TypeManager.GetElementType (type));
1669 DeclSpace type_ds = TypeManager.LookupDeclSpace (type);
1671 // Type is external, we can get attribute directly
1672 if (type_ds == null) {
1673 object[] attribute = type.GetCustomAttributes (TypeManager.obsolete_attribute_type, false);
1674 if (attribute.Length == 1)
1675 result = (ObsoleteAttribute)attribute [0];
1677 // Is null during corlib bootstrap
1678 if (TypeManager.obsolete_attribute_type != null)
1679 result = type_ds.GetObsoleteAttribute ();
1683 // Cannot use .Add because of corlib bootstrap
1684 analyzed_types_obsolete [type] = result == null ? FALSE : result;
1689 /// Returns instance of ObsoleteAttribute when method is obsolete
1691 public static ObsoleteAttribute GetMethodObsoleteAttribute (MethodBase mb)
1693 IMethodData mc = TypeManager.GetMethod (mb);
1695 return mc.GetObsoleteAttribute ();
1697 // compiler generated methods are not registered by AddMethod
1698 if (mb.DeclaringType is TypeBuilder)
1701 if (mb.IsSpecialName) {
1702 PropertyInfo pi = PropertyExpr.AccessorTable [mb] as PropertyInfo;
1704 // FIXME: This is buggy as properties from this assembly are included as well
1706 //return GetMemberObsoleteAttribute (pi);
1710 return GetMemberObsoleteAttribute (mb);
1714 /// Returns instance of ObsoleteAttribute when member is obsolete
1716 public static ObsoleteAttribute GetMemberObsoleteAttribute (MemberInfo mi)
1718 object type_obsolete = analyzed_member_obsolete [mi];
1719 if (type_obsolete == FALSE)
1722 if (type_obsolete != null)
1723 return (ObsoleteAttribute)type_obsolete;
1725 ObsoleteAttribute oa = System.Attribute.GetCustomAttribute (mi, TypeManager.obsolete_attribute_type, false)
1726 as ObsoleteAttribute;
1727 analyzed_member_obsolete.Add (mi, oa == null ? FALSE : oa);
1732 /// Common method for Obsolete error/warning reporting.
1734 public static void Report_ObsoleteMessage (ObsoleteAttribute oa, string member, Location loc)
1737 Report.Error (619, loc, "`{0}' is obsolete: `{1}'", member, oa.Message);
1741 if (oa.Message == null) {
1742 Report.Warning (612, 1, loc, "`{0}' is obsolete", member);
1745 Report.Warning (618, 2, loc, "`{0}' is obsolete: `{1}'", member, oa.Message);
1748 public static bool IsConditionalMethodExcluded (MethodBase mb)
1750 object excluded = analyzed_method_excluded [mb];
1751 if (excluded != null)
1752 return excluded == TRUE ? true : false;
1754 ConditionalAttribute[] attrs = mb.GetCustomAttributes (TypeManager.conditional_attribute_type, true)
1755 as ConditionalAttribute[];
1756 if (attrs.Length == 0) {
1757 analyzed_method_excluded.Add (mb, FALSE);
1761 foreach (ConditionalAttribute a in attrs) {
1762 if (RootContext.AllDefines.Contains (a.ConditionString)) {
1763 analyzed_method_excluded.Add (mb, FALSE);
1767 analyzed_method_excluded.Add (mb, TRUE);
1772 /// Analyzes class whether it has attribute which has ConditionalAttribute
1773 /// and its condition is not defined.
1775 public static bool IsAttributeExcluded (Type type)
1780 Class class_decl = TypeManager.LookupDeclSpace (type) as Class;
1782 // TODO: add caching
1783 // TODO: merge all Type bases attribute caching to one cache to save memory
1784 if (class_decl == null) {
1785 object[] attributes = type.GetCustomAttributes (TypeManager.conditional_attribute_type, false);
1786 foreach (ConditionalAttribute ca in attributes) {
1787 if (RootContext.AllDefines.Contains (ca.ConditionString))
1790 return attributes.Length > 0;
1793 return class_decl.IsExcluded ();
1796 public static Type GetCoClassAttribute (Type type)
1798 TypeContainer tc = TypeManager.LookupInterface (type);
1800 object[] o = type.GetCustomAttributes (TypeManager.coclass_attr_type, false);
1803 return ((System.Runtime.InteropServices.CoClassAttribute)o[0]).CoClass;
1806 if (tc.OptAttributes == null)
1809 Attribute a = tc.OptAttributes.Search (TypeManager.coclass_attr_type);
1813 return a.GetCoClassAttributeValue ();