2 // attribute.cs: Attribute Handler
4 // Author: Ravi Pratap (ravi@ximian.com)
5 // Marek Safar (marek.safar@seznam.cz)
7 // Dual licensed under the terms of the MIT X11 or GNU GPL
9 // Copyright 2001-2003 Ximian, Inc (http://www.ximian.com)
10 // Copyright 2003-2008 Novell, Inc.
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)
40 OptAttributes = attrs;
43 public Attributes OptAttributes
51 if (attributes != null) {
52 attributes.AttachTo (this);
58 /// Use member-specific procedure to apply attribute @a in @cb to the entity being built in @builder
60 public abstract void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb);
63 /// Returns one AttributeTarget for this element.
65 public abstract AttributeTargets AttributeTargets { get; }
67 public abstract IResolveContext ResolveContext { get; }
69 public abstract bool IsClsComplianceRequired ();
72 /// Gets list of valid attribute targets for explicit target declaration.
73 /// The first array item is default target. Don't break this rule.
75 public abstract string[] ValidAttributeTargets { get; }
78 public class Attribute : Expression
80 public readonly string ExplicitTarget;
81 public AttributeTargets Target;
83 // TODO: remove this member
84 public readonly string Name;
85 public readonly Expression LeftExpr;
86 public readonly string Identifier;
88 ArrayList PosArguments;
89 ArrayList NamedArguments;
92 readonly bool nameEscaped;
94 // It can contain more onwers when the attribute is applied to multiple fiels.
95 protected Attributable[] owners;
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;
109 // Cache for parameter-less attributes
110 static PtrHashtable att_cache;
112 public Attribute (string target, Expression left_expr, string identifier, object[] args, Location loc, bool nameEscaped)
114 LeftExpr = left_expr;
115 Identifier = identifier;
116 Name = LeftExpr == null ? identifier : LeftExpr + "." + identifier;
118 PosArguments = (ArrayList)args [0];
119 NamedArguments = (ArrayList)args [1];
122 ExplicitTarget = target;
123 this.nameEscaped = nameEscaped;
126 public Attribute Clone ()
128 Attribute a = new Attribute (ExplicitTarget, LeftExpr, Identifier, null, loc, nameEscaped);
129 a.PosArguments = PosArguments;
130 a.NamedArguments = NamedArguments;
139 public static void Reset ()
141 usage_attr_cache = new PtrHashtable ();
142 att_cache = new PtrHashtable ();
145 public virtual void AttachTo (Attributable owner)
147 if (this.owners == null) {
148 this.owners = new Attributable[1] { owner };
152 // When the same attribute is attached to multiple fiels
153 // we use this extra_owners as a list of owners. The attribute
154 // then can be removed because will be emitted when first owner
156 Attributable[] new_array = new Attributable [this.owners.Length + 1];
157 owners.CopyTo (new_array, 0);
158 new_array [owners.Length] = owner;
159 this.owners = new_array;
160 owner.OptAttributes = null;
163 void Error_InvalidNamedArgument (string name)
165 Report.Error (617, Location, "`{0}' is not a valid named attribute argument. Named attribute arguments " +
166 "must be fields which are not readonly, static, const or read-write properties which are " +
167 "public and not static",
171 void Error_InvalidNamedAgrumentType (string name)
173 Report.Error (655, Location, "`{0}' is not a valid named attribute argument because it is not a valid " +
174 "attribute parameter type", name);
177 public static void Error_AttributeArgumentNotValid (Location loc)
179 Report.Error (182, loc,
180 "An attribute argument must be a constant expression, typeof " +
181 "expression or array creation expression");
184 static void Error_TypeParameterInAttribute (Location loc)
187 -202, loc, "Can not use a type parameter in an attribute");
190 public void Error_MissingGuidAttribute ()
192 Report.Error (596, Location, "The Guid attribute must be specified with the ComImport attribute");
195 public void Error_MisusedExtensionAttribute ()
197 Report.Error (1112, Location, "Do not use `{0}' directly. Use parameter modifier `this' instead", GetSignatureForError ());
201 /// This is rather hack. We report many emit attribute error with same error to be compatible with
202 /// csc. But because csc has to report them this way because error came from ilasm we needn't.
204 public void Error_AttributeEmitError (string inner)
206 Report.Error (647, Location, "Error during emitting `{0}' attribute. The reason is `{1}'",
207 TypeManager.CSharpName (Type), inner);
210 public void Error_InvalidSecurityParent ()
212 Error_AttributeEmitError ("it is attached to invalid parent");
221 protected virtual TypeExpr ResolveAsTypeTerminal (Expression expr, IResolveContext ec, bool silent)
223 return expr.ResolveAsTypeTerminal (ec, silent);
226 Type ResolvePossibleAttributeType (string name, bool silent, ref bool is_attr)
228 IResolveContext rc = Owner.ResolveContext;
231 if (LeftExpr == null) {
232 te = ResolveAsTypeTerminal (new SimpleName (name, Location), rc, silent);
234 te = ResolveAsTypeTerminal (new MemberAccess (LeftExpr, name), rc, silent);
241 if (TypeManager.IsSubclassOf (t, TypeManager.attribute_type)) {
243 } else if (!silent) {
244 Report.SymbolRelatedToPreviousError (t);
245 Report.Error (616, Location, "`{0}': is not an attribute class", TypeManager.CSharpName (t));
251 /// Tries to resolve the type of the attribute. Flags an error if it can't, and complain is true.
253 void ResolveAttributeType ()
255 bool t1_is_attr = false;
256 Type t1 = ResolvePossibleAttributeType (Identifier, true, ref t1_is_attr);
258 bool t2_is_attr = false;
259 Type t2 = nameEscaped ? null :
260 ResolvePossibleAttributeType (Identifier + "Attribute", true, ref t2_is_attr);
262 if (t1_is_attr && t2_is_attr) {
263 Report.Error (1614, Location, "`{0}' is ambiguous between `{0}' and `{0}Attribute'. " +
264 "Use either `@{0}' or `{0}Attribute'", GetSignatureForError ());
265 resolve_error = true;
279 if (t1 == null && t2 == null)
280 ResolvePossibleAttributeType (Identifier, false, ref t1_is_attr);
282 ResolvePossibleAttributeType (Identifier, false, ref t1_is_attr);
284 ResolvePossibleAttributeType (Identifier + "Attribute", false, ref t2_is_attr);
286 resolve_error = true;
289 public virtual Type ResolveType ()
291 if (Type == null && !resolve_error)
292 ResolveAttributeType ();
296 public override string GetSignatureForError ()
299 return TypeManager.CSharpName (Type);
301 return LeftExpr == null ? Identifier : LeftExpr.GetSignatureForError () + "." + Identifier;
304 public bool HasSecurityAttribute {
306 return TypeManager.security_attr_type != null &&
307 TypeManager.IsSubclassOf (type, TypeManager.security_attr_type);
311 public bool IsValidSecurityAttribute ()
313 return HasSecurityAttribute && IsSecurityActionValid (false);
316 static bool IsValidArgumentType (Type t)
319 t = TypeManager.GetElementType (t);
321 return t == TypeManager.string_type ||
322 TypeManager.IsPrimitiveType (t) ||
323 TypeManager.IsEnumType (t) ||
324 t == TypeManager.object_type ||
325 t == TypeManager.type_type;
328 [Conditional ("GMCS_SOURCE")]
329 void ApplyModuleCharSet ()
331 if (Type != TypeManager.dllimport_type)
334 if (!CodeGen.Module.HasDefaultCharSet)
337 const string CharSetEnumMember = "CharSet";
338 if (NamedArguments == null) {
339 NamedArguments = new ArrayList (1);
341 foreach (DictionaryEntry de in NamedArguments) {
342 if ((string)de.Key == CharSetEnumMember)
347 NamedArguments.Add (new DictionaryEntry (CharSetEnumMember,
348 new Argument (Constant.CreateConstant (typeof (CharSet), CodeGen.Module.DefaultCharSet, Location))));
351 public CustomAttributeBuilder Resolve ()
356 resolve_error = true;
359 ResolveAttributeType ();
364 if (Type.IsAbstract) {
365 Report.Error (653, Location, "Cannot apply attribute class `{0}' because it is abstract", GetSignatureForError ());
369 ObsoleteAttribute obsolete_attr = AttributeTester.GetObsoleteAttribute (Type);
370 if (obsolete_attr != null) {
371 AttributeTester.Report_ObsoleteMessage (obsolete_attr, TypeManager.CSharpName (Type), Location);
374 if (PosArguments == null && NamedArguments == null) {
375 object o = att_cache [Type];
377 resolve_error = false;
378 return (CustomAttributeBuilder)o;
382 Attributable owner = Owner;
383 DeclSpace ds = owner.ResolveContext as DeclSpace;
385 ds = owner.ResolveContext.DeclContainer;
387 EmitContext ec = new EmitContext (owner.ResolveContext, ds, owner.ResolveContext.DeclContainer,
388 Location, null, typeof (Attribute), owner.ResolveContext.DeclContainer.ModFlags, false);
389 ec.IsAnonymousMethodAllowed = false;
391 ConstructorInfo ctor = ResolveConstructor (ec);
393 if (Type is TypeBuilder &&
394 TypeManager.LookupDeclSpace (Type).MemberCache == null)
395 // The attribute type has been DefineType'd, but not Defined. Let's not treat it as an error.
396 // It'll be resolved again when the attached-to entity is emitted.
397 resolve_error = false;
401 ApplyModuleCharSet ();
403 CustomAttributeBuilder cb;
405 // SRE does not allow private ctor but we want to report all source code errors
409 if (NamedArguments == null) {
410 cb = new CustomAttributeBuilder (ctor, pos_values);
412 if (pos_values.Length == 0)
413 att_cache.Add (Type, cb);
415 resolve_error = false;
419 if (!ResolveNamedArguments (ec)) {
423 cb = new CustomAttributeBuilder (ctor, pos_values,
424 prop_info_arr, prop_values_arr,
425 field_info_arr, field_values_arr);
427 resolve_error = false;
431 Error_AttributeArgumentNotValid (Location);
436 protected virtual ConstructorInfo ResolveConstructor (EmitContext ec)
438 if (PosArguments != null) {
439 for (int i = 0; i < PosArguments.Count; i++) {
440 Argument a = (Argument) PosArguments [i];
442 if (!a.Resolve (ec, Location))
447 MethodGroupExpr mg = MemberLookupFinal (ec, ec.ContainerType,
448 Type, ".ctor", MemberTypes.Constructor,
449 BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly,
450 Location) as MethodGroupExpr;
455 mg = mg.OverloadResolve (ec, ref PosArguments, false, Location);
459 ConstructorInfo constructor = (ConstructorInfo)mg;
461 // TODO: move to OverloadResolve
462 ObsoleteAttribute oa = AttributeTester.GetMethodObsoleteAttribute (constructor);
463 if (oa != null && !Owner.ResolveContext.IsInObsoleteScope) {
464 AttributeTester.Report_ObsoleteMessage (oa, mg.GetSignatureForError (), mg.Location);
467 if (PosArguments == null) {
468 pos_values = EmptyObject;
472 AParametersCollection pd = TypeManager.GetParameterData (constructor);
474 int pos_arg_count = PosArguments.Count;
475 pos_values = new object [pos_arg_count];
476 for (int j = 0; j < pos_arg_count; ++j) {
477 Argument a = (Argument) PosArguments [j];
479 if (!a.Expr.GetAttributableValue (ec, a.Type, out pos_values [j]))
483 // Here we do the checks which should be done by corlib or by runtime.
484 // However Zoltan doesn't like it and every Mono compiler has to do it again.
486 if (Type == TypeManager.guid_attr_type) {
488 new Guid ((string)pos_values [0]);
490 catch (Exception e) {
491 Error_AttributeEmitError (e.Message);
496 if (Type == TypeManager.attribute_usage_type && (int)pos_values [0] == 0) {
497 Report.Error (591, Location, "Invalid value for argument to `System.AttributeUsage' attribute");
501 if (Type == TypeManager.indexer_name_type || Type == TypeManager.conditional_attribute_type) {
502 string v = pos_values [0] as string;
503 if (!Tokenizer.IsValidIdentifier (v) || Tokenizer.IsKeyword (v)) {
504 Report.Error (633, ((Argument)PosArguments[0]).Expr.Location,
505 "The argument to the `{0}' attribute must be a valid identifier", GetSignatureForError ());
510 if (Type == TypeManager.methodimpl_attr_type && pos_values.Length == 1 &&
511 pd.Types [0] == TypeManager.short_type &&
512 !System.Enum.IsDefined (typeof (MethodImplOptions), pos_values [0].ToString ())) {
513 Error_AttributeEmitError ("Incorrect argument value.");
520 protected virtual bool ResolveNamedArguments (EmitContext ec)
522 int named_arg_count = NamedArguments.Count;
524 ArrayList field_infos = new ArrayList (named_arg_count);
525 ArrayList prop_infos = new ArrayList (named_arg_count);
526 ArrayList field_values = new ArrayList (named_arg_count);
527 ArrayList prop_values = new ArrayList (named_arg_count);
529 ArrayList seen_names = new ArrayList(named_arg_count);
531 foreach (DictionaryEntry de in NamedArguments) {
532 string member_name = (string) de.Key;
534 if (seen_names.Contains(member_name)) {
535 Report.Error(643, Location, "'" + member_name + "' duplicate named attribute argument");
538 seen_names.Add(member_name);
540 Argument a = (Argument) de.Value;
541 if (!a.Resolve (ec, Location))
544 Expression member = Expression.MemberLookup (
545 ec.ContainerType, Type, member_name,
546 MemberTypes.Field | MemberTypes.Property,
547 BindingFlags.Public | BindingFlags.Instance,
550 if (member == null) {
551 member = Expression.MemberLookup (ec.ContainerType, Type, member_name,
552 MemberTypes.Field | MemberTypes.Property, BindingFlags.NonPublic | BindingFlags.Instance,
555 if (member != null) {
556 Report.SymbolRelatedToPreviousError (member.Type);
557 Expression.ErrorIsInaccesible (Location, member.GetSignatureForError ());
563 Expression.Error_TypeDoesNotContainDefinition (Location, Type, member_name);
567 if (!(member is PropertyExpr || member is FieldExpr)) {
568 Error_InvalidNamedArgument (member_name);
572 if (a.Expr is TypeParameterExpr){
573 Error_TypeParameterInAttribute (Location);
577 ObsoleteAttribute obsolete_attr;
579 if (member is PropertyExpr) {
580 PropertyInfo pi = ((PropertyExpr) member).PropertyInfo;
582 if (!pi.CanWrite || !pi.CanRead) {
583 Report.SymbolRelatedToPreviousError (pi);
584 Error_InvalidNamedArgument (member_name);
588 if (!IsValidArgumentType (member.Type)) {
589 Report.SymbolRelatedToPreviousError (pi);
590 Error_InvalidNamedAgrumentType (member_name);
595 if (!a.Expr.GetAttributableValue (ec, member.Type, out value))
598 PropertyBase pb = TypeManager.GetProperty (pi);
600 obsolete_attr = pb.GetObsoleteAttribute ();
602 obsolete_attr = AttributeTester.GetMemberObsoleteAttribute (pi);
604 prop_values.Add (value);
608 FieldInfo fi = ((FieldExpr) member).FieldInfo;
611 Error_InvalidNamedArgument (member_name);
615 if (!IsValidArgumentType (member.Type)) {
616 Report.SymbolRelatedToPreviousError (fi);
617 Error_InvalidNamedAgrumentType (member_name);
622 if (!a.Expr.GetAttributableValue (ec, member.Type, out value))
625 FieldBase fb = TypeManager.GetField (fi);
627 obsolete_attr = fb.GetObsoleteAttribute ();
629 obsolete_attr = AttributeTester.GetMemberObsoleteAttribute (fi);
631 field_values.Add (value);
632 field_infos.Add (fi);
635 if (obsolete_attr != null && !Owner.ResolveContext.IsInObsoleteScope)
636 AttributeTester.Report_ObsoleteMessage (obsolete_attr, member.GetSignatureForError (), member.Location);
639 prop_info_arr = new PropertyInfo [prop_infos.Count];
640 field_info_arr = new FieldInfo [field_infos.Count];
641 field_values_arr = new object [field_values.Count];
642 prop_values_arr = new object [prop_values.Count];
644 field_infos.CopyTo (field_info_arr, 0);
645 field_values.CopyTo (field_values_arr, 0);
647 prop_values.CopyTo (prop_values_arr, 0);
648 prop_infos.CopyTo (prop_info_arr, 0);
654 /// Get a string containing a list of valid targets for the attribute 'attr'
656 public string GetValidTargets ()
658 StringBuilder sb = new StringBuilder ();
659 AttributeTargets targets = GetAttributeUsage (Type).ValidOn;
661 if ((targets & AttributeTargets.Assembly) != 0)
662 sb.Append ("assembly, ");
664 if ((targets & AttributeTargets.Module) != 0)
665 sb.Append ("module, ");
667 if ((targets & AttributeTargets.Class) != 0)
668 sb.Append ("class, ");
670 if ((targets & AttributeTargets.Struct) != 0)
671 sb.Append ("struct, ");
673 if ((targets & AttributeTargets.Enum) != 0)
674 sb.Append ("enum, ");
676 if ((targets & AttributeTargets.Constructor) != 0)
677 sb.Append ("constructor, ");
679 if ((targets & AttributeTargets.Method) != 0)
680 sb.Append ("method, ");
682 if ((targets & AttributeTargets.Property) != 0)
683 sb.Append ("property, indexer, ");
685 if ((targets & AttributeTargets.Field) != 0)
686 sb.Append ("field, ");
688 if ((targets & AttributeTargets.Event) != 0)
689 sb.Append ("event, ");
691 if ((targets & AttributeTargets.Interface) != 0)
692 sb.Append ("interface, ");
694 if ((targets & AttributeTargets.Parameter) != 0)
695 sb.Append ("parameter, ");
697 if ((targets & AttributeTargets.Delegate) != 0)
698 sb.Append ("delegate, ");
700 if ((targets & AttributeTargets.ReturnValue) != 0)
701 sb.Append ("return, ");
704 if ((targets & AttributeTargets.GenericParameter) != 0)
705 sb.Append ("type parameter, ");
707 return sb.Remove (sb.Length - 2, 2).ToString ();
711 /// Returns AttributeUsage attribute based on types hierarchy
713 static AttributeUsageAttribute GetAttributeUsage (Type type)
715 AttributeUsageAttribute ua = usage_attr_cache [type] as AttributeUsageAttribute;
719 Class attr_class = TypeManager.LookupClass (type);
721 if (attr_class == null) {
722 object[] usage_attr = type.GetCustomAttributes (TypeManager.attribute_usage_type, true);
723 ua = (AttributeUsageAttribute)usage_attr [0];
724 usage_attr_cache.Add (type, ua);
729 if (attr_class.OptAttributes != null)
730 a = attr_class.OptAttributes.Search (TypeManager.attribute_usage_type);
733 if (attr_class.TypeBuilder.BaseType != TypeManager.attribute_type)
734 ua = GetAttributeUsage (attr_class.TypeBuilder.BaseType);
736 ua = DefaultUsageAttribute;
738 ua = a.GetAttributeUsageAttribute ();
741 usage_attr_cache.Add (type, ua);
745 AttributeUsageAttribute GetAttributeUsageAttribute ()
747 if (pos_values == null)
748 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
749 // But because a lot of attribute class code must be rewritten will be better to wait...
753 return DefaultUsageAttribute;
755 AttributeUsageAttribute usage_attribute = new AttributeUsageAttribute ((AttributeTargets)pos_values [0]);
757 object field = GetPropertyValue ("AllowMultiple");
759 usage_attribute.AllowMultiple = (bool)field;
761 field = GetPropertyValue ("Inherited");
763 usage_attribute.Inherited = (bool)field;
765 return usage_attribute;
769 /// Returns custom name of indexer
771 public string GetIndexerAttributeValue ()
773 if (pos_values == null)
774 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
775 // But because a lot of attribute class code must be rewritten will be better to wait...
781 return pos_values [0] as string;
785 /// Returns condition of ConditionalAttribute
787 public string GetConditionalAttributeValue ()
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 (string)pos_values [0];
801 /// Creates the instance of ObsoleteAttribute from this attribute instance
803 public ObsoleteAttribute GetObsoleteAttribute ()
805 if (pos_values == null)
806 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
807 // But because a lot of attribute class code must be rewritten will be better to wait...
813 if (pos_values == null || pos_values.Length == 0)
814 return new ObsoleteAttribute ();
816 if (pos_values.Length == 1)
817 return new ObsoleteAttribute ((string)pos_values [0]);
819 return new ObsoleteAttribute ((string)pos_values [0], (bool)pos_values [1]);
823 /// Returns value of CLSCompliantAttribute contructor parameter but because the method can be called
824 /// before ApplyAttribute. We need to resolve the arguments.
825 /// This situation occurs when class deps is differs from Emit order.
827 public bool GetClsCompliantAttributeValue ()
829 if (pos_values == null)
830 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
831 // But because a lot of attribute class code must be rewritten will be better to wait...
837 return (bool)pos_values [0];
840 public Type GetCoClassAttributeValue ()
842 if (pos_values == null)
848 return (Type)pos_values [0];
851 public bool CheckTarget ()
853 string[] valid_targets = Owner.ValidAttributeTargets;
854 if (ExplicitTarget == null || ExplicitTarget == valid_targets [0]) {
855 Target = Owner.AttributeTargets;
859 // TODO: we can skip the first item
860 if (((IList) valid_targets).Contains (ExplicitTarget)) {
861 switch (ExplicitTarget) {
862 case "return": Target = AttributeTargets.ReturnValue; return true;
863 case "param": Target = AttributeTargets.Parameter; return true;
864 case "field": Target = AttributeTargets.Field; return true;
865 case "method": Target = AttributeTargets.Method; return true;
866 case "property": Target = AttributeTargets.Property; return true;
868 throw new InternalErrorException ("Unknown explicit target: " + ExplicitTarget);
871 StringBuilder sb = new StringBuilder ();
872 foreach (string s in valid_targets) {
876 sb.Remove (sb.Length - 2, 2);
877 Report.Error (657, Location, "`{0}' is not a valid attribute location for this declaration. " +
878 "Valid attribute locations for this declaration are `{1}'", ExplicitTarget, sb.ToString ());
883 /// Tests permitted SecurityAction for assembly or other types
885 protected virtual bool IsSecurityActionValid (bool for_assembly)
887 SecurityAction action = GetSecurityActionValue ();
890 case SecurityAction.Demand:
891 case SecurityAction.Assert:
892 case SecurityAction.Deny:
893 case SecurityAction.PermitOnly:
894 case SecurityAction.LinkDemand:
895 case SecurityAction.InheritanceDemand:
900 case SecurityAction.RequestMinimum:
901 case SecurityAction.RequestOptional:
902 case SecurityAction.RequestRefuse:
908 Error_AttributeEmitError ("SecurityAction is out of range");
912 Error_AttributeEmitError (String.Concat ("SecurityAction `", action, "' is not valid for this declaration"));
916 System.Security.Permissions.SecurityAction GetSecurityActionValue ()
918 return (SecurityAction)pos_values [0];
922 /// Creates instance of SecurityAttribute class and add result of CreatePermission method to permission table.
924 /// <returns></returns>
925 public void ExtractSecurityPermissionSet (ListDictionary permissions)
927 Type orig_assembly_type = null;
929 if (TypeManager.LookupDeclSpace (Type) != null) {
930 if (!RootContext.StdLib) {
931 orig_assembly_type = Type.GetType (Type.FullName);
933 string orig_version_path = Environment.GetEnvironmentVariable ("__SECURITY_BOOTSTRAP_DB");
934 if (orig_version_path == null) {
935 Error_AttributeEmitError ("security custom attributes can not be referenced from defining assembly");
939 if (orig_sec_assembly == null) {
940 string file = Path.Combine (orig_version_path, Driver.OutputFile);
941 orig_sec_assembly = Assembly.LoadFile (file);
944 orig_assembly_type = orig_sec_assembly.GetType (Type.FullName, true);
945 if (orig_assembly_type == null) {
946 Report.Warning (-112, 1, Location, "Self-referenced security attribute `{0}' " +
947 "was not found in previous version of assembly");
953 SecurityAttribute sa;
954 // For all non-selfreferencing security attributes we can avoid all hacks
955 if (orig_assembly_type == null) {
956 sa = (SecurityAttribute) Activator.CreateInstance (Type, pos_values);
958 if (prop_info_arr != null) {
959 for (int i = 0; i < prop_info_arr.Length; ++i) {
960 PropertyInfo pi = prop_info_arr [i];
961 pi.SetValue (sa, prop_values_arr [i], null);
965 // HACK: All security attributes have same ctor syntax
966 sa = (SecurityAttribute) Activator.CreateInstance (orig_assembly_type, new object[] { GetSecurityActionValue () } );
968 // All types are from newly created assembly but for invocation with old one we need to convert them
969 if (prop_info_arr != null) {
970 for (int i = 0; i < prop_info_arr.Length; ++i) {
971 PropertyInfo emited_pi = prop_info_arr [i];
972 // FIXME: We are missing return type filter
973 // TODO: pi can be null
974 PropertyInfo pi = orig_assembly_type.GetProperty (emited_pi.Name);
976 object old_instance = pi.PropertyType.IsEnum ?
977 System.Enum.ToObject (pi.PropertyType, prop_values_arr [i]) :
980 pi.SetValue (sa, old_instance, null);
986 perm = sa.CreatePermission ();
987 SecurityAction action = GetSecurityActionValue ();
989 // IS is correct because for corlib we are using an instance from old corlib
990 if (!(perm is System.Security.CodeAccessPermission)) {
992 case SecurityAction.Demand:
993 action = (SecurityAction)13;
995 case SecurityAction.LinkDemand:
996 action = (SecurityAction)14;
998 case SecurityAction.InheritanceDemand:
999 action = (SecurityAction)15;
1004 PermissionSet ps = (PermissionSet)permissions [action];
1006 if (sa is PermissionSetAttribute)
1007 ps = new PermissionSet (sa.Unrestricted ? PermissionState.Unrestricted : PermissionState.None);
1009 ps = new PermissionSet (PermissionState.None);
1011 permissions.Add (action, ps);
1012 } else if (!ps.IsUnrestricted () && (sa is PermissionSetAttribute) && sa.Unrestricted) {
1013 ps = ps.Union (new PermissionSet (PermissionState.Unrestricted));
1014 permissions [action] = ps;
1016 ps.AddPermission (perm);
1019 public object GetPropertyValue (string name)
1021 if (prop_info_arr == null)
1024 for (int i = 0; i < prop_info_arr.Length; ++i) {
1025 if (prop_info_arr [i].Name == name)
1026 return prop_values_arr [i];
1033 // Theoretically, we can get rid of this, since FieldBuilder.SetCustomAttribute()
1034 // and ParameterBuilder.SetCustomAttribute() are supposed to handle this attribute.
1035 // However, we can't, since it appears that the .NET 1.1 SRE hangs when given a MarshalAsAttribute.
1038 public UnmanagedMarshal GetMarshal (Attributable attr)
1040 UnmanagedType UnmanagedType;
1041 if (!RootContext.StdLib || pos_values [0].GetType () != typeof (UnmanagedType))
1042 UnmanagedType = (UnmanagedType) System.Enum.ToObject (typeof (UnmanagedType), pos_values [0]);
1044 UnmanagedType = (UnmanagedType) pos_values [0];
1046 object value = GetFieldValue ("SizeParamIndex");
1047 if (value != null && UnmanagedType != UnmanagedType.LPArray) {
1048 Error_AttributeEmitError ("SizeParamIndex field is not valid for the specified unmanaged type");
1052 object o = GetFieldValue ("ArraySubType");
1053 UnmanagedType array_sub_type = o == null ? (UnmanagedType) 0x50 /* NATIVE_MAX */ : (UnmanagedType) o;
1055 switch (UnmanagedType) {
1056 case UnmanagedType.CustomMarshaler: {
1057 MethodInfo define_custom = typeof (UnmanagedMarshal).GetMethod ("DefineCustom",
1058 BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
1059 if (define_custom == null) {
1060 Report.RuntimeMissingSupport (Location, "set marshal info");
1064 object [] args = new object [4];
1065 args [0] = GetFieldValue ("MarshalTypeRef");
1066 args [1] = GetFieldValue ("MarshalCookie");
1067 args [2] = GetFieldValue ("MarshalType");
1068 args [3] = Guid.Empty;
1069 return (UnmanagedMarshal) define_custom.Invoke (null, args);
1071 case UnmanagedType.LPArray: {
1072 object size_const = GetFieldValue ("SizeConst");
1073 object size_param_index = GetFieldValue ("SizeParamIndex");
1075 if ((size_const != null) || (size_param_index != null)) {
1076 MethodInfo define_array = typeof (UnmanagedMarshal).GetMethod ("DefineLPArrayInternal",
1077 BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
1078 if (define_array == null) {
1079 Report.RuntimeMissingSupport (Location, "set marshal info");
1083 object [] args = new object [3];
1084 args [0] = array_sub_type;
1085 args [1] = size_const == null ? -1 : size_const;
1086 args [2] = size_param_index == null ? -1 : size_param_index;
1087 return (UnmanagedMarshal) define_array.Invoke (null, args);
1090 return UnmanagedMarshal.DefineLPArray (array_sub_type);
1092 case UnmanagedType.SafeArray:
1093 return UnmanagedMarshal.DefineSafeArray (array_sub_type);
1095 case UnmanagedType.ByValArray:
1096 FieldBase fm = attr as FieldBase;
1098 Error_AttributeEmitError ("Specified unmanaged type is only valid on fields");
1101 return UnmanagedMarshal.DefineByValArray ((int) GetFieldValue ("SizeConst"));
1103 case UnmanagedType.ByValTStr:
1104 return UnmanagedMarshal.DefineByValTStr ((int) GetFieldValue ("SizeConst"));
1107 return UnmanagedMarshal.DefineUnmanagedMarshal (UnmanagedType);
1111 object GetFieldValue (string name)
1114 if (field_info_arr == null)
1117 foreach (FieldInfo fi in field_info_arr) {
1118 if (fi.Name == name)
1119 return GetValue (field_values_arr [i]);
1125 static object GetValue (object value)
1127 if (value is EnumConstant)
1128 return ((EnumConstant) value).GetValue ();
1135 public CharSet GetCharSetValue ()
1137 return (CharSet)System.Enum.Parse (typeof (CharSet), pos_values [0].ToString ());
1140 public bool IsInternalMethodImplAttribute {
1142 if (Type != TypeManager.methodimpl_attr_type)
1145 MethodImplOptions options;
1146 if (pos_values[0].GetType () != typeof (MethodImplOptions))
1147 options = (MethodImplOptions)System.Enum.ToObject (typeof (MethodImplOptions), pos_values[0]);
1149 options = (MethodImplOptions)pos_values[0];
1151 return (options & MethodImplOptions.InternalCall) != 0;
1155 public LayoutKind GetLayoutKindValue ()
1157 if (!RootContext.StdLib || pos_values [0].GetType () != typeof (LayoutKind))
1158 return (LayoutKind)System.Enum.ToObject (typeof (LayoutKind), pos_values [0]);
1160 return (LayoutKind)pos_values [0];
1163 public object GetParameterDefaultValue ()
1165 return pos_values [0];
1168 public override bool Equals (object obj)
1170 Attribute a = obj as Attribute;
1174 return Type == a.Type && Target == a.Target;
1177 public override int GetHashCode ()
1179 return base.GetHashCode ();
1183 /// Emit attribute for Attributable symbol
1185 public void Emit (ListDictionary allEmitted)
1187 CustomAttributeBuilder cb = Resolve ();
1191 AttributeUsageAttribute usage_attr = GetAttributeUsage (Type);
1192 if ((usage_attr.ValidOn & Target) == 0) {
1193 Report.Error (592, Location, "The attribute `{0}' is not valid on this declaration type. " +
1194 "It is valid on `{1}' declarations only",
1195 GetSignatureForError (), GetValidTargets ());
1200 foreach (Attributable owner in owners)
1201 owner.ApplyAttributeBuilder (this, cb);
1203 catch (Exception e) {
1204 Error_AttributeEmitError (e.Message);
1208 if (!usage_attr.AllowMultiple && allEmitted != null) {
1209 if (allEmitted.Contains (this)) {
1210 ArrayList a = allEmitted [this] as ArrayList;
1212 a = new ArrayList (2);
1213 allEmitted [this] = a;
1217 allEmitted.Add (this, null);
1221 if (!RootContext.VerifyClsCompliance)
1224 // Here we are testing attribute arguments for array usage (error 3016)
1225 if (Owner.IsClsComplianceRequired ()) {
1226 if (PosArguments != null) {
1227 foreach (Argument arg in PosArguments) {
1228 // Type is undefined (was error 246)
1229 if (arg.Type == null)
1232 if (arg.Type.IsArray) {
1233 Report.Warning (3016, 1, Location, "Arrays as attribute arguments are not CLS-compliant");
1239 if (NamedArguments == null)
1242 foreach (DictionaryEntry de in NamedArguments) {
1243 Argument arg = (Argument) de.Value;
1245 // Type is undefined (was error 246)
1246 if (arg.Type == null)
1249 if (arg.Type.IsArray) {
1250 Report.Warning (3016, 1, Location, "Arrays as attribute arguments are not CLS-compliant");
1257 private Expression GetValue ()
1259 if (PosArguments == null || PosArguments.Count < 1)
1262 return ((Argument) PosArguments [0]).Expr;
1265 public string GetString ()
1267 Expression e = GetValue ();
1268 if (e is StringConstant)
1269 return ((StringConstant)e).Value;
1273 public bool GetBoolean ()
1275 Expression e = GetValue ();
1276 if (e is BoolConstant)
1277 return ((BoolConstant)e).Value;
1281 public Type GetArgumentType ()
1283 TypeOf e = GetValue () as TypeOf;
1286 return e.TypeArgument;
1289 public override Expression CreateExpressionTree (EmitContext ec)
1291 throw new NotSupportedException ("ET");
1294 public override Expression DoResolve (EmitContext ec)
1296 throw new NotImplementedException ();
1299 public override void Emit (EmitContext ec)
1301 throw new NotImplementedException ();
1307 /// For global attributes (assembly, module) we need special handling.
1308 /// Attributes can be located in the several files
1310 public class GlobalAttribute : Attribute
1312 public readonly NamespaceEntry ns;
1314 public GlobalAttribute (NamespaceEntry ns, string target,
1315 Expression left_expr, string identifier, object[] args, Location loc, bool nameEscaped):
1316 base (target, left_expr, identifier, args, loc, nameEscaped)
1319 this.owners = new Attributable[1];
1322 public override void AttachTo (Attributable owner)
1324 if (ExplicitTarget == "assembly") {
1325 owners [0] = CodeGen.Assembly;
1328 if (ExplicitTarget == "module") {
1329 owners [0] = CodeGen.Module;
1332 throw new NotImplementedException ("Unknown global explicit target " + ExplicitTarget);
1337 // RootContext.ToplevelTypes has a single NamespaceEntry which gets overwritten
1338 // each time a new file is parsed. However, we need to use the NamespaceEntry
1339 // in effect where the attribute was used. Since code elsewhere cannot assume
1340 // that the NamespaceEntry is right, just overwrite it.
1342 // Precondition: RootContext.ToplevelTypes == null
1344 if (RootContext.ToplevelTypes.NamespaceEntry != null)
1345 throw new InternalErrorException (Location + " non-null NamespaceEntry");
1347 RootContext.ToplevelTypes.NamespaceEntry = ns;
1350 protected override bool IsSecurityActionValid (bool for_assembly)
1352 return base.IsSecurityActionValid (true);
1357 RootContext.ToplevelTypes.NamespaceEntry = null;
1360 protected override TypeExpr ResolveAsTypeTerminal (Expression expr, IResolveContext ec, bool silent)
1364 return base.ResolveAsTypeTerminal (expr, ec, silent);
1371 protected override ConstructorInfo ResolveConstructor (EmitContext ec)
1375 return base.ResolveConstructor (ec);
1382 protected override bool ResolveNamedArguments (EmitContext ec)
1386 return base.ResolveNamedArguments (ec);
1394 public class Attributes {
1395 public readonly ArrayList Attrs;
1397 public Attributes (Attribute a)
1399 Attrs = new ArrayList ();
1403 public Attributes (ArrayList attrs)
1408 public void AddAttributes (ArrayList attrs)
1410 Attrs.AddRange (attrs);
1413 public void AttachTo (Attributable attributable)
1415 foreach (Attribute a in Attrs)
1416 a.AttachTo (attributable);
1419 public Attributes Clone ()
1421 ArrayList al = new ArrayList (Attrs.Count);
1422 foreach (Attribute a in Attrs)
1423 al.Add (a.Clone ());
1425 return new Attributes (al);
1429 /// Checks whether attribute target is valid for the current element
1431 public bool CheckTargets ()
1433 foreach (Attribute a in Attrs) {
1434 if (!a.CheckTarget ())
1440 public Attribute Search (Type t)
1442 foreach (Attribute a in Attrs) {
1443 if (a.ResolveType () == t)
1450 /// Returns all attributes of type 't'. Use it when attribute is AllowMultiple = true
1452 public Attribute[] SearchMulti (Type t)
1454 ArrayList ar = null;
1456 foreach (Attribute a in Attrs) {
1457 if (a.ResolveType () == t) {
1459 ar = new ArrayList ();
1464 return ar == null ? null : ar.ToArray (typeof (Attribute)) as Attribute[];
1471 ListDictionary ld = Attrs.Count > 1 ? new ListDictionary () : null;
1473 foreach (Attribute a in Attrs)
1476 if (ld == null || ld.Count == 0)
1479 foreach (DictionaryEntry d in ld) {
1480 if (d.Value == null)
1483 foreach (Attribute collision in (ArrayList)d.Value)
1484 Report.SymbolRelatedToPreviousError (collision.Location, "");
1486 Attribute a = (Attribute)d.Key;
1487 Report.Error (579, a.Location, "The attribute `{0}' cannot be applied multiple times",
1488 a.GetSignatureForError ());
1492 public bool Contains (Type t)
1494 return Search (t) != null;
1499 /// Helper class for attribute verification routine.
1501 sealed class AttributeTester
1503 static PtrHashtable analyzed_types;
1504 static PtrHashtable analyzed_types_obsolete;
1505 static PtrHashtable analyzed_member_obsolete;
1506 static PtrHashtable analyzed_method_excluded;
1507 static PtrHashtable fixed_buffer_cache;
1509 static object TRUE = new object ();
1510 static object FALSE = new object ();
1512 static AttributeTester ()
1517 private AttributeTester ()
1521 public static void Reset ()
1523 analyzed_types = new PtrHashtable ();
1524 analyzed_types_obsolete = new PtrHashtable ();
1525 analyzed_member_obsolete = new PtrHashtable ();
1526 analyzed_method_excluded = new PtrHashtable ();
1527 fixed_buffer_cache = new PtrHashtable ();
1530 public enum Result {
1537 /// Returns true if parameters of two compared methods are CLS-Compliant.
1538 /// It tests differing only in ref or out, or in array rank.
1540 public static Result AreOverloadedMethodParamsClsCompliant (AParametersCollection pa, AParametersCollection pb)
1542 Type [] types_a = pa.Types;
1543 Type [] types_b = pb.Types;
1544 if (types_a == null || types_b == null)
1547 if (types_a.Length != types_b.Length)
1550 Result result = Result.Ok;
1551 for (int i = 0; i < types_b.Length; ++i) {
1552 Type aType = types_a [i];
1553 Type bType = types_b [i];
1555 if (aType.IsArray && bType.IsArray) {
1556 Type a_el_type = aType.GetElementType ();
1557 Type b_el_type = bType.GetElementType ();
1558 if (aType.GetArrayRank () != bType.GetArrayRank () && a_el_type == b_el_type) {
1559 result = Result.RefOutArrayError;
1563 if (a_el_type.IsArray || b_el_type.IsArray) {
1564 result = Result.ArrayArrayError;
1572 if (pa.FixedParameters [i].ModFlags != pb.FixedParameters [i].ModFlags)
1573 result = Result.RefOutArrayError;
1579 /// This method tests the CLS compliance of external types. It doesn't test type visibility.
1581 public static bool IsClsCompliant (Type type)
1586 object type_compliance = analyzed_types[type];
1587 if (type_compliance != null)
1588 return type_compliance == TRUE;
1590 if (type.IsPointer) {
1591 analyzed_types.Add (type, FALSE);
1597 result = IsClsCompliant (TypeManager.GetElementType (type));
1598 } else if (TypeManager.IsNullableType (type)) {
1599 result = IsClsCompliant (TypeManager.GetTypeArguments (type) [0]);
1601 result = AnalyzeTypeCompliance (type);
1603 analyzed_types.Add (type, result ? TRUE : FALSE);
1608 /// Returns IFixedBuffer implementation if field is fixed buffer else null.
1610 public static IFixedBuffer GetFixedBuffer (FieldInfo fi)
1612 // Fixed buffer helper type is generated as value type
1613 if (!fi.FieldType.IsValueType)
1616 FieldBase fb = TypeManager.GetField (fi);
1618 return fb as IFixedBuffer;
1621 if (TypeManager.GetConstant (fi) != null)
1624 object o = fixed_buffer_cache [fi];
1626 if (TypeManager.fixed_buffer_attr_type == null)
1629 if (!fi.IsDefined (TypeManager.fixed_buffer_attr_type, false)) {
1630 fixed_buffer_cache.Add (fi, FALSE);
1634 IFixedBuffer iff = new FixedFieldExternal (fi);
1635 fixed_buffer_cache.Add (fi, iff);
1642 return (IFixedBuffer)o;
1645 public static void VerifyModulesClsCompliance ()
1647 Module[] modules = RootNamespace.Global.Modules;
1648 if (modules == null)
1651 // The first module is generated assembly
1652 for (int i = 1; i < modules.Length; ++i) {
1653 Module module = modules [i];
1654 if (!GetClsCompliantAttributeValue (module, null)) {
1655 Report.Error (3013, "Added modules must be marked with the CLSCompliant attribute " +
1656 "to match the assembly", module.Name);
1662 public static Type GetImportedIgnoreCaseClsType (string name)
1664 foreach (Assembly a in RootNamespace.Global.Assemblies) {
1665 Type t = a.GetType (name, false, true);
1669 if (IsClsCompliant (t))
1675 static bool GetClsCompliantAttributeValue (ICustomAttributeProvider attribute_provider, Assembly a)
1677 if (TypeManager.cls_compliant_attribute_type == null)
1680 object[] cls_attr = attribute_provider.GetCustomAttributes (TypeManager.cls_compliant_attribute_type, false);
1681 if (cls_attr.Length == 0) {
1685 return GetClsCompliantAttributeValue (a, null);
1688 return ((CLSCompliantAttribute)cls_attr [0]).IsCompliant;
1691 static bool AnalyzeTypeCompliance (Type type)
1693 type = TypeManager.DropGenericTypeArguments (type);
1694 DeclSpace ds = TypeManager.LookupDeclSpace (type);
1696 return ds.IsClsComplianceRequired ();
1699 if (TypeManager.IsGenericParameter (type))
1702 return GetClsCompliantAttributeValue (type, type.Assembly);
1706 /// Returns instance of ObsoleteAttribute when type is obsolete
1708 public static ObsoleteAttribute GetObsoleteAttribute (Type type)
1710 object type_obsolete = analyzed_types_obsolete [type];
1711 if (type_obsolete == FALSE)
1714 if (type_obsolete != null)
1715 return (ObsoleteAttribute)type_obsolete;
1717 ObsoleteAttribute result = null;
1718 if (TypeManager.HasElementType (type)) {
1719 result = GetObsoleteAttribute (TypeManager.GetElementType (type));
1720 } else if (TypeManager.IsGenericParameter (type) || TypeManager.IsGenericType (type))
1723 DeclSpace type_ds = TypeManager.LookupDeclSpace (type);
1725 // Type is external, we can get attribute directly
1726 if (type_ds == null) {
1727 if (TypeManager.obsolete_attribute_type != null) {
1728 object [] attribute = type.GetCustomAttributes (TypeManager.obsolete_attribute_type, false);
1729 if (attribute.Length == 1)
1730 result = (ObsoleteAttribute) attribute [0];
1733 result = type_ds.GetObsoleteAttribute ();
1737 // Cannot use .Add because of corlib bootstrap
1738 analyzed_types_obsolete [type] = result == null ? FALSE : result;
1743 /// Returns instance of ObsoleteAttribute when method is obsolete
1745 public static ObsoleteAttribute GetMethodObsoleteAttribute (MethodBase mb)
1747 IMethodData mc = TypeManager.GetMethod (mb);
1749 return mc.GetObsoleteAttribute ();
1751 // compiler generated methods are not registered by AddMethod
1752 if (mb.DeclaringType is TypeBuilder)
1755 MemberInfo mi = TypeManager.GetPropertyFromAccessor (mb);
1757 return GetMemberObsoleteAttribute (mi);
1759 mi = TypeManager.GetEventFromAccessor (mb);
1761 return GetMemberObsoleteAttribute (mi);
1763 return GetMemberObsoleteAttribute (mb);
1767 /// Returns instance of ObsoleteAttribute when member is obsolete
1769 public static ObsoleteAttribute GetMemberObsoleteAttribute (MemberInfo mi)
1771 object type_obsolete = analyzed_member_obsolete [mi];
1772 if (type_obsolete == FALSE)
1775 if (type_obsolete != null)
1776 return (ObsoleteAttribute)type_obsolete;
1778 if ((mi.DeclaringType is TypeBuilder) || TypeManager.IsGenericType (mi.DeclaringType))
1781 if (TypeManager.obsolete_attribute_type == null)
1784 ObsoleteAttribute oa = System.Attribute.GetCustomAttribute (mi, TypeManager.obsolete_attribute_type, false)
1785 as ObsoleteAttribute;
1786 analyzed_member_obsolete.Add (mi, oa == null ? FALSE : oa);
1791 /// Common method for Obsolete error/warning reporting.
1793 public static void Report_ObsoleteMessage (ObsoleteAttribute oa, string member, Location loc)
1796 Report.Error (619, loc, "`{0}' is obsolete: `{1}'", member, oa.Message);
1800 if (oa.Message == null || oa.Message.Length == 0) {
1801 Report.Warning (612, 1, loc, "`{0}' is obsolete", member);
1804 Report.Warning (618, 2, loc, "`{0}' is obsolete: `{1}'", member, oa.Message);
1807 public static bool IsConditionalMethodExcluded (MethodBase mb, Location loc)
1809 object excluded = analyzed_method_excluded [mb];
1810 if (excluded != null)
1811 return excluded == TRUE ? true : false;
1813 if (TypeManager.conditional_attribute_type == null)
1816 ConditionalAttribute[] attrs = mb.GetCustomAttributes (TypeManager.conditional_attribute_type, true)
1817 as ConditionalAttribute[];
1818 if (attrs.Length == 0) {
1819 analyzed_method_excluded.Add (mb, FALSE);
1823 foreach (ConditionalAttribute a in attrs) {
1824 if (loc.CompilationUnit.IsConditionalDefined (a.ConditionString)) {
1825 analyzed_method_excluded.Add (mb, FALSE);
1830 analyzed_method_excluded.Add (mb, TRUE);
1835 /// Analyzes class whether it has attribute which has ConditionalAttribute
1836 /// and its condition is not defined.
1838 public static bool IsAttributeExcluded (Type type, Location loc)
1843 Class class_decl = TypeManager.LookupDeclSpace (type) as Class;
1845 // TODO: add caching
1846 // TODO: merge all Type bases attribute caching to one cache to save memory
1847 if (class_decl == null && TypeManager.conditional_attribute_type != null) {
1848 object[] attributes = type.GetCustomAttributes (TypeManager.conditional_attribute_type, false);
1849 foreach (ConditionalAttribute ca in attributes) {
1850 if (loc.CompilationUnit.IsConditionalDefined (ca.ConditionString))
1853 return attributes.Length > 0;
1856 return class_decl.IsExcluded ();
1859 public static Type GetCoClassAttribute (Type type)
1861 TypeContainer tc = TypeManager.LookupInterface (type);
1863 if (TypeManager.coclass_attr_type == null)
1866 object[] o = type.GetCustomAttributes (TypeManager.coclass_attr_type, false);
1869 return ((System.Runtime.InteropServices.CoClassAttribute)o[0]).CoClass;
1872 if (tc.OptAttributes == null || TypeManager.coclass_attr_type == null)
1875 Attribute a = tc.OptAttributes.Search (TypeManager.coclass_attr_type);
1879 return a.GetCoClassAttributeValue ();