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;
131 public static void Reset ()
133 usage_attr_cache = new PtrHashtable ();
134 att_cache = new PtrHashtable ();
137 public virtual void AttachTo (Attributable owner)
139 if (this.owners == null) {
140 this.owners = new Attributable[1] { owner };
144 // When the same attribute is attached to multiple fiels
145 // we use this extra_owners as a list of owners. The attribute
146 // then can be removed because will be emitted when first owner
148 Attributable[] new_array = new Attributable [this.owners.Length + 1];
149 owners.CopyTo (new_array, 0);
150 new_array [owners.Length] = owner;
151 this.owners = new_array;
152 owner.OptAttributes = null;
155 void Error_InvalidNamedArgument (string name)
157 Report.Error (617, Location, "`{0}' is not a valid named attribute argument. Named attribute arguments " +
158 "must be fields which are not readonly, static, const or read-write properties which are " +
159 "public and not static",
163 void Error_InvalidNamedAgrumentType (string name)
165 Report.Error (655, Location, "`{0}' is not a valid named attribute argument because it is not a valid " +
166 "attribute parameter type", name);
169 public static void Error_AttributeArgumentNotValid (Location loc)
171 Report.Error (182, loc,
172 "An attribute argument must be a constant expression, typeof " +
173 "expression or array creation expression");
176 static void Error_TypeParameterInAttribute (Location loc)
179 -202, loc, "Can not use a type parameter in an attribute");
182 public void Error_MissingGuidAttribute ()
184 Report.Error (596, Location, "The Guid attribute must be specified with the ComImport attribute");
187 public void Error_MisusedExtensionAttribute ()
189 Report.Error (1112, Location, "Do not use `{0}' directly. Use parameter modifier `this' instead", GetSignatureForError ());
193 /// This is rather hack. We report many emit attribute error with same error to be compatible with
194 /// csc. But because csc has to report them this way because error came from ilasm we needn't.
196 public void Error_AttributeEmitError (string inner)
198 Report.Error (647, Location, "Error during emitting `{0}' attribute. The reason is `{1}'",
199 TypeManager.CSharpName (Type), inner);
202 public void Error_InvalidSecurityParent ()
204 Error_AttributeEmitError ("it is attached to invalid parent");
213 protected virtual TypeExpr ResolveAsTypeTerminal (Expression expr, IResolveContext ec, bool silent)
215 return expr.ResolveAsTypeTerminal (ec, silent);
218 Type ResolvePossibleAttributeType (string name, bool silent, ref bool is_attr)
220 IResolveContext rc = Owner.ResolveContext;
223 if (LeftExpr == null) {
224 te = ResolveAsTypeTerminal (new SimpleName (name, Location), rc, silent);
226 te = ResolveAsTypeTerminal (new MemberAccess (LeftExpr, name), rc, silent);
233 if (TypeManager.IsSubclassOf (t, TypeManager.attribute_type)) {
235 } else if (!silent) {
236 Report.SymbolRelatedToPreviousError (t);
237 Report.Error (616, Location, "`{0}': is not an attribute class", TypeManager.CSharpName (t));
243 /// Tries to resolve the type of the attribute. Flags an error if it can't, and complain is true.
245 void ResolveAttributeType ()
247 bool t1_is_attr = false;
248 Type t1 = ResolvePossibleAttributeType (Identifier, true, ref t1_is_attr);
250 bool t2_is_attr = false;
251 Type t2 = nameEscaped ? null :
252 ResolvePossibleAttributeType (Identifier + "Attribute", true, ref t2_is_attr);
254 if (t1_is_attr && t2_is_attr) {
255 Report.Error (1614, Location, "`{0}' is ambiguous between `{0}' and `{0}Attribute'. " +
256 "Use either `@{0}' or `{0}Attribute'", GetSignatureForError ());
257 resolve_error = true;
271 if (t1 == null && t2 == null)
272 ResolvePossibleAttributeType (Identifier, false, ref t1_is_attr);
274 ResolvePossibleAttributeType (Identifier, false, ref t1_is_attr);
276 ResolvePossibleAttributeType (Identifier + "Attribute", false, ref t2_is_attr);
278 resolve_error = true;
281 public virtual Type ResolveType ()
283 if (Type == null && !resolve_error)
284 ResolveAttributeType ();
288 public override string GetSignatureForError ()
291 return TypeManager.CSharpName (Type);
293 return LeftExpr == null ? Identifier : LeftExpr.GetSignatureForError () + "." + Identifier;
296 public bool HasSecurityAttribute {
298 return TypeManager.security_attr_type != null &&
299 TypeManager.IsSubclassOf (type, TypeManager.security_attr_type);
303 public bool IsValidSecurityAttribute ()
305 return HasSecurityAttribute && IsSecurityActionValid (false);
308 static bool IsValidArgumentType (Type t)
311 t = TypeManager.GetElementType (t);
313 return t == TypeManager.string_type ||
314 TypeManager.IsPrimitiveType (t) ||
315 TypeManager.IsEnumType (t) ||
316 t == TypeManager.object_type ||
317 t == TypeManager.type_type;
320 [Conditional ("GMCS_SOURCE")]
321 void ApplyModuleCharSet ()
323 if (Type != TypeManager.dllimport_type)
326 if (!CodeGen.Module.HasDefaultCharSet)
329 const string CharSetEnumMember = "CharSet";
330 if (NamedArguments == null) {
331 NamedArguments = new ArrayList (1);
333 foreach (DictionaryEntry de in NamedArguments) {
334 if ((string)de.Key == CharSetEnumMember)
339 NamedArguments.Add (new DictionaryEntry (CharSetEnumMember,
340 new Argument (Constant.CreateConstant (typeof (CharSet), CodeGen.Module.DefaultCharSet, Location))));
343 public CustomAttributeBuilder Resolve ()
348 resolve_error = true;
351 ResolveAttributeType ();
356 if (Type.IsAbstract) {
357 Report.Error (653, Location, "Cannot apply attribute class `{0}' because it is abstract", GetSignatureForError ());
361 ObsoleteAttribute obsolete_attr = AttributeTester.GetObsoleteAttribute (Type);
362 if (obsolete_attr != null) {
363 AttributeTester.Report_ObsoleteMessage (obsolete_attr, TypeManager.CSharpName (Type), Location);
366 if (PosArguments == null && NamedArguments == null) {
367 object o = att_cache [Type];
369 resolve_error = false;
370 return (CustomAttributeBuilder)o;
374 Attributable owner = Owner;
375 DeclSpace ds = owner.ResolveContext as DeclSpace;
377 ds = owner.ResolveContext.DeclContainer;
379 EmitContext ec = new EmitContext (owner.ResolveContext, ds, owner.ResolveContext.DeclContainer,
380 Location, null, typeof (Attribute), owner.ResolveContext.DeclContainer.ModFlags, false);
381 ec.IsAnonymousMethodAllowed = false;
383 ConstructorInfo ctor = ResolveConstructor (ec);
385 if (Type is TypeBuilder &&
386 TypeManager.LookupDeclSpace (Type).MemberCache == null)
387 // The attribute type has been DefineType'd, but not Defined. Let's not treat it as an error.
388 // It'll be resolved again when the attached-to entity is emitted.
389 resolve_error = false;
393 ApplyModuleCharSet ();
395 CustomAttributeBuilder cb;
397 // SRE does not allow private ctor but we want to report all source code errors
401 if (NamedArguments == null) {
402 cb = new CustomAttributeBuilder (ctor, pos_values);
404 if (pos_values.Length == 0)
405 att_cache.Add (Type, cb);
407 resolve_error = false;
411 if (!ResolveNamedArguments (ec)) {
415 cb = new CustomAttributeBuilder (ctor, pos_values,
416 prop_info_arr, prop_values_arr,
417 field_info_arr, field_values_arr);
419 resolve_error = false;
423 Error_AttributeArgumentNotValid (Location);
428 protected virtual ConstructorInfo ResolveConstructor (EmitContext ec)
430 if (PosArguments != null) {
431 for (int i = 0; i < PosArguments.Count; i++) {
432 Argument a = (Argument) PosArguments [i];
434 if (!a.Resolve (ec, Location))
439 MethodGroupExpr mg = MemberLookupFinal (ec, ec.ContainerType,
440 Type, ".ctor", MemberTypes.Constructor,
441 BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly,
442 Location) as MethodGroupExpr;
447 mg = mg.OverloadResolve (ec, ref PosArguments, false, Location);
451 ConstructorInfo constructor = (ConstructorInfo)mg;
453 // TODO: move to OverloadResolve
454 ObsoleteAttribute oa = AttributeTester.GetMethodObsoleteAttribute (constructor);
455 if (oa != null && !Owner.ResolveContext.IsInObsoleteScope) {
456 AttributeTester.Report_ObsoleteMessage (oa, mg.GetSignatureForError (), mg.Location);
459 if (PosArguments == null) {
460 pos_values = EmptyObject;
464 ParameterData pd = TypeManager.GetParameterData (constructor);
466 int pos_arg_count = PosArguments.Count;
467 pos_values = new object [pos_arg_count];
468 for (int j = 0; j < pos_arg_count; ++j) {
469 Argument a = (Argument) PosArguments [j];
471 if (!a.Expr.GetAttributableValue (a.Type, out pos_values [j]))
475 // Here we do the checks which should be done by corlib or by runtime.
476 // However Zoltan doesn't like it and every Mono compiler has to do it again.
478 if (Type == TypeManager.guid_attr_type) {
480 new Guid ((string)pos_values [0]);
482 catch (Exception e) {
483 Error_AttributeEmitError (e.Message);
488 if (Type == TypeManager.attribute_usage_type && (int)pos_values [0] == 0) {
489 Report.Error (591, Location, "Invalid value for argument to `System.AttributeUsage' attribute");
493 if (Type == TypeManager.indexer_name_type || Type == TypeManager.conditional_attribute_type) {
494 if (!Tokenizer.IsValidIdentifier ((string)pos_values [0])) {
495 Report.Error (633, ((Argument)PosArguments[0]).Expr.Location,
496 "The argument to the `{0}' attribute must be a valid identifier", GetSignatureForError ());
501 if (Type == TypeManager.methodimpl_attr_type && pos_values.Length == 1 &&
502 pd.ParameterType (0) == TypeManager.short_type &&
503 !System.Enum.IsDefined (typeof (MethodImplOptions), pos_values [0].ToString ())) {
504 Error_AttributeEmitError ("Incorrect argument value.");
511 protected virtual bool ResolveNamedArguments (EmitContext ec)
513 int named_arg_count = NamedArguments.Count;
515 ArrayList field_infos = new ArrayList (named_arg_count);
516 ArrayList prop_infos = new ArrayList (named_arg_count);
517 ArrayList field_values = new ArrayList (named_arg_count);
518 ArrayList prop_values = new ArrayList (named_arg_count);
520 ArrayList seen_names = new ArrayList(named_arg_count);
522 foreach (DictionaryEntry de in NamedArguments) {
523 string member_name = (string) de.Key;
525 if (seen_names.Contains(member_name)) {
526 Report.Error(643, Location, "'" + member_name + "' duplicate named attribute argument");
529 seen_names.Add(member_name);
531 Argument a = (Argument) de.Value;
532 if (!a.Resolve (ec, Location))
535 Expression member = Expression.MemberLookup (
536 ec.ContainerType, Type, member_name,
537 MemberTypes.Field | MemberTypes.Property,
538 BindingFlags.Public | BindingFlags.Instance,
541 if (member == null) {
542 member = Expression.MemberLookup (ec.ContainerType, Type, member_name,
543 MemberTypes.Field | MemberTypes.Property, BindingFlags.NonPublic | BindingFlags.Instance,
546 if (member != null) {
547 Report.SymbolRelatedToPreviousError (member.Type);
548 Expression.ErrorIsInaccesible (Location, member.GetSignatureForError ());
554 Expression.Error_TypeDoesNotContainDefinition (Location, Type, member_name);
558 if (!(member is PropertyExpr || member is FieldExpr)) {
559 Error_InvalidNamedArgument (member_name);
563 if (a.Expr is TypeParameterExpr){
564 Error_TypeParameterInAttribute (Location);
568 ObsoleteAttribute obsolete_attr;
570 if (member is PropertyExpr) {
571 PropertyInfo pi = ((PropertyExpr) member).PropertyInfo;
573 if (!pi.CanWrite || !pi.CanRead) {
574 Report.SymbolRelatedToPreviousError (pi);
575 Error_InvalidNamedArgument (member_name);
579 if (!IsValidArgumentType (member.Type)) {
580 Report.SymbolRelatedToPreviousError (pi);
581 Error_InvalidNamedAgrumentType (member_name);
586 if (!a.Expr.GetAttributableValue (member.Type, out value))
589 PropertyBase pb = TypeManager.GetProperty (pi);
591 obsolete_attr = pb.GetObsoleteAttribute ();
593 obsolete_attr = AttributeTester.GetMemberObsoleteAttribute (pi);
595 prop_values.Add (value);
599 FieldInfo fi = ((FieldExpr) member).FieldInfo;
602 Error_InvalidNamedArgument (member_name);
606 if (!IsValidArgumentType (member.Type)) {
607 Report.SymbolRelatedToPreviousError (fi);
608 Error_InvalidNamedAgrumentType (member_name);
613 if (!a.Expr.GetAttributableValue (member.Type, out value))
616 FieldBase fb = TypeManager.GetField (fi);
618 obsolete_attr = fb.GetObsoleteAttribute ();
620 obsolete_attr = AttributeTester.GetMemberObsoleteAttribute (fi);
622 field_values.Add (value);
623 field_infos.Add (fi);
626 if (obsolete_attr != null && !Owner.ResolveContext.IsInObsoleteScope)
627 AttributeTester.Report_ObsoleteMessage (obsolete_attr, member.GetSignatureForError (), member.Location);
630 prop_info_arr = new PropertyInfo [prop_infos.Count];
631 field_info_arr = new FieldInfo [field_infos.Count];
632 field_values_arr = new object [field_values.Count];
633 prop_values_arr = new object [prop_values.Count];
635 field_infos.CopyTo (field_info_arr, 0);
636 field_values.CopyTo (field_values_arr, 0);
638 prop_values.CopyTo (prop_values_arr, 0);
639 prop_infos.CopyTo (prop_info_arr, 0);
645 /// Get a string containing a list of valid targets for the attribute 'attr'
647 public string GetValidTargets ()
649 StringBuilder sb = new StringBuilder ();
650 AttributeTargets targets = GetAttributeUsage (Type).ValidOn;
652 if ((targets & AttributeTargets.Assembly) != 0)
653 sb.Append ("assembly, ");
655 if ((targets & AttributeTargets.Module) != 0)
656 sb.Append ("module, ");
658 if ((targets & AttributeTargets.Class) != 0)
659 sb.Append ("class, ");
661 if ((targets & AttributeTargets.Struct) != 0)
662 sb.Append ("struct, ");
664 if ((targets & AttributeTargets.Enum) != 0)
665 sb.Append ("enum, ");
667 if ((targets & AttributeTargets.Constructor) != 0)
668 sb.Append ("constructor, ");
670 if ((targets & AttributeTargets.Method) != 0)
671 sb.Append ("method, ");
673 if ((targets & AttributeTargets.Property) != 0)
674 sb.Append ("property, indexer, ");
676 if ((targets & AttributeTargets.Field) != 0)
677 sb.Append ("field, ");
679 if ((targets & AttributeTargets.Event) != 0)
680 sb.Append ("event, ");
682 if ((targets & AttributeTargets.Interface) != 0)
683 sb.Append ("interface, ");
685 if ((targets & AttributeTargets.Parameter) != 0)
686 sb.Append ("parameter, ");
688 if ((targets & AttributeTargets.Delegate) != 0)
689 sb.Append ("delegate, ");
691 if ((targets & AttributeTargets.ReturnValue) != 0)
692 sb.Append ("return, ");
695 if ((targets & AttributeTargets.GenericParameter) != 0)
696 sb.Append ("type parameter, ");
698 return sb.Remove (sb.Length - 2, 2).ToString ();
702 /// Returns AttributeUsage attribute based on types hierarchy
704 static AttributeUsageAttribute GetAttributeUsage (Type type)
706 AttributeUsageAttribute ua = usage_attr_cache [type] as AttributeUsageAttribute;
710 Class attr_class = TypeManager.LookupClass (type);
712 if (attr_class == null) {
713 object[] usage_attr = type.GetCustomAttributes (TypeManager.attribute_usage_type, true);
714 ua = (AttributeUsageAttribute)usage_attr [0];
715 usage_attr_cache.Add (type, ua);
720 if (attr_class.OptAttributes != null)
721 a = attr_class.OptAttributes.Search (TypeManager.attribute_usage_type);
724 if (attr_class.TypeBuilder.BaseType != TypeManager.attribute_type)
725 ua = GetAttributeUsage (attr_class.TypeBuilder.BaseType);
727 ua = DefaultUsageAttribute;
729 ua = a.GetAttributeUsageAttribute ();
732 usage_attr_cache.Add (type, ua);
736 AttributeUsageAttribute GetAttributeUsageAttribute ()
738 if (pos_values == null)
739 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
740 // But because a lot of attribute class code must be rewritten will be better to wait...
744 return DefaultUsageAttribute;
746 AttributeUsageAttribute usage_attribute = new AttributeUsageAttribute ((AttributeTargets)pos_values [0]);
748 object field = GetPropertyValue ("AllowMultiple");
750 usage_attribute.AllowMultiple = (bool)field;
752 field = GetPropertyValue ("Inherited");
754 usage_attribute.Inherited = (bool)field;
756 return usage_attribute;
760 /// Returns custom name of indexer
762 public string GetIndexerAttributeValue ()
764 if (pos_values == null)
765 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
766 // But because a lot of attribute class code must be rewritten will be better to wait...
772 return pos_values [0] as string;
776 /// Returns condition of ConditionalAttribute
778 public string GetConditionalAttributeValue ()
780 if (pos_values == null)
781 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
782 // But because a lot of attribute class code must be rewritten will be better to wait...
788 return (string)pos_values [0];
792 /// Creates the instance of ObsoleteAttribute from this attribute instance
794 public ObsoleteAttribute GetObsoleteAttribute ()
796 if (pos_values == null)
797 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
798 // But because a lot of attribute class code must be rewritten will be better to wait...
804 if (pos_values == null || pos_values.Length == 0)
805 return new ObsoleteAttribute ();
807 if (pos_values.Length == 1)
808 return new ObsoleteAttribute ((string)pos_values [0]);
810 return new ObsoleteAttribute ((string)pos_values [0], (bool)pos_values [1]);
814 /// Returns value of CLSCompliantAttribute contructor parameter but because the method can be called
815 /// before ApplyAttribute. We need to resolve the arguments.
816 /// This situation occurs when class deps is differs from Emit order.
818 public bool GetClsCompliantAttributeValue ()
820 if (pos_values == null)
821 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
822 // But because a lot of attribute class code must be rewritten will be better to wait...
828 return (bool)pos_values [0];
831 public Type GetCoClassAttributeValue ()
833 if (pos_values == null)
839 return (Type)pos_values [0];
842 public bool CheckTarget ()
844 string[] valid_targets = Owner.ValidAttributeTargets;
845 if (ExplicitTarget == null || ExplicitTarget == valid_targets [0]) {
846 Target = Owner.AttributeTargets;
850 // TODO: we can skip the first item
851 if (((IList) valid_targets).Contains (ExplicitTarget)) {
852 switch (ExplicitTarget) {
853 case "return": Target = AttributeTargets.ReturnValue; return true;
854 case "param": Target = AttributeTargets.Parameter; return true;
855 case "field": Target = AttributeTargets.Field; return true;
856 case "method": Target = AttributeTargets.Method; return true;
857 case "property": Target = AttributeTargets.Property; return true;
859 throw new InternalErrorException ("Unknown explicit target: " + ExplicitTarget);
862 StringBuilder sb = new StringBuilder ();
863 foreach (string s in valid_targets) {
867 sb.Remove (sb.Length - 2, 2);
868 Report.Error (657, Location, "`{0}' is not a valid attribute location for this declaration. " +
869 "Valid attribute locations for this declaration are `{1}'", ExplicitTarget, sb.ToString ());
874 /// Tests permitted SecurityAction for assembly or other types
876 protected virtual bool IsSecurityActionValid (bool for_assembly)
878 SecurityAction action = GetSecurityActionValue ();
881 case SecurityAction.Demand:
882 case SecurityAction.Assert:
883 case SecurityAction.Deny:
884 case SecurityAction.PermitOnly:
885 case SecurityAction.LinkDemand:
886 case SecurityAction.InheritanceDemand:
891 case SecurityAction.RequestMinimum:
892 case SecurityAction.RequestOptional:
893 case SecurityAction.RequestRefuse:
899 Error_AttributeEmitError ("SecurityAction is out of range");
903 Error_AttributeEmitError (String.Concat ("SecurityAction `", action, "' is not valid for this declaration"));
907 System.Security.Permissions.SecurityAction GetSecurityActionValue ()
909 return (SecurityAction)pos_values [0];
913 /// Creates instance of SecurityAttribute class and add result of CreatePermission method to permission table.
915 /// <returns></returns>
916 public void ExtractSecurityPermissionSet (ListDictionary permissions)
918 Type orig_assembly_type = null;
920 if (TypeManager.LookupDeclSpace (Type) != null) {
921 if (!RootContext.StdLib) {
922 orig_assembly_type = Type.GetType (Type.FullName);
924 string orig_version_path = Environment.GetEnvironmentVariable ("__SECURITY_BOOTSTRAP_DB");
925 if (orig_version_path == null) {
926 Error_AttributeEmitError ("security custom attributes can not be referenced from defining assembly");
930 if (orig_sec_assembly == null) {
931 string file = Path.Combine (orig_version_path, Driver.OutputFile);
932 orig_sec_assembly = Assembly.LoadFile (file);
935 orig_assembly_type = orig_sec_assembly.GetType (Type.FullName, true);
936 if (orig_assembly_type == null) {
937 Report.Warning (-112, 1, Location, "Self-referenced security attribute `{0}' " +
938 "was not found in previous version of assembly");
944 SecurityAttribute sa;
945 // For all non-selfreferencing security attributes we can avoid all hacks
946 if (orig_assembly_type == null) {
947 sa = (SecurityAttribute) Activator.CreateInstance (Type, pos_values);
949 if (prop_info_arr != null) {
950 for (int i = 0; i < prop_info_arr.Length; ++i) {
951 PropertyInfo pi = prop_info_arr [i];
952 pi.SetValue (sa, prop_values_arr [i], null);
956 // HACK: All security attributes have same ctor syntax
957 sa = (SecurityAttribute) Activator.CreateInstance (orig_assembly_type, new object[] { GetSecurityActionValue () } );
959 // All types are from newly created assembly but for invocation with old one we need to convert them
960 if (prop_info_arr != null) {
961 for (int i = 0; i < prop_info_arr.Length; ++i) {
962 PropertyInfo emited_pi = prop_info_arr [i];
963 // FIXME: We are missing return type filter
964 // TODO: pi can be null
965 PropertyInfo pi = orig_assembly_type.GetProperty (emited_pi.Name);
967 object old_instance = pi.PropertyType.IsEnum ?
968 System.Enum.ToObject (pi.PropertyType, prop_values_arr [i]) :
971 pi.SetValue (sa, old_instance, null);
977 perm = sa.CreatePermission ();
978 SecurityAction action = GetSecurityActionValue ();
980 // IS is correct because for corlib we are using an instance from old corlib
981 if (!(perm is System.Security.CodeAccessPermission)) {
983 case SecurityAction.Demand:
984 action = (SecurityAction)13;
986 case SecurityAction.LinkDemand:
987 action = (SecurityAction)14;
989 case SecurityAction.InheritanceDemand:
990 action = (SecurityAction)15;
995 PermissionSet ps = (PermissionSet)permissions [action];
997 if (sa is PermissionSetAttribute)
998 ps = new PermissionSet (sa.Unrestricted ? PermissionState.Unrestricted : PermissionState.None);
1000 ps = new PermissionSet (PermissionState.None);
1002 permissions.Add (action, ps);
1003 } else if (!ps.IsUnrestricted () && (sa is PermissionSetAttribute) && sa.Unrestricted) {
1004 ps = ps.Union (new PermissionSet (PermissionState.Unrestricted));
1005 permissions [action] = ps;
1007 ps.AddPermission (perm);
1010 static object GetValue (object value)
1012 if (value is EnumConstant)
1013 return ((EnumConstant) value).GetValue ();
1018 public object GetPropertyValue (string name)
1020 if (prop_info_arr == null)
1023 for (int i = 0; i < prop_info_arr.Length; ++i) {
1024 if (prop_info_arr [i].Name == name)
1025 return prop_values_arr [i];
1031 object GetFieldValue (string name)
1034 if (field_info_arr == null)
1037 foreach (FieldInfo fi in field_info_arr) {
1038 if (fi.Name == name)
1039 return GetValue (field_values_arr [i]);
1046 // Theoretically, we can get rid of this, since FieldBuilder.SetCustomAttribute()
1047 // and ParameterBuilder.SetCustomAttribute() are supposed to handle this attribute.
1048 // However, we can't, since it appears that the .NET 1.1 SRE hangs when given a MarshalAsAttribute.
1050 public UnmanagedMarshal GetMarshal (Attributable attr)
1052 UnmanagedType UnmanagedType;
1053 if (!RootContext.StdLib || pos_values [0].GetType () != typeof (UnmanagedType))
1054 UnmanagedType = (UnmanagedType) System.Enum.ToObject (typeof (UnmanagedType), pos_values [0]);
1056 UnmanagedType = (UnmanagedType) pos_values [0];
1058 object value = GetFieldValue ("SizeParamIndex");
1059 if (value != null && UnmanagedType != UnmanagedType.LPArray) {
1060 Error_AttributeEmitError ("SizeParamIndex field is not valid for the specified unmanaged type");
1064 object o = GetFieldValue ("ArraySubType");
1065 UnmanagedType array_sub_type = o == null ? (UnmanagedType) 0x50 /* NATIVE_MAX */ : (UnmanagedType) o;
1067 switch (UnmanagedType) {
1068 case UnmanagedType.CustomMarshaler: {
1069 MethodInfo define_custom = typeof (UnmanagedMarshal).GetMethod ("DefineCustom",
1070 BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
1071 if (define_custom == null) {
1072 Report.RuntimeMissingSupport (Location, "set marshal info");
1076 object [] args = new object [4];
1077 args [0] = GetFieldValue ("MarshalTypeRef");
1078 args [1] = GetFieldValue ("MarshalCookie");
1079 args [2] = GetFieldValue ("MarshalType");
1080 args [3] = Guid.Empty;
1081 return (UnmanagedMarshal) define_custom.Invoke (null, args);
1083 case UnmanagedType.LPArray: {
1084 object size_const = GetFieldValue ("SizeConst");
1085 object size_param_index = GetFieldValue ("SizeParamIndex");
1087 if ((size_const != null) || (size_param_index != null)) {
1088 MethodInfo define_array = typeof (UnmanagedMarshal).GetMethod ("DefineLPArrayInternal",
1089 BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
1090 if (define_array == null) {
1091 Report.RuntimeMissingSupport (Location, "set marshal info");
1095 object [] args = new object [3];
1096 args [0] = array_sub_type;
1097 args [1] = size_const == null ? -1 : size_const;
1098 args [2] = size_param_index == null ? -1 : size_param_index;
1099 return (UnmanagedMarshal) define_array.Invoke (null, args);
1102 return UnmanagedMarshal.DefineLPArray (array_sub_type);
1104 case UnmanagedType.SafeArray:
1105 return UnmanagedMarshal.DefineSafeArray (array_sub_type);
1107 case UnmanagedType.ByValArray:
1108 FieldBase fm = attr as FieldBase;
1110 Error_AttributeEmitError ("Specified unmanaged type is only valid on fields");
1113 return UnmanagedMarshal.DefineByValArray ((int) GetFieldValue ("SizeConst"));
1115 case UnmanagedType.ByValTStr:
1116 return UnmanagedMarshal.DefineByValTStr ((int) GetFieldValue ("SizeConst"));
1119 return UnmanagedMarshal.DefineUnmanagedMarshal (UnmanagedType);
1123 public CharSet GetCharSetValue ()
1125 return (CharSet)System.Enum.Parse (typeof (CharSet), pos_values [0].ToString ());
1128 public bool IsInternalMethodImplAttribute {
1130 if (Type != TypeManager.methodimpl_attr_type)
1133 MethodImplOptions options;
1134 if (pos_values[0].GetType () != typeof (MethodImplOptions))
1135 options = (MethodImplOptions)System.Enum.ToObject (typeof (MethodImplOptions), pos_values[0]);
1137 options = (MethodImplOptions)pos_values[0];
1139 return (options & MethodImplOptions.InternalCall) != 0;
1143 public LayoutKind GetLayoutKindValue ()
1145 if (!RootContext.StdLib || pos_values [0].GetType () != typeof (LayoutKind))
1146 return (LayoutKind)System.Enum.ToObject (typeof (LayoutKind), pos_values [0]);
1148 return (LayoutKind)pos_values [0];
1151 public object GetParameterDefaultValue ()
1153 return pos_values [0];
1156 public override bool Equals (object obj)
1158 Attribute a = obj as Attribute;
1162 return Type == a.Type && Target == a.Target;
1165 public override int GetHashCode ()
1167 return base.GetHashCode ();
1171 /// Emit attribute for Attributable symbol
1173 public void Emit (ListDictionary allEmitted)
1175 CustomAttributeBuilder cb = Resolve ();
1179 AttributeUsageAttribute usage_attr = GetAttributeUsage (Type);
1180 if ((usage_attr.ValidOn & Target) == 0) {
1181 Report.Error (592, Location, "The attribute `{0}' is not valid on this declaration type. " +
1182 "It is valid on `{1}' declarations only",
1183 GetSignatureForError (), GetValidTargets ());
1188 foreach (Attributable owner in owners)
1189 owner.ApplyAttributeBuilder (this, cb);
1191 catch (Exception e) {
1192 Error_AttributeEmitError (e.Message);
1196 if (!usage_attr.AllowMultiple && allEmitted != null) {
1197 if (allEmitted.Contains (this)) {
1198 ArrayList a = allEmitted [this] as ArrayList;
1200 a = new ArrayList (2);
1201 allEmitted [this] = a;
1205 allEmitted.Add (this, null);
1209 if (!RootContext.VerifyClsCompliance)
1212 // Here we are testing attribute arguments for array usage (error 3016)
1213 if (Owner.IsClsComplianceRequired ()) {
1214 if (PosArguments != null) {
1215 foreach (Argument arg in PosArguments) {
1216 // Type is undefined (was error 246)
1217 if (arg.Type == null)
1220 if (arg.Type.IsArray) {
1221 Report.Error (3016, Location, "Arrays as attribute arguments are not CLS-compliant");
1227 if (NamedArguments == null)
1230 foreach (DictionaryEntry de in NamedArguments) {
1231 Argument arg = (Argument) de.Value;
1233 // Type is undefined (was error 246)
1234 if (arg.Type == null)
1237 if (arg.Type.IsArray) {
1238 Report.Error (3016, Location, "Arrays as attribute arguments are not CLS-compliant");
1245 private Expression GetValue ()
1247 if (PosArguments == null || PosArguments.Count < 1)
1250 return ((Argument) PosArguments [0]).Expr;
1253 public string GetString ()
1255 Expression e = GetValue ();
1256 if (e is StringConstant)
1257 return ((StringConstant)e).Value;
1261 public bool GetBoolean ()
1263 Expression e = GetValue ();
1264 if (e is BoolConstant)
1265 return ((BoolConstant)e).Value;
1269 public Type GetArgumentType ()
1271 TypeOf e = GetValue () as TypeOf;
1274 return e.TypeArgument;
1277 public override Expression CreateExpressionTree (EmitContext ec)
1279 throw new NotSupportedException ("ET");
1282 public override Expression DoResolve (EmitContext ec)
1284 throw new NotImplementedException ();
1287 public override void Emit (EmitContext ec)
1289 throw new NotImplementedException ();
1295 /// For global attributes (assembly, module) we need special handling.
1296 /// Attributes can be located in the several files
1298 public class GlobalAttribute : Attribute
1300 public readonly NamespaceEntry ns;
1302 public GlobalAttribute (NamespaceEntry ns, string target,
1303 Expression left_expr, string identifier, object[] args, Location loc, bool nameEscaped):
1304 base (target, left_expr, identifier, args, loc, nameEscaped)
1307 this.owners = new Attributable[1];
1310 public override void AttachTo (Attributable owner)
1312 if (ExplicitTarget == "assembly") {
1313 owners [0] = CodeGen.Assembly;
1316 if (ExplicitTarget == "module") {
1317 owners [0] = CodeGen.Module;
1320 throw new NotImplementedException ("Unknown global explicit target " + ExplicitTarget);
1325 // RootContext.ToplevelTypes has a single NamespaceEntry which gets overwritten
1326 // each time a new file is parsed. However, we need to use the NamespaceEntry
1327 // in effect where the attribute was used. Since code elsewhere cannot assume
1328 // that the NamespaceEntry is right, just overwrite it.
1330 // Precondition: RootContext.ToplevelTypes == null
1332 if (RootContext.ToplevelTypes.NamespaceEntry != null)
1333 throw new InternalErrorException (Location + " non-null NamespaceEntry");
1335 RootContext.ToplevelTypes.NamespaceEntry = ns;
1338 protected override bool IsSecurityActionValid (bool for_assembly)
1340 return base.IsSecurityActionValid (true);
1345 RootContext.ToplevelTypes.NamespaceEntry = null;
1348 protected override TypeExpr ResolveAsTypeTerminal (Expression expr, IResolveContext ec, bool silent)
1352 return base.ResolveAsTypeTerminal (expr, ec, silent);
1359 protected override ConstructorInfo ResolveConstructor (EmitContext ec)
1363 return base.ResolveConstructor (ec);
1370 protected override bool ResolveNamedArguments (EmitContext ec)
1374 return base.ResolveNamedArguments (ec);
1382 public class Attributes {
1383 public readonly ArrayList Attrs;
1385 public Attributes (Attribute a)
1387 Attrs = new ArrayList ();
1391 public Attributes (ArrayList attrs)
1396 public void AddAttributes (ArrayList attrs)
1398 Attrs.AddRange (attrs);
1401 public void AttachTo (Attributable attributable)
1403 foreach (Attribute a in Attrs)
1404 a.AttachTo (attributable);
1408 /// Checks whether attribute target is valid for the current element
1410 public bool CheckTargets ()
1412 foreach (Attribute a in Attrs) {
1413 if (!a.CheckTarget ())
1419 public Attribute Search (Type t)
1421 foreach (Attribute a in Attrs) {
1422 if (a.ResolveType () == t)
1429 /// Returns all attributes of type 't'. Use it when attribute is AllowMultiple = true
1431 public Attribute[] SearchMulti (Type t)
1433 ArrayList ar = null;
1435 foreach (Attribute a in Attrs) {
1436 if (a.ResolveType () == t) {
1438 ar = new ArrayList ();
1443 return ar == null ? null : ar.ToArray (typeof (Attribute)) as Attribute[];
1450 ListDictionary ld = Attrs.Count > 1 ? new ListDictionary () : null;
1452 foreach (Attribute a in Attrs)
1455 if (ld == null || ld.Count == 0)
1458 foreach (DictionaryEntry d in ld) {
1459 if (d.Value == null)
1462 foreach (Attribute collision in (ArrayList)d.Value)
1463 Report.SymbolRelatedToPreviousError (collision.Location, "");
1465 Attribute a = (Attribute)d.Key;
1466 Report.Error (579, a.Location, "The attribute `{0}' cannot be applied multiple times",
1467 a.GetSignatureForError ());
1471 public bool Contains (Type t)
1473 return Search (t) != null;
1478 /// Helper class for attribute verification routine.
1480 sealed class AttributeTester
1482 static PtrHashtable analyzed_types;
1483 static PtrHashtable analyzed_types_obsolete;
1484 static PtrHashtable analyzed_member_obsolete;
1485 static PtrHashtable analyzed_method_excluded;
1486 static PtrHashtable fixed_buffer_cache;
1488 static object TRUE = new object ();
1489 static object FALSE = new object ();
1491 static AttributeTester ()
1496 private AttributeTester ()
1500 public static void Reset ()
1502 analyzed_types = new PtrHashtable ();
1503 analyzed_types_obsolete = new PtrHashtable ();
1504 analyzed_member_obsolete = new PtrHashtable ();
1505 analyzed_method_excluded = new PtrHashtable ();
1506 fixed_buffer_cache = new PtrHashtable ();
1509 public enum Result {
1516 /// Returns true if parameters of two compared methods are CLS-Compliant.
1517 /// It tests differing only in ref or out, or in array rank.
1519 public static Result AreOverloadedMethodParamsClsCompliant (Type[] types_a, Type[] types_b)
1521 if (types_a == null || types_b == null)
1524 if (types_a.Length != types_b.Length)
1527 Result result = Result.Ok;
1528 for (int i = 0; i < types_b.Length; ++i) {
1529 Type aType = types_a [i];
1530 Type bType = types_b [i];
1532 if (aType.IsArray && bType.IsArray) {
1533 Type a_el_type = aType.GetElementType ();
1534 Type b_el_type = bType.GetElementType ();
1535 if (aType.GetArrayRank () != bType.GetArrayRank () && a_el_type == b_el_type) {
1536 result = Result.RefOutArrayError;
1540 if (a_el_type.IsArray || b_el_type.IsArray) {
1541 result = Result.ArrayArrayError;
1546 Type aBaseType = aType;
1547 bool is_either_ref_or_out = false;
1549 if (aType.IsByRef || aType.IsPointer) {
1550 aBaseType = aType.GetElementType ();
1551 is_either_ref_or_out = true;
1554 Type bBaseType = bType;
1555 if (bType.IsByRef || bType.IsPointer)
1557 bBaseType = bType.GetElementType ();
1558 is_either_ref_or_out = !is_either_ref_or_out;
1561 if (aBaseType != bBaseType)
1564 if (is_either_ref_or_out)
1565 result = Result.RefOutArrayError;
1571 /// This method tests the CLS compliance of external types. It doesn't test type visibility.
1573 public static bool IsClsCompliant (Type type)
1578 object type_compliance = analyzed_types[type];
1579 if (type_compliance != null)
1580 return type_compliance == TRUE;
1582 if (type.IsPointer) {
1583 analyzed_types.Add (type, null);
1588 if (type.IsArray || type.IsByRef) {
1589 result = IsClsCompliant (TypeManager.GetElementType (type));
1590 } else if (TypeManager.IsNullableType (type)) {
1591 result = IsClsCompliant (TypeManager.GetTypeArguments (type) [0]);
1593 result = AnalyzeTypeCompliance (type);
1595 analyzed_types.Add (type, result ? TRUE : FALSE);
1600 /// Returns IFixedBuffer implementation if field is fixed buffer else null.
1602 public static IFixedBuffer GetFixedBuffer (FieldInfo fi)
1604 // Fixed buffer helper type is generated as value type
1605 if (!fi.FieldType.IsValueType)
1608 FieldBase fb = TypeManager.GetField (fi);
1610 return fb as IFixedBuffer;
1613 if (TypeManager.GetConstant (fi) != null)
1616 object o = fixed_buffer_cache [fi];
1618 if (TypeManager.fixed_buffer_attr_type == null)
1621 if (!fi.IsDefined (TypeManager.fixed_buffer_attr_type, false)) {
1622 fixed_buffer_cache.Add (fi, FALSE);
1626 IFixedBuffer iff = new FixedFieldExternal (fi);
1627 fixed_buffer_cache.Add (fi, iff);
1634 return (IFixedBuffer)o;
1637 public static void VerifyModulesClsCompliance ()
1639 Module[] modules = RootNamespace.Global.Modules;
1640 if (modules == null)
1643 // The first module is generated assembly
1644 for (int i = 1; i < modules.Length; ++i) {
1645 Module module = modules [i];
1646 if (!GetClsCompliantAttributeValue (module, null)) {
1647 Report.Error (3013, "Added modules must be marked with the CLSCompliant attribute " +
1648 "to match the assembly", module.Name);
1654 public static Type GetImportedIgnoreCaseClsType (string name)
1656 foreach (Assembly a in RootNamespace.Global.Assemblies) {
1657 Type t = a.GetType (name, false, true);
1661 if (IsClsCompliant (t))
1667 static bool GetClsCompliantAttributeValue (ICustomAttributeProvider attribute_provider, Assembly a)
1669 if (TypeManager.cls_compliant_attribute_type == null)
1672 object[] cls_attr = attribute_provider.GetCustomAttributes (TypeManager.cls_compliant_attribute_type, false);
1673 if (cls_attr.Length == 0) {
1677 return GetClsCompliantAttributeValue (a, null);
1680 return ((CLSCompliantAttribute)cls_attr [0]).IsCompliant;
1683 static bool AnalyzeTypeCompliance (Type type)
1685 type = TypeManager.DropGenericTypeArguments (type);
1686 DeclSpace ds = TypeManager.LookupDeclSpace (type);
1688 return ds.IsClsComplianceRequired ();
1691 if (TypeManager.IsGenericParameter (type))
1694 return GetClsCompliantAttributeValue (type, type.Assembly);
1697 // Registers the core type as we assume that they will never be obsolete which
1698 // makes things easier for bootstrap and faster (we don't need to query Obsolete attribute).
1699 public static void RegisterNonObsoleteType (Type type)
1701 analyzed_types_obsolete [type] = FALSE;
1705 /// Returns instance of ObsoleteAttribute when type is obsolete
1707 public static ObsoleteAttribute GetObsoleteAttribute (Type type)
1709 object type_obsolete = analyzed_types_obsolete [type];
1710 if (type_obsolete == FALSE)
1713 if (type_obsolete != null)
1714 return (ObsoleteAttribute)type_obsolete;
1716 ObsoleteAttribute result = null;
1717 if (TypeManager.HasElementType (type)) {
1718 result = GetObsoleteAttribute (TypeManager.GetElementType (type));
1719 } else if (TypeManager.IsGenericParameter (type) || TypeManager.IsGenericType (type))
1722 DeclSpace type_ds = TypeManager.LookupDeclSpace (type);
1724 // Type is external, we can get attribute directly
1725 if (type_ds == null) {
1726 if (TypeManager.obsolete_attribute_type != null) {
1727 object [] attribute = type.GetCustomAttributes (TypeManager.obsolete_attribute_type, false);
1728 if (attribute.Length == 1)
1729 result = (ObsoleteAttribute) attribute [0];
1732 result = type_ds.GetObsoleteAttribute ();
1736 // Cannot use .Add because of corlib bootstrap
1737 analyzed_types_obsolete [type] = result == null ? FALSE : result;
1742 /// Returns instance of ObsoleteAttribute when method is obsolete
1744 public static ObsoleteAttribute GetMethodObsoleteAttribute (MethodBase mb)
1746 IMethodData mc = TypeManager.GetMethod (mb);
1748 return mc.GetObsoleteAttribute ();
1750 // compiler generated methods are not registered by AddMethod
1751 if (mb.DeclaringType is TypeBuilder)
1754 MemberInfo mi = TypeManager.GetPropertyFromAccessor (mb);
1756 return GetMemberObsoleteAttribute (mi);
1758 mi = TypeManager.GetEventFromAccessor (mb);
1760 return GetMemberObsoleteAttribute (mi);
1762 return GetMemberObsoleteAttribute (mb);
1766 /// Returns instance of ObsoleteAttribute when member is obsolete
1768 public static ObsoleteAttribute GetMemberObsoleteAttribute (MemberInfo mi)
1770 object type_obsolete = analyzed_member_obsolete [mi];
1771 if (type_obsolete == FALSE)
1774 if (type_obsolete != null)
1775 return (ObsoleteAttribute)type_obsolete;
1777 if ((mi.DeclaringType is TypeBuilder) || TypeManager.IsGenericType (mi.DeclaringType))
1780 if (TypeManager.obsolete_attribute_type == null)
1783 ObsoleteAttribute oa = System.Attribute.GetCustomAttribute (mi, TypeManager.obsolete_attribute_type, false)
1784 as ObsoleteAttribute;
1785 analyzed_member_obsolete.Add (mi, oa == null ? FALSE : oa);
1790 /// Common method for Obsolete error/warning reporting.
1792 public static void Report_ObsoleteMessage (ObsoleteAttribute oa, string member, Location loc)
1795 Report.Error (619, loc, "`{0}' is obsolete: `{1}'", member, oa.Message);
1799 if (oa.Message == null || oa.Message.Length == 0) {
1800 Report.Warning (612, 1, loc, "`{0}' is obsolete", member);
1803 Report.Warning (618, 2, loc, "`{0}' is obsolete: `{1}'", member, oa.Message);
1806 public static bool IsConditionalMethodExcluded (MethodBase mb)
1808 object excluded = analyzed_method_excluded [mb];
1809 if (excluded != null)
1810 return excluded == TRUE ? true : false;
1812 if (TypeManager.conditional_attribute_type == null)
1815 ConditionalAttribute[] attrs = mb.GetCustomAttributes (TypeManager.conditional_attribute_type, true)
1816 as ConditionalAttribute[];
1817 if (attrs.Length == 0) {
1818 analyzed_method_excluded.Add (mb, FALSE);
1822 foreach (ConditionalAttribute a in attrs) {
1823 if (RootContext.AllDefines.Contains (a.ConditionString)) {
1824 analyzed_method_excluded.Add (mb, FALSE);
1828 analyzed_method_excluded.Add (mb, TRUE);
1833 /// Analyzes class whether it has attribute which has ConditionalAttribute
1834 /// and its condition is not defined.
1836 public static bool IsAttributeExcluded (Type type)
1841 Class class_decl = TypeManager.LookupDeclSpace (type) as Class;
1843 // TODO: add caching
1844 // TODO: merge all Type bases attribute caching to one cache to save memory
1845 if (class_decl == null && TypeManager.conditional_attribute_type != null) {
1846 object[] attributes = type.GetCustomAttributes (TypeManager.conditional_attribute_type, false);
1847 foreach (ConditionalAttribute ca in attributes) {
1848 if (RootContext.AllDefines.Contains (ca.ConditionString))
1851 return attributes.Length > 0;
1854 return class_decl.IsExcluded ();
1857 public static Type GetCoClassAttribute (Type type)
1859 TypeContainer tc = TypeManager.LookupInterface (type);
1861 if (TypeManager.coclass_attr_type == null)
1864 object[] o = type.GetCustomAttributes (TypeManager.coclass_attr_type, false);
1867 return ((System.Runtime.InteropServices.CoClassAttribute)o[0]).CoClass;
1870 if (tc.OptAttributes == null || TypeManager.coclass_attr_type == null)
1873 Attribute a = tc.OptAttributes.Search (TypeManager.coclass_attr_type);
1877 return a.GetCoClassAttributeValue ();