2 // attribute.cs: Attribute Handler
4 // Author: Ravi Pratap (ravi@ximian.com)
5 // Marek Safar (marek.safar@seznam.cz)
7 // Licensed under the terms of the GNU GPL
9 // (C) 2001 Ximian, Inc (http://www.ximian.com)
14 using System.Diagnostics;
15 using System.Collections;
16 using System.Collections.Specialized;
17 using System.Reflection;
18 using System.Reflection.Emit;
19 using System.Runtime.InteropServices;
20 using System.Runtime.CompilerServices;
21 using System.Security;
22 using System.Security.Permissions;
26 namespace Mono.CSharp {
29 /// Base class for objects that can have Attributes applied to them.
31 public abstract class Attributable {
33 /// Attributes for this type
35 protected Attributes attributes;
37 public Attributable (Attributes attrs)
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 readonly 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 bool IsValidArgumentType (Type t)
299 t = t.GetElementType ();
301 return TypeManager.IsPrimitiveType (t) ||
302 TypeManager.IsEnumType (t) ||
303 t == TypeManager.string_type ||
304 t == TypeManager.object_type ||
305 t == TypeManager.type_type;
308 [Conditional ("GMCS_SOURCE")]
309 void ApplyModuleCharSet ()
311 if (Type != TypeManager.dllimport_type)
314 if (!CodeGen.Module.HasDefaultCharSet)
317 const string CharSetEnumMember = "CharSet";
318 if (NamedArguments == null) {
319 NamedArguments = new ArrayList (1);
321 foreach (DictionaryEntry de in NamedArguments) {
322 if ((string)de.Key == CharSetEnumMember)
327 NamedArguments.Add (new DictionaryEntry (CharSetEnumMember,
328 new Argument (Constant.CreateConstant (typeof (CharSet), CodeGen.Module.DefaultCharSet, Location))));
331 public CustomAttributeBuilder Resolve ()
336 resolve_error = true;
339 ResolveAttributeType ();
344 if (Type.IsAbstract) {
345 Report.Error (653, Location, "Cannot apply attribute class `{0}' because it is abstract", GetSignatureForError ());
349 ObsoleteAttribute obsolete_attr = AttributeTester.GetObsoleteAttribute (Type);
350 if (obsolete_attr != null) {
351 AttributeTester.Report_ObsoleteMessage (obsolete_attr, TypeManager.CSharpName (Type), Location);
354 if (PosArguments == null && NamedArguments == null) {
355 object o = att_cache [Type];
357 resolve_error = false;
358 return (CustomAttributeBuilder)o;
362 Attributable owner = Owner;
363 DeclSpace ds = owner.ResolveContext as DeclSpace;
365 ds = owner.ResolveContext.DeclContainer;
367 EmitContext ec = new EmitContext (owner.ResolveContext, ds, owner.ResolveContext.DeclContainer,
368 Location, null, typeof (Attribute), owner.ResolveContext.DeclContainer.ModFlags, false);
369 ec.IsAnonymousMethodAllowed = false;
371 ConstructorInfo ctor = ResolveConstructor (ec);
373 if (Type is TypeBuilder &&
374 TypeManager.LookupDeclSpace (Type).MemberCache == null)
375 // The attribute type has been DefineType'd, but not Defined. Let's not treat it as an error.
376 // It'll be resolved again when the attached-to entity is emitted.
377 resolve_error = false;
381 ApplyModuleCharSet ();
383 CustomAttributeBuilder cb;
385 // SRE does not allow private ctor but we want to report all source code errors
389 if (NamedArguments == null) {
390 cb = new CustomAttributeBuilder (ctor, pos_values);
392 if (pos_values.Length == 0)
393 att_cache.Add (Type, cb);
395 resolve_error = false;
399 if (!ResolveNamedArguments (ec)) {
403 cb = new CustomAttributeBuilder (ctor, pos_values,
404 prop_info_arr, prop_values_arr,
405 field_info_arr, field_values_arr);
407 resolve_error = false;
411 Error_AttributeArgumentNotValid (Location);
416 protected virtual ConstructorInfo ResolveConstructor (EmitContext ec)
418 if (PosArguments != null) {
419 for (int i = 0; i < PosArguments.Count; i++) {
420 Argument a = (Argument) PosArguments [i];
422 if (!a.Resolve (ec, Location))
427 MethodGroupExpr mg = MemberLookupFinal (ec, ec.ContainerType,
428 Type, ".ctor", MemberTypes.Constructor,
429 BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly,
430 Location) as MethodGroupExpr;
435 mg = mg.OverloadResolve (ec, PosArguments, false, Location);
439 ConstructorInfo constructor = (ConstructorInfo)mg;
441 // TODO: move to OverloadResolve
442 ObsoleteAttribute oa = AttributeTester.GetMethodObsoleteAttribute (constructor);
443 if (oa != null && !Owner.ResolveContext.IsInObsoleteScope) {
444 AttributeTester.Report_ObsoleteMessage (oa, mg.GetSignatureForError (), mg.Location);
447 if (PosArguments == null) {
448 pos_values = EmptyObject;
452 ParameterData pd = TypeManager.GetParameterData (constructor);
454 int pos_arg_count = PosArguments.Count;
455 int last_real_param = pd.Count;
457 pos_values = new object [pos_arg_count];
460 // When the params is not filled we need to put one
461 if (last_real_param > pos_arg_count) {
462 object [] new_pos_values = new object [pos_arg_count + 1];
463 pos_values.CopyTo (new_pos_values, 0);
464 new_pos_values [pos_arg_count] = new object [] {} ;
465 pos_values = new_pos_values;
470 for (int j = 0; j < pos_arg_count; ++j) {
471 Argument a = (Argument) PosArguments [j];
473 if (!a.Expr.GetAttributableValue (a.Type, out pos_values [j]))
476 if (j < last_real_param)
479 if (j == last_real_param) {
480 object [] array = new object [pos_arg_count - last_real_param];
481 array [0] = pos_values [j];
482 pos_values [j] = array;
486 object [] params_array = (object []) pos_values [last_real_param];
487 params_array [j - last_real_param] = pos_values [j];
490 // Adjust the size of the pos_values if it had params
491 if (last_real_param != pos_arg_count) {
492 object [] new_pos_values = new object [last_real_param + 1];
493 Array.Copy (pos_values, new_pos_values, last_real_param + 1);
494 pos_values = new_pos_values;
497 // Here we do the checks which should be done by corlib or by runtime.
498 // However Zoltan doesn't like it and every Mono compiler has to do it again.
500 if (Type == TypeManager.guid_attr_type) {
502 new Guid ((string)pos_values [0]);
504 catch (Exception e) {
505 Error_AttributeEmitError (e.Message);
510 if (Type == TypeManager.attribute_usage_type && (int)pos_values [0] == 0) {
511 Report.Error (591, Location, "Invalid value for argument to `System.AttributeUsage' attribute");
515 if (Type == TypeManager.indexer_name_type || Type == TypeManager.conditional_attribute_type) {
516 if (!Tokenizer.IsValidIdentifier ((string)pos_values [0])) {
517 Report.Error (633, ((Argument)PosArguments[0]).Expr.Location,
518 "The argument to the `{0}' attribute must be a valid identifier", GetSignatureForError ());
523 if (Type == TypeManager.methodimpl_attr_type && pos_values.Length == 1 &&
524 pd.ParameterType (0) == TypeManager.short_type &&
525 !System.Enum.IsDefined (typeof (MethodImplOptions), pos_values [0].ToString ())) {
526 Error_AttributeEmitError ("Incorrect argument value.");
530 return (ConstructorInfo)constructor;
533 protected virtual bool ResolveNamedArguments (EmitContext ec)
535 int named_arg_count = NamedArguments.Count;
537 ArrayList field_infos = new ArrayList (named_arg_count);
538 ArrayList prop_infos = new ArrayList (named_arg_count);
539 ArrayList field_values = new ArrayList (named_arg_count);
540 ArrayList prop_values = new ArrayList (named_arg_count);
542 ArrayList seen_names = new ArrayList(named_arg_count);
544 foreach (DictionaryEntry de in NamedArguments) {
545 string member_name = (string) de.Key;
547 if (seen_names.Contains(member_name)) {
548 Report.Error(643, Location, "'" + member_name + "' duplicate named attribute argument");
551 seen_names.Add(member_name);
553 Argument a = (Argument) de.Value;
554 if (!a.Resolve (ec, Location))
557 Expression member = Expression.MemberLookup (
558 ec.ContainerType, Type, member_name,
559 MemberTypes.Field | MemberTypes.Property,
560 BindingFlags.Public | BindingFlags.Instance,
563 if (member == null) {
564 member = Expression.MemberLookup (ec.ContainerType, Type, member_name,
565 MemberTypes.Field | MemberTypes.Property, BindingFlags.NonPublic | BindingFlags.Instance,
568 if (member != null) {
569 Report.SymbolRelatedToPreviousError (member.Type);
570 Expression.ErrorIsInaccesible (Location, member.GetSignatureForError ());
576 Expression.Error_TypeDoesNotContainDefinition (Location, Type, member_name);
580 if (!(member is PropertyExpr || member is FieldExpr)) {
581 Error_InvalidNamedArgument (member_name);
585 if (a.Expr is TypeParameterExpr){
586 Error_TypeParameterInAttribute (Location);
590 ObsoleteAttribute obsolete_attr;
592 if (member is PropertyExpr) {
593 PropertyInfo pi = ((PropertyExpr) member).PropertyInfo;
595 if (!pi.CanWrite || !pi.CanRead) {
596 Report.SymbolRelatedToPreviousError (pi);
597 Error_InvalidNamedArgument (member_name);
601 if (!IsValidArgumentType (pi.PropertyType)) {
602 Report.SymbolRelatedToPreviousError (pi);
603 Error_InvalidNamedAgrumentType (member_name);
608 if (!a.Expr.GetAttributableValue (pi.PropertyType, out value))
611 PropertyBase pb = TypeManager.GetProperty (pi);
613 obsolete_attr = pb.GetObsoleteAttribute ();
615 obsolete_attr = AttributeTester.GetMemberObsoleteAttribute (pi);
617 prop_values.Add (value);
621 FieldInfo fi = ((FieldExpr) member).FieldInfo;
624 Error_InvalidNamedArgument (member_name);
628 if (!IsValidArgumentType (fi.FieldType)) {
629 Report.SymbolRelatedToPreviousError (fi);
630 Error_InvalidNamedAgrumentType (member_name);
635 if (!a.Expr.GetAttributableValue (fi.FieldType, out value))
638 FieldBase fb = TypeManager.GetField (fi);
640 obsolete_attr = fb.GetObsoleteAttribute ();
642 obsolete_attr = AttributeTester.GetMemberObsoleteAttribute (fi);
644 field_values.Add (value);
645 field_infos.Add (fi);
648 if (obsolete_attr != null && !Owner.ResolveContext.IsInObsoleteScope)
649 AttributeTester.Report_ObsoleteMessage (obsolete_attr, member.GetSignatureForError (), member.Location);
652 prop_info_arr = new PropertyInfo [prop_infos.Count];
653 field_info_arr = new FieldInfo [field_infos.Count];
654 field_values_arr = new object [field_values.Count];
655 prop_values_arr = new object [prop_values.Count];
657 field_infos.CopyTo (field_info_arr, 0);
658 field_values.CopyTo (field_values_arr, 0);
660 prop_values.CopyTo (prop_values_arr, 0);
661 prop_infos.CopyTo (prop_info_arr, 0);
667 /// Get a string containing a list of valid targets for the attribute 'attr'
669 public string GetValidTargets ()
671 StringBuilder sb = new StringBuilder ();
672 AttributeTargets targets = GetAttributeUsage (Type).ValidOn;
674 if ((targets & AttributeTargets.Assembly) != 0)
675 sb.Append ("assembly, ");
677 if ((targets & AttributeTargets.Module) != 0)
678 sb.Append ("module, ");
680 if ((targets & AttributeTargets.Class) != 0)
681 sb.Append ("class, ");
683 if ((targets & AttributeTargets.Struct) != 0)
684 sb.Append ("struct, ");
686 if ((targets & AttributeTargets.Enum) != 0)
687 sb.Append ("enum, ");
689 if ((targets & AttributeTargets.Constructor) != 0)
690 sb.Append ("constructor, ");
692 if ((targets & AttributeTargets.Method) != 0)
693 sb.Append ("method, ");
695 if ((targets & AttributeTargets.Property) != 0)
696 sb.Append ("property, indexer, ");
698 if ((targets & AttributeTargets.Field) != 0)
699 sb.Append ("field, ");
701 if ((targets & AttributeTargets.Event) != 0)
702 sb.Append ("event, ");
704 if ((targets & AttributeTargets.Interface) != 0)
705 sb.Append ("interface, ");
707 if ((targets & AttributeTargets.Parameter) != 0)
708 sb.Append ("parameter, ");
710 if ((targets & AttributeTargets.Delegate) != 0)
711 sb.Append ("delegate, ");
713 if ((targets & AttributeTargets.ReturnValue) != 0)
714 sb.Append ("return, ");
717 if ((targets & AttributeTargets.GenericParameter) != 0)
718 sb.Append ("type parameter, ");
720 return sb.Remove (sb.Length - 2, 2).ToString ();
724 /// Returns AttributeUsage attribute based on types hierarchy
726 static AttributeUsageAttribute GetAttributeUsage (Type type)
728 AttributeUsageAttribute ua = usage_attr_cache [type] as AttributeUsageAttribute;
732 Class attr_class = TypeManager.LookupClass (type);
734 if (attr_class == null) {
735 object[] usage_attr = type.GetCustomAttributes (TypeManager.attribute_usage_type, true);
736 ua = (AttributeUsageAttribute)usage_attr [0];
737 usage_attr_cache.Add (type, ua);
742 if (attr_class.OptAttributes != null)
743 a = attr_class.OptAttributes.Search (TypeManager.attribute_usage_type);
746 if (attr_class.TypeBuilder.BaseType != TypeManager.attribute_type)
747 ua = GetAttributeUsage (attr_class.TypeBuilder.BaseType);
749 ua = DefaultUsageAttribute;
751 ua = a.GetAttributeUsageAttribute ();
754 usage_attr_cache.Add (type, ua);
758 AttributeUsageAttribute GetAttributeUsageAttribute ()
760 if (pos_values == null)
761 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
762 // But because a lot of attribute class code must be rewritten will be better to wait...
766 return DefaultUsageAttribute;
768 AttributeUsageAttribute usage_attribute = new AttributeUsageAttribute ((AttributeTargets)pos_values [0]);
770 object field = GetPropertyValue ("AllowMultiple");
772 usage_attribute.AllowMultiple = (bool)field;
774 field = GetPropertyValue ("Inherited");
776 usage_attribute.Inherited = (bool)field;
778 return usage_attribute;
782 /// Returns custom name of indexer
784 public string GetIndexerAttributeValue ()
786 if (pos_values == null)
787 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
788 // But because a lot of attribute class code must be rewritten will be better to wait...
794 return pos_values [0] as string;
798 /// Returns condition of ConditionalAttribute
800 public string GetConditionalAttributeValue ()
802 if (pos_values == null)
803 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
804 // But because a lot of attribute class code must be rewritten will be better to wait...
810 return (string)pos_values [0];
814 /// Creates the instance of ObsoleteAttribute from this attribute instance
816 public ObsoleteAttribute GetObsoleteAttribute ()
818 if (pos_values == null)
819 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
820 // But because a lot of attribute class code must be rewritten will be better to wait...
826 if (pos_values == null || pos_values.Length == 0)
827 return new ObsoleteAttribute ();
829 if (pos_values.Length == 1)
830 return new ObsoleteAttribute ((string)pos_values [0]);
832 return new ObsoleteAttribute ((string)pos_values [0], (bool)pos_values [1]);
836 /// Returns value of CLSCompliantAttribute contructor parameter but because the method can be called
837 /// before ApplyAttribute. We need to resolve the arguments.
838 /// This situation occurs when class deps is differs from Emit order.
840 public bool GetClsCompliantAttributeValue ()
842 if (pos_values == null)
843 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
844 // But because a lot of attribute class code must be rewritten will be better to wait...
850 return (bool)pos_values [0];
853 public Type GetCoClassAttributeValue ()
855 if (pos_values == null)
861 return (Type)pos_values [0];
864 public bool CheckTarget ()
866 string[] valid_targets = Owner.ValidAttributeTargets;
867 if (ExplicitTarget == null || ExplicitTarget == valid_targets [0]) {
868 Target = Owner.AttributeTargets;
872 // TODO: we can skip the first item
873 if (((IList) valid_targets).Contains (ExplicitTarget)) {
874 switch (ExplicitTarget) {
875 case "return": Target = AttributeTargets.ReturnValue; return true;
876 case "param": Target = AttributeTargets.Parameter; return true;
877 case "field": Target = AttributeTargets.Field; return true;
878 case "method": Target = AttributeTargets.Method; return true;
879 case "property": Target = AttributeTargets.Property; return true;
881 throw new InternalErrorException ("Unknown explicit target: " + ExplicitTarget);
884 StringBuilder sb = new StringBuilder ();
885 foreach (string s in valid_targets) {
889 sb.Remove (sb.Length - 2, 2);
890 Report.Error (657, Location, "`{0}' is not a valid attribute location for this declaration. " +
891 "Valid attribute locations for this declaration are `{1}'", ExplicitTarget, sb.ToString ());
896 /// Tests permitted SecurityAction for assembly or other types
898 public bool CheckSecurityActionValidity (bool for_assembly)
900 SecurityAction action = GetSecurityActionValue ();
903 case SecurityAction.Demand:
904 case SecurityAction.Assert:
905 case SecurityAction.Deny:
906 case SecurityAction.PermitOnly:
907 case SecurityAction.LinkDemand:
908 case SecurityAction.InheritanceDemand:
913 case SecurityAction.RequestMinimum:
914 case SecurityAction.RequestOptional:
915 case SecurityAction.RequestRefuse:
921 Error_AttributeEmitError ("SecurityAction is out of range");
925 Error_AttributeEmitError (String.Concat ("SecurityAction `", action, "' is not valid for this declaration"));
929 System.Security.Permissions.SecurityAction GetSecurityActionValue ()
931 return (SecurityAction)pos_values [0];
935 /// Creates instance of SecurityAttribute class and add result of CreatePermission method to permission table.
937 /// <returns></returns>
938 public void ExtractSecurityPermissionSet (ListDictionary permissions)
940 Type orig_assembly_type = null;
942 if (TypeManager.LookupDeclSpace (Type) != null) {
943 if (!RootContext.StdLib) {
944 orig_assembly_type = Type.GetType (Type.FullName);
946 string orig_version_path = Environment.GetEnvironmentVariable ("__SECURITY_BOOTSTRAP_DB");
947 if (orig_version_path == null) {
948 Error_AttributeEmitError ("security custom attributes can not be referenced from defining assembly");
952 if (orig_sec_assembly == null) {
953 string file = Path.Combine (orig_version_path, Driver.OutputFile);
954 orig_sec_assembly = Assembly.LoadFile (file);
957 orig_assembly_type = orig_sec_assembly.GetType (Type.FullName, true);
958 if (orig_assembly_type == null) {
959 Report.Warning (-112, 1, Location, "Self-referenced security attribute `{0}' " +
960 "was not found in previous version of assembly");
966 SecurityAttribute sa;
967 // For all non-selfreferencing security attributes we can avoid all hacks
968 if (orig_assembly_type == null) {
969 sa = (SecurityAttribute) Activator.CreateInstance (Type, pos_values);
971 if (prop_info_arr != null) {
972 for (int i = 0; i < prop_info_arr.Length; ++i) {
973 PropertyInfo pi = prop_info_arr [i];
974 pi.SetValue (sa, prop_values_arr [i], null);
978 // HACK: All security attributes have same ctor syntax
979 sa = (SecurityAttribute) Activator.CreateInstance (orig_assembly_type, new object[] { GetSecurityActionValue () } );
981 // All types are from newly created assembly but for invocation with old one we need to convert them
982 if (prop_info_arr != null) {
983 for (int i = 0; i < prop_info_arr.Length; ++i) {
984 PropertyInfo emited_pi = prop_info_arr [i];
985 PropertyInfo pi = orig_assembly_type.GetProperty (emited_pi.Name, emited_pi.PropertyType);
987 object old_instance = pi.PropertyType.IsEnum ?
988 System.Enum.ToObject (pi.PropertyType, prop_values_arr [i]) :
991 pi.SetValue (sa, old_instance, null);
997 perm = sa.CreatePermission ();
998 SecurityAction action = GetSecurityActionValue ();
1000 // IS is correct because for corlib we are using an instance from old corlib
1001 if (!(perm is System.Security.CodeAccessPermission)) {
1003 case SecurityAction.Demand:
1004 action = (SecurityAction)13;
1006 case SecurityAction.LinkDemand:
1007 action = (SecurityAction)14;
1009 case SecurityAction.InheritanceDemand:
1010 action = (SecurityAction)15;
1015 PermissionSet ps = (PermissionSet)permissions [action];
1017 if (sa is PermissionSetAttribute)
1018 ps = new PermissionSet (sa.Unrestricted ? PermissionState.Unrestricted : PermissionState.None);
1020 ps = new PermissionSet (PermissionState.None);
1022 permissions.Add (action, ps);
1023 } else if (!ps.IsUnrestricted () && (sa is PermissionSetAttribute) && sa.Unrestricted) {
1024 ps = ps.Union (new PermissionSet (PermissionState.Unrestricted));
1025 permissions [action] = ps;
1027 ps.AddPermission (perm);
1030 static object GetValue (object value)
1032 if (value is EnumConstant)
1033 return ((EnumConstant) value).GetValue ();
1038 public object GetPropertyValue (string name)
1040 if (prop_info_arr == null)
1043 for (int i = 0; i < prop_info_arr.Length; ++i) {
1044 if (prop_info_arr [i].Name == name)
1045 return prop_values_arr [i];
1051 object GetFieldValue (string name)
1054 if (field_info_arr == null)
1057 foreach (FieldInfo fi in field_info_arr) {
1058 if (fi.Name == name)
1059 return GetValue (field_values_arr [i]);
1066 // Theoretically, we can get rid of this, since FieldBuilder.SetCustomAttribute()
1067 // and ParameterBuilder.SetCustomAttribute() are supposed to handle this attribute.
1068 // However, we can't, since it appears that the .NET 1.1 SRE hangs when given a MarshalAsAttribute.
1070 public UnmanagedMarshal GetMarshal (Attributable attr)
1072 UnmanagedType UnmanagedType;
1073 if (!RootContext.StdLib || pos_values [0].GetType () != typeof (UnmanagedType))
1074 UnmanagedType = (UnmanagedType) System.Enum.ToObject (typeof (UnmanagedType), pos_values [0]);
1076 UnmanagedType = (UnmanagedType) pos_values [0];
1078 object value = GetFieldValue ("SizeParamIndex");
1079 if (value != null && UnmanagedType != UnmanagedType.LPArray) {
1080 Error_AttributeEmitError ("SizeParamIndex field is not valid for the specified unmanaged type");
1084 object o = GetFieldValue ("ArraySubType");
1085 UnmanagedType array_sub_type = o == null ? (UnmanagedType) 0x50 /* NATIVE_MAX */ : (UnmanagedType) o;
1087 switch (UnmanagedType) {
1088 case UnmanagedType.CustomMarshaler: {
1089 MethodInfo define_custom = typeof (UnmanagedMarshal).GetMethod ("DefineCustom",
1090 BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
1091 if (define_custom == null) {
1092 Report.RuntimeMissingSupport (Location, "set marshal info");
1096 object [] args = new object [4];
1097 args [0] = GetFieldValue ("MarshalTypeRef");
1098 args [1] = GetFieldValue ("MarshalCookie");
1099 args [2] = GetFieldValue ("MarshalType");
1100 args [3] = Guid.Empty;
1101 return (UnmanagedMarshal) define_custom.Invoke (null, args);
1103 case UnmanagedType.LPArray: {
1104 object size_const = GetFieldValue ("SizeConst");
1105 object size_param_index = GetFieldValue ("SizeParamIndex");
1107 if ((size_const != null) || (size_param_index != null)) {
1108 MethodInfo define_array = typeof (UnmanagedMarshal).GetMethod ("DefineLPArrayInternal",
1109 BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
1110 if (define_array == null) {
1111 Report.RuntimeMissingSupport (Location, "set marshal info");
1115 object [] args = new object [3];
1116 args [0] = array_sub_type;
1117 args [1] = size_const == null ? -1 : size_const;
1118 args [2] = size_param_index == null ? -1 : size_param_index;
1119 return (UnmanagedMarshal) define_array.Invoke (null, args);
1122 return UnmanagedMarshal.DefineLPArray (array_sub_type);
1124 case UnmanagedType.SafeArray:
1125 return UnmanagedMarshal.DefineSafeArray (array_sub_type);
1127 case UnmanagedType.ByValArray:
1128 FieldBase fm = attr as FieldBase;
1130 Error_AttributeEmitError ("Specified unmanaged type is only valid on fields");
1133 return UnmanagedMarshal.DefineByValArray ((int) GetFieldValue ("SizeConst"));
1135 case UnmanagedType.ByValTStr:
1136 return UnmanagedMarshal.DefineByValTStr ((int) GetFieldValue ("SizeConst"));
1139 return UnmanagedMarshal.DefineUnmanagedMarshal (UnmanagedType);
1143 public CharSet GetCharSetValue ()
1145 return (CharSet)System.Enum.Parse (typeof (CharSet), pos_values [0].ToString ());
1148 public bool IsInternalMethodImplAttribute {
1150 if (Type != TypeManager.methodimpl_attr_type)
1153 MethodImplOptions options;
1154 if (pos_values[0].GetType () != typeof (MethodImplOptions))
1155 options = (MethodImplOptions)System.Enum.ToObject (typeof (MethodImplOptions), pos_values[0]);
1157 options = (MethodImplOptions)pos_values[0];
1159 return (options & MethodImplOptions.InternalCall) != 0;
1163 public LayoutKind GetLayoutKindValue ()
1165 if (!RootContext.StdLib || pos_values [0].GetType () != typeof (LayoutKind))
1166 return (LayoutKind)System.Enum.ToObject (typeof (LayoutKind), pos_values [0]);
1168 return (LayoutKind)pos_values [0];
1171 public object GetParameterDefaultValue ()
1173 return pos_values [0];
1176 public override bool Equals (object obj)
1178 Attribute a = obj as Attribute;
1182 return Type == a.Type && Target == a.Target;
1185 public override int GetHashCode ()
1187 return base.GetHashCode ();
1191 /// Emit attribute for Attributable symbol
1193 public void Emit (ListDictionary allEmitted)
1195 CustomAttributeBuilder cb = Resolve ();
1199 AttributeUsageAttribute usage_attr = GetAttributeUsage (Type);
1200 if ((usage_attr.ValidOn & Target) == 0) {
1201 Report.Error (592, Location, "The attribute `{0}' is not valid on this declaration type. " +
1202 "It is valid on `{1}' declarations only",
1203 GetSignatureForError (), GetValidTargets ());
1208 foreach (Attributable owner in owners)
1209 owner.ApplyAttributeBuilder (this, cb);
1211 catch (Exception e) {
1212 Error_AttributeEmitError (e.Message);
1216 if (!usage_attr.AllowMultiple && allEmitted != null) {
1217 if (allEmitted.Contains (this)) {
1218 ArrayList a = allEmitted [this] as ArrayList;
1220 a = new ArrayList (2);
1221 allEmitted [this] = a;
1225 allEmitted.Add (this, null);
1229 if (!RootContext.VerifyClsCompliance)
1232 // Here we are testing attribute arguments for array usage (error 3016)
1233 if (Owner.IsClsComplianceRequired ()) {
1234 if (PosArguments != null) {
1235 foreach (Argument arg in PosArguments) {
1236 // Type is undefined (was error 246)
1237 if (arg.Type == null)
1240 if (arg.Type.IsArray) {
1241 Report.Error (3016, Location, "Arrays as attribute arguments are not CLS-compliant");
1247 if (NamedArguments == null)
1250 foreach (DictionaryEntry de in NamedArguments) {
1251 Argument arg = (Argument) de.Value;
1253 // Type is undefined (was error 246)
1254 if (arg.Type == null)
1257 if (arg.Type.IsArray) {
1258 Report.Error (3016, Location, "Arrays as attribute arguments are not CLS-compliant");
1265 private Expression GetValue ()
1267 if (PosArguments == null || PosArguments.Count < 1)
1270 return ((Argument) PosArguments [0]).Expr;
1273 public string GetString ()
1275 Expression e = GetValue ();
1276 if (e is StringConstant)
1277 return ((StringConstant)e).Value;
1281 public bool GetBoolean ()
1283 Expression e = GetValue ();
1284 if (e is BoolConstant)
1285 return ((BoolConstant)e).Value;
1289 public Type GetArgumentType ()
1291 TypeOf e = GetValue () as TypeOf;
1294 return e.TypeArgument;
1297 public override Expression DoResolve (EmitContext ec)
1299 throw new NotImplementedException ();
1302 public override void Emit (EmitContext ec)
1304 throw new NotImplementedException ();
1310 /// For global attributes (assembly, module) we need special handling.
1311 /// Attributes can be located in the several files
1313 public class GlobalAttribute : Attribute
1315 public readonly NamespaceEntry ns;
1317 public GlobalAttribute (NamespaceEntry ns, string target,
1318 Expression left_expr, string identifier, object[] args, Location loc, bool nameEscaped):
1319 base (target, left_expr, identifier, args, loc, nameEscaped)
1322 this.owners = new Attributable[1];
1325 public override void AttachTo (Attributable owner)
1327 if (ExplicitTarget == "assembly") {
1328 owners [0] = CodeGen.Assembly;
1331 if (ExplicitTarget == "module") {
1332 owners [0] = CodeGen.Module;
1335 throw new NotImplementedException ("Unknown global explicit target " + ExplicitTarget);
1340 // RootContext.ToplevelTypes has a single NamespaceEntry which gets overwritten
1341 // each time a new file is parsed. However, we need to use the NamespaceEntry
1342 // in effect where the attribute was used. Since code elsewhere cannot assume
1343 // that the NamespaceEntry is right, just overwrite it.
1345 // Precondition: RootContext.ToplevelTypes == null
1347 if (RootContext.ToplevelTypes.NamespaceEntry != null)
1348 throw new InternalErrorException (Location + " non-null NamespaceEntry");
1350 RootContext.ToplevelTypes.NamespaceEntry = ns;
1355 RootContext.ToplevelTypes.NamespaceEntry = null;
1358 protected override TypeExpr ResolveAsTypeTerminal (Expression expr, IResolveContext ec, bool silent)
1362 return base.ResolveAsTypeTerminal (expr, ec, silent);
1369 protected override ConstructorInfo ResolveConstructor (EmitContext ec)
1373 return base.ResolveConstructor (ec);
1380 protected override bool ResolveNamedArguments (EmitContext ec)
1384 return base.ResolveNamedArguments (ec);
1392 public class Attributes {
1393 public readonly ArrayList Attrs;
1395 public Attributes (Attribute a)
1397 Attrs = new ArrayList ();
1401 public Attributes (ArrayList attrs)
1406 public void AddAttributes (ArrayList attrs)
1408 Attrs.AddRange (attrs);
1411 public void AttachTo (Attributable attributable)
1413 foreach (Attribute a in Attrs)
1414 a.AttachTo (attributable);
1418 /// Checks whether attribute target is valid for the current element
1420 public bool CheckTargets ()
1422 foreach (Attribute a in Attrs) {
1423 if (!a.CheckTarget ())
1429 public Attribute Search (Type t)
1431 foreach (Attribute a in Attrs) {
1432 if (a.ResolveType () == t)
1439 /// Returns all attributes of type 't'. Use it when attribute is AllowMultiple = true
1441 public Attribute[] SearchMulti (Type t)
1443 ArrayList ar = null;
1445 foreach (Attribute a in Attrs) {
1446 if (a.ResolveType () == t) {
1448 ar = new ArrayList ();
1453 return ar == null ? null : ar.ToArray (typeof (Attribute)) as Attribute[];
1460 ListDictionary ld = Attrs.Count > 1 ? new ListDictionary () : null;
1462 foreach (Attribute a in Attrs)
1465 if (ld == null || ld.Count == 0)
1468 foreach (DictionaryEntry d in ld) {
1469 if (d.Value == null)
1472 foreach (Attribute collision in (ArrayList)d.Value)
1473 Report.SymbolRelatedToPreviousError (collision.Location, "");
1475 Attribute a = (Attribute)d.Key;
1476 Report.Error (579, a.Location, "The attribute `{0}' cannot be applied multiple times",
1477 a.GetSignatureForError ());
1481 public bool Contains (Type t)
1483 return Search (t) != null;
1488 /// Helper class for attribute verification routine.
1490 sealed class AttributeTester
1492 static PtrHashtable analyzed_types;
1493 static PtrHashtable analyzed_types_obsolete;
1494 static PtrHashtable analyzed_member_obsolete;
1495 static PtrHashtable analyzed_method_excluded;
1498 static PtrHashtable fixed_buffer_cache;
1501 static object TRUE = new object ();
1502 static object FALSE = new object ();
1504 static AttributeTester ()
1509 private AttributeTester ()
1513 public static void Reset ()
1515 analyzed_types = new PtrHashtable ();
1516 analyzed_types_obsolete = new PtrHashtable ();
1517 analyzed_member_obsolete = new PtrHashtable ();
1518 analyzed_method_excluded = new PtrHashtable ();
1520 fixed_buffer_cache = new PtrHashtable ();
1524 public enum Result {
1531 /// Returns true if parameters of two compared methods are CLS-Compliant.
1532 /// It tests differing only in ref or out, or in array rank.
1534 public static Result AreOverloadedMethodParamsClsCompliant (Type[] types_a, Type[] types_b)
1536 if (types_a == null || types_b == null)
1539 if (types_a.Length != types_b.Length)
1542 Result result = Result.Ok;
1543 for (int i = 0; i < types_b.Length; ++i) {
1544 Type aType = types_a [i];
1545 Type bType = types_b [i];
1547 if (aType.IsArray && bType.IsArray) {
1548 Type a_el_type = aType.GetElementType ();
1549 Type b_el_type = bType.GetElementType ();
1550 if (aType.GetArrayRank () != bType.GetArrayRank () && a_el_type == b_el_type) {
1551 result = Result.RefOutArrayError;
1555 if (a_el_type.IsArray || b_el_type.IsArray) {
1556 result = Result.ArrayArrayError;
1561 Type aBaseType = aType;
1562 bool is_either_ref_or_out = false;
1564 if (aType.IsByRef || aType.IsPointer) {
1565 aBaseType = aType.GetElementType ();
1566 is_either_ref_or_out = true;
1569 Type bBaseType = bType;
1570 if (bType.IsByRef || bType.IsPointer)
1572 bBaseType = bType.GetElementType ();
1573 is_either_ref_or_out = !is_either_ref_or_out;
1576 if (aBaseType != bBaseType)
1579 if (is_either_ref_or_out)
1580 result = Result.RefOutArrayError;
1586 /// This method tests the CLS compliance of external types. It doesn't test type visibility.
1588 public static bool IsClsCompliant (Type type)
1593 object type_compliance = analyzed_types[type];
1594 if (type_compliance != null)
1595 return type_compliance == TRUE;
1597 if (type.IsPointer) {
1598 analyzed_types.Add (type, null);
1603 if (type.IsArray || type.IsByRef) {
1604 result = IsClsCompliant (TypeManager.GetElementType (type));
1605 } else if (TypeManager.IsNullableType (type)) {
1606 result = IsClsCompliant (TypeManager.GetTypeArguments (type) [0]);
1608 result = AnalyzeTypeCompliance (type);
1610 analyzed_types.Add (type, result ? TRUE : FALSE);
1615 /// Returns IFixedBuffer implementation if field is fixed buffer else null.
1617 public static IFixedBuffer GetFixedBuffer (FieldInfo fi)
1619 // Fixed buffer helper type is generated as value type
1620 if (!fi.FieldType.IsValueType)
1623 FieldBase fb = TypeManager.GetField (fi);
1625 return fb as IFixedBuffer;
1628 if (TypeManager.GetConstant (fi) != null)
1632 object o = fixed_buffer_cache [fi];
1634 if (!fi.IsDefined (TypeManager.fixed_buffer_attr_type, false)) {
1635 fixed_buffer_cache.Add (fi, FALSE);
1639 IFixedBuffer iff = new FixedFieldExternal (fi);
1640 fixed_buffer_cache.Add (fi, iff);
1647 return (IFixedBuffer)o;
1653 public static void VerifyModulesClsCompliance ()
1655 Module[] modules = RootNamespace.Global.Modules;
1656 if (modules == null)
1659 // The first module is generated assembly
1660 for (int i = 1; i < modules.Length; ++i) {
1661 Module module = modules [i];
1662 if (!IsClsCompliant (module)) {
1663 Report.Error (3013, "Added modules must be marked with the CLSCompliant attribute " +
1664 "to match the assembly", module.Name);
1670 public static Type GetImportedIgnoreCaseClsType (string name)
1672 foreach (Assembly a in RootNamespace.Global.Assemblies) {
1673 Type t = a.GetType (name, false, true);
1677 if (IsClsCompliant (t))
1683 static bool IsClsCompliant (ICustomAttributeProvider attribute_provider)
1685 object[] CompliantAttribute = attribute_provider.GetCustomAttributes (TypeManager.cls_compliant_attribute_type, false);
1686 if (CompliantAttribute.Length == 0)
1689 return ((CLSCompliantAttribute)CompliantAttribute[0]).IsCompliant;
1692 static bool AnalyzeTypeCompliance (Type type)
1694 type = TypeManager.DropGenericTypeArguments (type);
1695 DeclSpace ds = TypeManager.LookupDeclSpace (type);
1697 return ds.IsClsComplianceRequired ();
1700 if (TypeManager.IsGenericParameter (type))
1703 object[] CompliantAttribute = type.GetCustomAttributes (TypeManager.cls_compliant_attribute_type, false);
1704 if (CompliantAttribute.Length == 0)
1705 return IsClsCompliant (type.Assembly);
1707 return ((CLSCompliantAttribute)CompliantAttribute[0]).IsCompliant;
1710 // Registers the core type as we assume that they will never be obsolete which
1711 // makes things easier for bootstrap and faster (we don't need to query Obsolete attribute).
1712 public static void RegisterNonObsoleteType (Type type)
1714 analyzed_types_obsolete [type] = FALSE;
1718 /// Returns instance of ObsoleteAttribute when type is obsolete
1720 public static ObsoleteAttribute GetObsoleteAttribute (Type type)
1722 object type_obsolete = analyzed_types_obsolete [type];
1723 if (type_obsolete == FALSE)
1726 if (type_obsolete != null)
1727 return (ObsoleteAttribute)type_obsolete;
1729 ObsoleteAttribute result = null;
1730 if (TypeManager.HasElementType (type)) {
1731 result = GetObsoleteAttribute (TypeManager.GetElementType (type));
1732 } else if (TypeManager.IsGenericParameter (type) || TypeManager.IsGenericType (type))
1735 DeclSpace type_ds = TypeManager.LookupDeclSpace (type);
1737 // Type is external, we can get attribute directly
1738 if (type_ds == null) {
1739 object[] attribute = type.GetCustomAttributes (TypeManager.obsolete_attribute_type, false);
1740 if (attribute.Length == 1)
1741 result = (ObsoleteAttribute)attribute [0];
1743 result = type_ds.GetObsoleteAttribute ();
1747 // Cannot use .Add because of corlib bootstrap
1748 analyzed_types_obsolete [type] = result == null ? FALSE : result;
1753 /// Returns instance of ObsoleteAttribute when method is obsolete
1755 public static ObsoleteAttribute GetMethodObsoleteAttribute (MethodBase mb)
1757 IMethodData mc = TypeManager.GetMethod (mb);
1759 return mc.GetObsoleteAttribute ();
1761 // compiler generated methods are not registered by AddMethod
1762 if (mb.DeclaringType is TypeBuilder)
1765 MemberInfo mi = TypeManager.GetPropertyFromAccessor (mb);
1767 return GetMemberObsoleteAttribute (mi);
1769 mi = TypeManager.GetEventFromAccessor (mb);
1771 return GetMemberObsoleteAttribute (mi);
1773 return GetMemberObsoleteAttribute (mb);
1777 /// Returns instance of ObsoleteAttribute when member is obsolete
1779 public static ObsoleteAttribute GetMemberObsoleteAttribute (MemberInfo mi)
1781 object type_obsolete = analyzed_member_obsolete [mi];
1782 if (type_obsolete == FALSE)
1785 if (type_obsolete != null)
1786 return (ObsoleteAttribute)type_obsolete;
1788 if ((mi.DeclaringType is TypeBuilder) || TypeManager.IsGenericType (mi.DeclaringType))
1791 ObsoleteAttribute oa = System.Attribute.GetCustomAttribute (mi, TypeManager.obsolete_attribute_type, false)
1792 as ObsoleteAttribute;
1793 analyzed_member_obsolete.Add (mi, oa == null ? FALSE : oa);
1798 /// Common method for Obsolete error/warning reporting.
1800 public static void Report_ObsoleteMessage (ObsoleteAttribute oa, string member, Location loc)
1803 Report.Error (619, loc, "`{0}' is obsolete: `{1}'", member, oa.Message);
1807 if (oa.Message == null || oa.Message.Length == 0) {
1808 Report.Warning (612, 1, loc, "`{0}' is obsolete", member);
1811 Report.Warning (618, 2, loc, "`{0}' is obsolete: `{1}'", member, oa.Message);
1814 public static bool IsConditionalMethodExcluded (MethodBase mb)
1816 object excluded = analyzed_method_excluded [mb];
1817 if (excluded != null)
1818 return excluded == TRUE ? true : false;
1820 ConditionalAttribute[] attrs = mb.GetCustomAttributes (TypeManager.conditional_attribute_type, true)
1821 as ConditionalAttribute[];
1822 if (attrs.Length == 0) {
1823 analyzed_method_excluded.Add (mb, FALSE);
1827 foreach (ConditionalAttribute a in attrs) {
1828 if (RootContext.AllDefines.Contains (a.ConditionString)) {
1829 analyzed_method_excluded.Add (mb, FALSE);
1833 analyzed_method_excluded.Add (mb, TRUE);
1838 /// Analyzes class whether it has attribute which has ConditionalAttribute
1839 /// and its condition is not defined.
1841 public static bool IsAttributeExcluded (Type type)
1846 Class class_decl = TypeManager.LookupDeclSpace (type) as Class;
1848 // TODO: add caching
1849 // TODO: merge all Type bases attribute caching to one cache to save memory
1850 if (class_decl == null) {
1851 object[] attributes = type.GetCustomAttributes (TypeManager.conditional_attribute_type, false);
1852 foreach (ConditionalAttribute ca in attributes) {
1853 if (RootContext.AllDefines.Contains (ca.ConditionString))
1856 return attributes.Length > 0;
1859 return class_decl.IsExcluded ();
1862 public static Type GetCoClassAttribute (Type type)
1864 TypeContainer tc = TypeManager.LookupInterface (type);
1866 object[] o = type.GetCustomAttributes (TypeManager.coclass_attr_type, false);
1869 return ((System.Runtime.InteropServices.CoClassAttribute)o[0]).CoClass;
1872 if (tc.OptAttributes == null)
1875 Attribute a = tc.OptAttributes.Search (TypeManager.coclass_attr_type);
1879 return a.GetCoClassAttributeValue ();