2 // attribute.cs: Attribute Handler
4 // Author: Ravi Pratap (ravi@ximian.com)
5 // Marek Safar (marek.safar@seznam.cz)
7 // Licensed under the terms of the GNU GPL
9 // (C) 2001 Ximian, Inc (http://www.ximian.com)
14 using System.Diagnostics;
15 using System.Collections;
16 using System.Collections.Specialized;
17 using System.Reflection;
18 using System.Reflection.Emit;
19 using System.Runtime.InteropServices;
20 using System.Runtime.CompilerServices;
21 using System.Security;
22 using System.Security.Permissions;
26 namespace Mono.CSharp {
29 /// Base class for objects that can have Attributes applied to them.
31 public abstract class Attributable {
33 /// Attributes for this type
35 Attributes attributes;
37 public Attributable (Attributes attrs)
42 public Attributes OptAttributes
53 /// Use member-specific procedure to apply attribute @a in @cb to the entity being built in @builder
55 public abstract void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb);
58 /// Returns one AttributeTarget for this element.
60 public abstract AttributeTargets AttributeTargets { get; }
62 public abstract bool IsClsComplianceRequired (DeclSpace ds);
65 /// Gets list of valid attribute targets for explicit target declaration.
66 /// The first array item is default target. Don't break this rule.
68 public abstract string[] ValidAttributeTargets { get; }
71 public class Attribute {
72 public readonly string ExplicitTarget;
73 public AttributeTargets Target;
75 // TODO: remove this member
76 public readonly string Name;
77 public readonly Expression LeftExpr;
78 public readonly string Identifier;
80 public readonly ArrayList Arguments;
82 public readonly Location Location;
88 readonly bool nameEscaped;
90 static AttributeUsageAttribute DefaultUsageAttribute = new AttributeUsageAttribute (AttributeTargets.All);
91 static Assembly orig_sec_assembly;
93 // non-null if named args present after Resolve () is called
94 PropertyInfo [] prop_info_arr;
95 FieldInfo [] field_info_arr;
96 object [] field_values_arr;
97 object [] prop_values_arr;
100 static PtrHashtable usage_attr_cache = new PtrHashtable ();
102 public Attribute (string target, Expression left_expr, string identifier, ArrayList args, Location loc, bool nameEscaped)
104 LeftExpr = left_expr;
105 Identifier = identifier;
106 Name = LeftExpr == null ? identifier : LeftExpr + "." + identifier;
109 ExplicitTarget = target;
110 this.nameEscaped = nameEscaped;
113 void Error_InvalidNamedArgument (string name)
115 Report.Error (617, Location, "`{0}' is not a valid named attribute argument. Named attribute arguments " +
116 "must be fields which are not readonly, static, const or read-write properties which are " +
117 "public and not static",
121 void Error_InvalidNamedAgrumentType (string name)
123 Report.Error (655, Location, "`{0}' is not a valid named attribute argument because it is not a valid " +
124 "attribute parameter type", name);
127 static void Error_AttributeArgumentNotValid (string extra, Location loc)
129 Report.Error (182, loc,
130 "An attribute argument must be a constant expression, typeof " +
131 "expression or array creation expression" + extra);
134 static void Error_AttributeArgumentNotValid (Location loc)
136 Error_AttributeArgumentNotValid ("", loc);
141 /// This is rather hack. We report many emit attribute error with same error to be compatible with
142 /// csc. But because csc has to report them this way because error came from ilasm we needn't.
144 public void Error_AttributeEmitError (string inner)
146 Report.Error (647, Location, "Error during emitting `{0}' attribute. The reason is `{1}'",
147 TypeManager.CSharpName (Type), inner);
150 public void Error_InvalidSecurityParent ()
152 Error_AttributeEmitError ("it is attached to invalid parent");
155 protected virtual FullNamedExpression ResolveAsTypeTerminal (Expression expr, EmitContext ec, bool silent)
157 return expr.ResolveAsTypeTerminal (ec, silent);
160 protected virtual FullNamedExpression ResolveAsTypeStep (Expression expr, EmitContext ec, bool silent)
162 return expr.ResolveAsTypeStep (ec, silent);
165 Type ResolvePossibleAttributeType (EmitContext ec, string name, bool silent, ref bool is_attr)
167 FullNamedExpression fn;
168 if (LeftExpr == null) {
169 fn = ResolveAsTypeTerminal (new SimpleName (name, Location), ec, silent);
171 fn = ResolveAsTypeStep (LeftExpr, ec, silent);
174 fn = new MemberAccess (fn, name, Location).ResolveAsTypeTerminal (ec, silent);
177 TypeExpr te = fn as TypeExpr;
182 if (t.IsSubclassOf (TypeManager.attribute_type)) {
184 } else if (!silent) {
185 Report.SymbolRelatedToPreviousError (t);
186 Report.Error (616, Location, "`{0}': is not an attribute class", TypeManager.CSharpName (t));
192 /// Tries to resolve the type of the attribute. Flags an error if it can't, and complain is true.
194 void ResolveAttributeType (EmitContext ec)
196 bool t1_is_attr = false;
197 Type t1 = ResolvePossibleAttributeType (ec, Identifier, true, ref t1_is_attr);
199 bool t2_is_attr = false;
200 Type t2 = nameEscaped ? null :
201 ResolvePossibleAttributeType (ec, Identifier + "Attribute", true, ref t2_is_attr);
203 if (t1_is_attr && t2_is_attr) {
204 Report.Error (1614, Location, "`{0}' is ambiguous between `{0}' and `{0}Attribute'. " +
205 "Use either `@{0}' or `{0}Attribute'", GetSignatureForError ());
206 resolve_error = true;
220 if (t1 == null && t2 == null)
221 ResolvePossibleAttributeType (ec, Identifier, false, ref t1_is_attr);
223 ResolvePossibleAttributeType (ec, Identifier, false, ref t1_is_attr);
225 ResolvePossibleAttributeType (ec, Identifier + "Attribute", false, ref t2_is_attr);
227 resolve_error = true;
230 public virtual Type ResolveType (EmitContext ec)
232 if (Type == null && !resolve_error)
233 ResolveAttributeType (ec);
237 public string GetSignatureForError ()
239 return LeftExpr == null ? Identifier : LeftExpr.GetSignatureForError () + "." + Identifier;
243 // Given an expression, if the expression is a valid attribute-argument-expression
244 // returns an object that can be used to encode it, or null on failure.
246 public static bool GetAttributeArgumentExpression (Expression e, Location loc, Type arg_type, out object result)
248 Constant constant = e as Constant;
249 if (constant != null) {
250 constant = constant.ToType (arg_type, loc);
251 if (constant == null) {
255 result = constant.GetTypedValue ();
257 } else if (e is TypeOf) {
258 result = ((TypeOf) e).TypeArg;
260 } else if (e is ArrayCreation){
261 result = ((ArrayCreation) e).EncodeAsAttribute ();
264 } else if (e is EmptyCast) {
265 Expression child = ((EmptyCast)e).Child;
266 return GetAttributeArgumentExpression (child, loc, child.Type, out result);
267 } else if (e is As) {
269 return GetAttributeArgumentExpression (as_e.Expr, loc, as_e.ProbeType.Type, out result);
273 Error_AttributeArgumentNotValid (loc);
277 bool IsValidArgumentType (Type t)
280 t = t.GetElementType ();
282 return TypeManager.IsPrimitiveType (t) ||
283 TypeManager.IsEnumType (t) ||
284 t == TypeManager.string_type ||
285 t == TypeManager.object_type ||
286 t == TypeManager.type_type;
289 // Cache for parameter-less attributes
290 static PtrHashtable att_cache = new PtrHashtable ();
292 public CustomAttributeBuilder Resolve (EmitContext ec)
297 resolve_error = true;
300 ResolveAttributeType (ec);
305 if (Type.IsAbstract) {
306 Report.Error (653, Location, "Cannot apply attribute class `{0}' because it is abstract", GetSignatureForError ());
310 ObsoleteAttribute obsolete_attr = AttributeTester.GetObsoleteAttribute (Type);
311 if (obsolete_attr != null) {
312 AttributeTester.Report_ObsoleteMessage (obsolete_attr, TypeManager.CSharpName (Type), Location);
315 if (Arguments == null) {
316 object o = att_cache [Type];
318 resolve_error = false;
319 return (CustomAttributeBuilder)o;
323 ConstructorInfo ctor = ResolveArguments (ec);
327 CustomAttributeBuilder cb;
330 if (prop_info_arr != null || field_info_arr != null) {
331 cb = new CustomAttributeBuilder (
333 prop_info_arr, prop_values_arr,
334 field_info_arr, field_values_arr);
336 cb = new CustomAttributeBuilder (
339 if (pos_values.Length == 0)
340 att_cache.Add (Type, cb);
344 Error_AttributeArgumentNotValid (Location);
348 resolve_error = false;
352 protected virtual ConstructorInfo ResolveArguments (EmitContext ec)
354 // Now we extract the positional and named arguments
356 ArrayList pos_args = null;
357 ArrayList named_args = null;
358 int pos_arg_count = 0;
359 int named_arg_count = 0;
361 if (Arguments != null) {
362 pos_args = (ArrayList) Arguments [0];
363 if (pos_args != null)
364 pos_arg_count = pos_args.Count;
365 if (Arguments.Count > 1) {
366 named_args = (ArrayList) Arguments [1];
367 named_arg_count = named_args.Count;
371 pos_values = new object [pos_arg_count];
374 // First process positional arguments
378 for (i = 0; i < pos_arg_count; i++) {
379 Argument a = (Argument) pos_args [i];
382 if (!a.Resolve (ec, Location))
388 if (!GetAttributeArgumentExpression (e, Location, a.Type, out val))
391 pos_values [i] = val;
393 if (i == 0 && Type == TypeManager.attribute_usage_type && (int)val == 0) {
394 Report.Error (591, Location, "Invalid value for argument to 'System.AttributeUsage' attribute");
400 // Now process named arguments
403 ArrayList field_infos = null;
404 ArrayList prop_infos = null;
405 ArrayList field_values = null;
406 ArrayList prop_values = null;
407 Hashtable seen_names = null;
409 if (named_arg_count > 0) {
410 field_infos = new ArrayList ();
411 prop_infos = new ArrayList ();
412 field_values = new ArrayList ();
413 prop_values = new ArrayList ();
415 seen_names = new Hashtable();
418 for (i = 0; i < named_arg_count; i++) {
419 DictionaryEntry de = (DictionaryEntry) named_args [i];
420 string member_name = (string) de.Key;
421 Argument a = (Argument) de.Value;
424 if (seen_names.Contains(member_name)) {
425 Report.Error(643, Location, "'" + member_name + "' duplicate named attribute argument");
428 seen_names.Add(member_name, 1);
430 if (!a.Resolve (ec, Location))
433 Expression member = Expression.MemberLookup (
434 ec, Type, member_name,
435 MemberTypes.Field | MemberTypes.Property,
436 BindingFlags.Public | BindingFlags.Instance,
439 if (member == null) {
440 member = Expression.MemberLookup (ec, Type, member_name,
441 MemberTypes.Field | MemberTypes.Property, BindingFlags.NonPublic | BindingFlags.Instance,
444 if (member != null) {
445 Expression.ErrorIsInaccesible (Location, member.GetSignatureForError ());
451 Report.Error (117, Location, "`{0}' does not contain a definition for `{1}'",
452 TypeManager.CSharpName (Type), member_name);
456 if (!(member is PropertyExpr || member is FieldExpr)) {
457 Error_InvalidNamedArgument (member_name);
462 if (member is PropertyExpr) {
463 PropertyExpr pe = (PropertyExpr) member;
464 PropertyInfo pi = pe.PropertyInfo;
466 if (!pi.CanWrite || !pi.CanRead) {
467 Report.SymbolRelatedToPreviousError (pi);
468 Error_InvalidNamedArgument (member_name);
472 if (!IsValidArgumentType (pi.PropertyType)) {
473 Report.SymbolRelatedToPreviousError (pi);
474 Error_InvalidNamedAgrumentType (member_name);
479 if (!GetAttributeArgumentExpression (e, Location, pi.PropertyType, out value))
482 prop_values.Add (value);
485 } else if (member is FieldExpr) {
486 FieldExpr fe = (FieldExpr) member;
487 FieldInfo fi = fe.FieldInfo;
490 Error_InvalidNamedArgument (member_name);
494 if (!IsValidArgumentType (fi.FieldType)) {
495 Report.SymbolRelatedToPreviousError (fi);
496 Error_InvalidNamedAgrumentType (member_name);
501 if (!GetAttributeArgumentExpression (e, Location, fi.FieldType, out value))
504 field_values.Add (value);
505 field_infos.Add (fi);
509 Expression mg = Expression.MemberLookup (
510 ec, Type, ".ctor", MemberTypes.Constructor,
511 BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly,
514 MethodBase constructor = Invocation.OverloadResolve (
515 ec, (MethodGroupExpr) mg, pos_args, false, Location);
517 if (constructor == null) {
522 // Here we do the checks which should be done by corlib or by runtime.
523 // However Zoltan doesn't like it and every Mono compiler has to do it again.
525 if (Type == TypeManager.guid_attr_type) {
527 new Guid ((string)pos_values [0]);
529 catch (Exception e) {
530 Error_AttributeEmitError (e.Message);
535 if (Type == TypeManager.methodimpl_attr_type &&
536 pos_values.Length == 1 && ((Argument)pos_args [0]).Type == TypeManager.short_type &&
537 !System.Enum.IsDefined (typeof (MethodImplOptions), pos_values [0])) {
538 Error_AttributeEmitError ("Incorrect argument value.");
543 // Now we perform some checks on the positional args as they
544 // cannot be null for a constructor which expects a parameter
548 ParameterData pd = TypeManager.GetParameterData (constructor);
550 int last_real_param = pd.Count;
552 // When the params is not filled we need to put one
553 if (last_real_param > pos_arg_count) {
554 object [] new_pos_values = new object [pos_arg_count + 1];
555 pos_values.CopyTo (new_pos_values, 0);
556 new_pos_values [pos_arg_count] = new object [] {} ;
557 pos_values = new_pos_values;
562 for (int j = 0; j < pos_arg_count; ++j) {
563 Argument a = (Argument) pos_args [j];
565 if (a.Expr is NullLiteral && pd.ParameterType (j) == TypeManager.object_type) {
566 Error_AttributeArgumentNotValid (Location);
570 object value = pos_values [j];
571 if (value != null && a.Type != value.GetType () && TypeManager.IsPrimitiveType (a.Type)) {
573 pos_values [j] = TypeManager.ChangeType (value, a.Type, out fail);
575 // TODO: Can failed ?
576 throw new NotImplementedException ();
580 if (j < last_real_param)
583 if (j == last_real_param) {
584 object [] array = new object [pos_arg_count - last_real_param];
585 array [0] = pos_values [j];
586 pos_values [j] = array;
590 object [] params_array = (object []) pos_values [last_real_param];
591 params_array [j - last_real_param] = pos_values [j];
594 // Adjust the size of the pos_values if it had params
595 if (last_real_param != pos_arg_count) {
596 object [] new_pos_values = new object [last_real_param + 1];
597 Array.Copy (pos_values, new_pos_values, last_real_param + 1);
598 pos_values = new_pos_values;
601 if (named_arg_count > 0) {
602 prop_info_arr = new PropertyInfo [prop_infos.Count];
603 field_info_arr = new FieldInfo [field_infos.Count];
604 field_values_arr = new object [field_values.Count];
605 prop_values_arr = new object [prop_values.Count];
607 field_infos.CopyTo (field_info_arr, 0);
608 field_values.CopyTo (field_values_arr, 0);
610 prop_values.CopyTo (prop_values_arr, 0);
611 prop_infos.CopyTo (prop_info_arr, 0);
614 return (ConstructorInfo) constructor;
618 /// Get a string containing a list of valid targets for the attribute 'attr'
620 public string GetValidTargets ()
622 StringBuilder sb = new StringBuilder ();
623 AttributeTargets targets = GetAttributeUsage (null).ValidOn;
625 if ((targets & AttributeTargets.Assembly) != 0)
626 sb.Append ("assembly, ");
628 if ((targets & AttributeTargets.Module) != 0)
629 sb.Append ("module, ");
631 if ((targets & AttributeTargets.Class) != 0)
632 sb.Append ("class, ");
634 if ((targets & AttributeTargets.Struct) != 0)
635 sb.Append ("struct, ");
637 if ((targets & AttributeTargets.Enum) != 0)
638 sb.Append ("enum, ");
640 if ((targets & AttributeTargets.Constructor) != 0)
641 sb.Append ("constructor, ");
643 if ((targets & AttributeTargets.Method) != 0)
644 sb.Append ("method, ");
646 if ((targets & AttributeTargets.Property) != 0)
647 sb.Append ("property, indexer, ");
649 if ((targets & AttributeTargets.Field) != 0)
650 sb.Append ("field, ");
652 if ((targets & AttributeTargets.Event) != 0)
653 sb.Append ("event, ");
655 if ((targets & AttributeTargets.Interface) != 0)
656 sb.Append ("interface, ");
658 if ((targets & AttributeTargets.Parameter) != 0)
659 sb.Append ("parameter, ");
661 if ((targets & AttributeTargets.Delegate) != 0)
662 sb.Append ("delegate, ");
664 if ((targets & AttributeTargets.ReturnValue) != 0)
665 sb.Append ("return, ");
668 if ((targets & AttributeTargets.GenericParameter) != 0)
669 sb.Append ("type parameter, ");
671 return sb.Remove (sb.Length - 2, 2).ToString ();
675 /// Returns AttributeUsage attribute for this type
677 AttributeUsageAttribute GetAttributeUsage (EmitContext ec)
679 AttributeUsageAttribute ua = usage_attr_cache [Type] as AttributeUsageAttribute;
683 Class attr_class = TypeManager.LookupClass (Type);
685 if (attr_class == null) {
686 object[] usage_attr = Type.GetCustomAttributes (TypeManager.attribute_usage_type, true);
687 ua = (AttributeUsageAttribute)usage_attr [0];
688 usage_attr_cache.Add (Type, ua);
692 Attribute a = attr_class.OptAttributes == null
694 : attr_class.OptAttributes.Search (TypeManager.attribute_usage_type, attr_class.EmitContext);
697 ? DefaultUsageAttribute
698 : a.GetAttributeUsageAttribute (attr_class.EmitContext);
700 usage_attr_cache.Add (Type, ua);
704 AttributeUsageAttribute GetAttributeUsageAttribute (EmitContext ec)
706 if (pos_values == null)
707 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
708 // But because a lot of attribute class code must be rewritten will be better to wait...
712 return DefaultUsageAttribute;
714 AttributeUsageAttribute usage_attribute = new AttributeUsageAttribute ((AttributeTargets)pos_values [0]);
716 object field = GetPropertyValue ("AllowMultiple");
718 usage_attribute.AllowMultiple = (bool)field;
720 field = GetPropertyValue ("Inherited");
722 usage_attribute.Inherited = (bool)field;
724 return usage_attribute;
728 /// Returns custom name of indexer
730 public string GetIndexerAttributeValue (EmitContext ec)
732 if (pos_values == null)
733 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
734 // But because a lot of attribute class code must be rewritten will be better to wait...
740 return pos_values [0] as string;
744 /// Returns condition of ConditionalAttribute
746 public string GetConditionalAttributeValue (EmitContext ec)
748 if (pos_values == null)
749 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
750 // But because a lot of attribute class code must be rewritten will be better to wait...
756 return (string)pos_values [0];
760 /// Creates the instance of ObsoleteAttribute from this attribute instance
762 public ObsoleteAttribute GetObsoleteAttribute (EmitContext ec)
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 if (pos_values == null || pos_values.Length == 0)
773 return new ObsoleteAttribute ();
775 if (pos_values.Length == 1)
776 return new ObsoleteAttribute ((string)pos_values [0]);
778 return new ObsoleteAttribute ((string)pos_values [0], (bool)pos_values [1]);
782 /// Returns value of CLSCompliantAttribute contructor parameter but because the method can be called
783 /// before ApplyAttribute. We need to resolve the arguments.
784 /// This situation occurs when class deps is differs from Emit order.
786 public bool GetClsCompliantAttributeValue (EmitContext ec)
788 if (pos_values == null)
789 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
790 // But because a lot of attribute class code must be rewritten will be better to wait...
796 return (bool)pos_values [0];
799 public Type GetCoClassAttributeValue (EmitContext ec)
801 if (pos_values == null)
807 return (Type)pos_values [0];
811 /// Tests permitted SecurityAction for assembly or other types
813 public bool CheckSecurityActionValidity (bool for_assembly)
815 SecurityAction action = GetSecurityActionValue ();
817 if ((action == SecurityAction.RequestMinimum || action == SecurityAction.RequestOptional ||
818 action == SecurityAction.RequestRefuse) && for_assembly)
822 if (action < SecurityAction.Demand || action > SecurityAction.InheritanceDemand) {
823 Error_AttributeEmitError ("SecurityAction is out of range");
827 if ((action != SecurityAction.RequestMinimum && action != SecurityAction.RequestOptional &&
828 action != SecurityAction.RequestRefuse) && !for_assembly)
832 Error_AttributeEmitError (String.Concat ("SecurityAction `", action, "' is not valid for this declaration"));
836 System.Security.Permissions.SecurityAction GetSecurityActionValue ()
838 return (SecurityAction)pos_values [0];
842 /// Creates instance of SecurityAttribute class and add result of CreatePermission method to permission table.
844 /// <returns></returns>
845 public void ExtractSecurityPermissionSet (ListDictionary permissions)
847 Type orig_assembly_type = null;
849 if (TypeManager.LookupDeclSpace (Type) != null) {
850 if (!RootContext.StdLib) {
851 orig_assembly_type = Type.GetType (Type.FullName);
853 string orig_version_path = Environment.GetEnvironmentVariable ("__SECURITY_BOOTSTRAP_DB");
854 if (orig_version_path == null) {
855 Error_AttributeEmitError ("security custom attributes can not be referenced from defining assembly");
859 if (orig_sec_assembly == null) {
860 string file = Path.Combine (orig_version_path, Driver.OutputFile);
861 orig_sec_assembly = Assembly.LoadFile (file);
864 orig_assembly_type = orig_sec_assembly.GetType (Type.FullName, true);
865 if (orig_assembly_type == null) {
866 Report.Warning (-112, 1, Location, "Self-referenced security attribute `{0}' " +
867 "was not found in previous version of assembly");
873 SecurityAttribute sa;
874 // For all non-selfreferencing security attributes we can avoid all hacks
875 if (orig_assembly_type == null) {
876 sa = (SecurityAttribute) Activator.CreateInstance (Type, pos_values);
878 if (prop_info_arr != null) {
879 for (int i = 0; i < prop_info_arr.Length; ++i) {
880 PropertyInfo pi = prop_info_arr [i];
881 pi.SetValue (sa, prop_values_arr [i], null);
885 // HACK: All security attributes have same ctor syntax
886 sa = (SecurityAttribute) Activator.CreateInstance (orig_assembly_type, new object[] { GetSecurityActionValue () } );
888 // All types are from newly created assembly but for invocation with old one we need to convert them
889 if (prop_info_arr != null) {
890 for (int i = 0; i < prop_info_arr.Length; ++i) {
891 PropertyInfo emited_pi = prop_info_arr [i];
892 PropertyInfo pi = orig_assembly_type.GetProperty (emited_pi.Name, emited_pi.PropertyType);
894 object old_instance = pi.PropertyType.IsEnum ?
895 System.Enum.ToObject (pi.PropertyType, prop_values_arr [i]) :
898 pi.SetValue (sa, old_instance, null);
904 perm = sa.CreatePermission ();
905 SecurityAction action = GetSecurityActionValue ();
907 // IS is correct because for corlib we are using an instance from old corlib
908 if (!(perm is System.Security.CodeAccessPermission)) {
910 case SecurityAction.Demand:
911 action = (SecurityAction)13;
913 case SecurityAction.LinkDemand:
914 action = (SecurityAction)14;
916 case SecurityAction.InheritanceDemand:
917 action = (SecurityAction)15;
922 PermissionSet ps = (PermissionSet)permissions [action];
924 if (sa is PermissionSetAttribute)
925 ps = new PermissionSet (sa.Unrestricted ? PermissionState.Unrestricted : PermissionState.None);
927 ps = new PermissionSet (PermissionState.None);
929 permissions.Add (action, ps);
930 } else if (!ps.IsUnrestricted () && (sa is PermissionSetAttribute) && sa.Unrestricted) {
931 ps = ps.Union (new PermissionSet (PermissionState.Unrestricted));
932 permissions [action] = ps;
934 ps.AddPermission (perm);
937 object GetValue (object value)
939 if (value is EnumConstant)
940 return ((EnumConstant) value).GetValue ();
945 public object GetPropertyValue (string name)
947 if (prop_info_arr == null)
950 for (int i = 0; i < prop_info_arr.Length; ++i) {
951 if (prop_info_arr [i].Name == name)
952 return prop_values_arr [i];
958 object GetFieldValue (string name)
961 if (field_info_arr == null)
964 foreach (FieldInfo fi in field_info_arr) {
966 return GetValue (field_values_arr [i]);
973 // Theoretically, we can get rid of this, since FieldBuilder.SetCustomAttribute()
974 // and ParameterBuilder.SetCustomAttribute() are supposed to handle this attribute.
975 // However, we can't, since it appears that the .NET 1.1 SRE hangs when given a MarshalAsAttribute.
977 public UnmanagedMarshal GetMarshal (Attributable attr)
979 UnmanagedType UnmanagedType;
980 if (!RootContext.StdLib || pos_values [0].GetType () != typeof (UnmanagedType))
981 UnmanagedType = (UnmanagedType) System.Enum.ToObject (typeof (UnmanagedType), pos_values [0]);
983 UnmanagedType = (UnmanagedType) pos_values [0];
985 object value = GetFieldValue ("SizeParamIndex");
986 if (value != null && UnmanagedType != UnmanagedType.LPArray) {
987 Error_AttributeEmitError ("SizeParamIndex field is not valid for the specified unmanaged type");
991 object o = GetFieldValue ("ArraySubType");
992 UnmanagedType array_sub_type = o == null ? (UnmanagedType) 0x50 /* NATIVE_MAX */ : (UnmanagedType) o;
994 switch (UnmanagedType) {
995 case UnmanagedType.CustomMarshaler: {
996 MethodInfo define_custom = typeof (UnmanagedMarshal).GetMethod ("DefineCustom",
997 BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
998 if (define_custom == null) {
999 Report.RuntimeMissingSupport (Location, "set marshal info");
1003 object [] args = new object [4];
1004 args [0] = GetFieldValue ("MarshalTypeRef");
1005 args [1] = GetFieldValue ("MarshalCookie");
1006 args [2] = GetFieldValue ("MarshalType");
1007 args [3] = Guid.Empty;
1008 return (UnmanagedMarshal) define_custom.Invoke (null, args);
1010 case UnmanagedType.LPArray: {
1011 object size_const = GetFieldValue ("SizeConst");
1012 object size_param_index = GetFieldValue ("SizeParamIndex");
1014 if ((size_const != null) || (size_param_index != null)) {
1015 MethodInfo define_array = typeof (UnmanagedMarshal).GetMethod ("DefineLPArrayInternal",
1016 BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
1017 if (define_array == null) {
1018 Report.RuntimeMissingSupport (Location, "set marshal info");
1022 object [] args = new object [3];
1023 args [0] = array_sub_type;
1024 args [1] = size_const == null ? -1 : size_const;
1025 args [2] = size_param_index == null ? -1 : size_param_index;
1026 return (UnmanagedMarshal) define_array.Invoke (null, args);
1029 return UnmanagedMarshal.DefineLPArray (array_sub_type);
1031 case UnmanagedType.SafeArray:
1032 return UnmanagedMarshal.DefineSafeArray (array_sub_type);
1034 case UnmanagedType.ByValArray:
1035 FieldMember fm = attr as FieldMember;
1037 Error_AttributeEmitError ("Specified unmanaged type is only valid on fields");
1040 return UnmanagedMarshal.DefineByValArray ((int) GetFieldValue ("SizeConst"));
1042 case UnmanagedType.ByValTStr:
1043 return UnmanagedMarshal.DefineByValTStr ((int) GetFieldValue ("SizeConst"));
1046 return UnmanagedMarshal.DefineUnmanagedMarshal (UnmanagedType);
1050 public CharSet GetCharSetValue ()
1052 return (CharSet)System.Enum.Parse (typeof (CharSet), pos_values [0].ToString ());
1055 public MethodImplOptions GetMethodImplOptions ()
1057 if (pos_values [0].GetType () != typeof (MethodImplOptions))
1058 return (MethodImplOptions)System.Enum.ToObject (typeof (MethodImplOptions), pos_values [0]);
1059 return (MethodImplOptions)pos_values [0];
1062 public LayoutKind GetLayoutKindValue ()
1064 if (!RootContext.StdLib || pos_values [0].GetType () != typeof (LayoutKind))
1065 return (LayoutKind)System.Enum.ToObject (typeof (LayoutKind), pos_values [0]);
1067 return (LayoutKind)pos_values [0];
1071 /// Emit attribute for Attributable symbol
1073 public void Emit (EmitContext ec, Attributable ias, ListDictionary emitted_attr)
1075 CustomAttributeBuilder cb = Resolve (ec);
1079 AttributeUsageAttribute usage_attr = GetAttributeUsage (ec);
1080 if ((usage_attr.ValidOn & Target) == 0) {
1081 Report.Error (592, Location, "Attribute `{0}' is not valid on this declaration type. " +
1082 "It is valid on `{1}' declarations only",
1083 GetSignatureForError (), GetValidTargets ());
1088 ias.ApplyAttributeBuilder (this, cb);
1090 catch (Exception e) {
1091 Error_AttributeEmitError (e.Message);
1095 if (!usage_attr.AllowMultiple) {
1096 ArrayList emitted_targets = (ArrayList)emitted_attr [Type];
1097 if (emitted_targets == null) {
1098 emitted_targets = new ArrayList ();
1099 emitted_attr.Add (Type, emitted_targets);
1100 } else if (emitted_targets.Contains (Target)) {
1101 Report.Error (579, Location, "Duplicate `{0}' attribute", GetSignatureForError ());
1104 emitted_targets.Add (Target);
1107 if (!RootContext.VerifyClsCompliance)
1110 // Here we are testing attribute arguments for array usage (error 3016)
1111 if (ias.IsClsComplianceRequired (ec.DeclSpace)) {
1112 if (Arguments == null)
1115 ArrayList pos_args = (ArrayList) Arguments [0];
1116 if (pos_args != null) {
1117 foreach (Argument arg in pos_args) {
1118 // Type is undefined (was error 246)
1119 if (arg.Type == null)
1122 if (arg.Type.IsArray) {
1123 Report.Error (3016, Location, "Arrays as attribute arguments are not CLS-compliant");
1129 if (Arguments.Count < 2)
1132 ArrayList named_args = (ArrayList) Arguments [1];
1133 foreach (DictionaryEntry de in named_args) {
1134 Argument arg = (Argument) de.Value;
1136 // Type is undefined (was error 246)
1137 if (arg.Type == null)
1140 if (arg.Type.IsArray) {
1141 Report.Error (3016, Location, "Arrays as attribute arguments are not CLS-compliant");
1148 public MethodBuilder DefinePInvokeMethod (EmitContext ec, TypeBuilder builder, string name,
1149 MethodAttributes flags, Type ret_type, Type [] param_types)
1151 if (pos_values == null)
1152 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
1153 // But because a lot of attribute class code must be rewritten will be better to wait...
1159 string dll_name = (string)pos_values [0];
1162 CallingConvention cc = CallingConvention.Winapi;
1163 CharSet charset = CodeGen.Module.DefaultCharSet;
1164 bool preserve_sig = true;
1165 string entry_point = name;
1166 bool best_fit_mapping = false;
1167 bool throw_on_unmappable = false;
1168 bool exact_spelling = false;
1169 bool set_last_error = false;
1171 bool best_fit_mapping_set = false;
1172 bool throw_on_unmappable_set = false;
1173 bool exact_spelling_set = false;
1174 bool set_last_error_set = false;
1176 MethodInfo set_best_fit = null;
1177 MethodInfo set_throw_on = null;
1178 MethodInfo set_exact_spelling = null;
1179 MethodInfo set_set_last_error = null;
1181 if (field_info_arr != null) {
1183 for (int i = 0; i < field_info_arr.Length; i++) {
1184 switch (field_info_arr [i].Name) {
1185 case "BestFitMapping":
1186 best_fit_mapping = (bool) field_values_arr [i];
1187 best_fit_mapping_set = true;
1189 case "CallingConvention":
1190 cc = (CallingConvention) field_values_arr [i];
1193 charset = (CharSet) field_values_arr [i];
1196 entry_point = (string) field_values_arr [i];
1198 case "ExactSpelling":
1199 exact_spelling = (bool) field_values_arr [i];
1200 exact_spelling_set = true;
1203 preserve_sig = (bool) field_values_arr [i];
1205 case "SetLastError":
1206 set_last_error = (bool) field_values_arr [i];
1207 set_last_error_set = true;
1209 case "ThrowOnUnmappableChar":
1210 throw_on_unmappable = (bool) field_values_arr [i];
1211 throw_on_unmappable_set = true;
1214 throw new InternalErrorException (field_info_arr [i].ToString ());
1219 if (throw_on_unmappable_set || best_fit_mapping_set || exact_spelling_set || set_last_error_set) {
1220 set_best_fit = typeof (MethodBuilder).
1221 GetMethod ("set_BestFitMapping", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
1222 set_throw_on = typeof (MethodBuilder).
1223 GetMethod ("set_ThrowOnUnmappableChar", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
1224 set_exact_spelling = typeof (MethodBuilder).
1225 GetMethod ("set_ExactSpelling", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
1226 set_set_last_error = typeof (MethodBuilder).
1227 GetMethod ("set_SetLastError", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
1229 if ((set_best_fit == null) || (set_throw_on == null) ||
1230 (set_exact_spelling == null) || (set_set_last_error == null)) {
1231 Report.Error (-1, Location,
1232 "The ThrowOnUnmappableChar, BestFitMapping, SetLastError, " +
1233 "and ExactSpelling attributes can only be emitted when running on the mono runtime.");
1239 MethodBuilder mb = builder.DefinePInvokeMethod (
1240 name, dll_name, entry_point, flags | MethodAttributes.HideBySig | MethodAttributes.PinvokeImpl,
1241 CallingConventions.Standard, ret_type, param_types, cc, charset);
1244 mb.SetImplementationFlags (MethodImplAttributes.PreserveSig);
1246 if (throw_on_unmappable_set)
1247 set_throw_on.Invoke (mb, 0, null, new object [] { throw_on_unmappable }, null);
1248 if (best_fit_mapping_set)
1249 set_best_fit.Invoke (mb, 0, null, new object [] { best_fit_mapping }, null);
1250 if (exact_spelling_set)
1251 set_exact_spelling.Invoke (mb, 0, null, new object [] { exact_spelling }, null);
1252 if (set_last_error_set)
1253 set_set_last_error.Invoke (mb, 0, null, new object [] { set_last_error }, null);
1257 catch (ArgumentException e) {
1258 Error_AttributeEmitError (e.Message);
1263 private Expression GetValue ()
1265 if ((Arguments == null) || (Arguments.Count < 1))
1267 ArrayList al = (ArrayList) Arguments [0];
1268 if ((al == null) || (al.Count < 1))
1270 Argument arg = (Argument) al [0];
1271 if ((arg == null) || (arg.Expr == null))
1276 public string GetString ()
1278 Expression e = GetValue ();
1279 if (e is StringLiteral)
1280 return (e as StringLiteral).Value;
1284 public bool GetBoolean ()
1286 Expression e = GetValue ();
1287 if (e is BoolLiteral)
1288 return (e as BoolLiteral).Value;
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, ArrayList args, Location loc, bool nameEscaped):
1304 base (target, left_expr, identifier, args, loc, nameEscaped)
1311 // RootContext.Tree.Types has a single NamespaceEntry which gets overwritten
1312 // each time a new file is parsed. However, we need to use the NamespaceEntry
1313 // in effect where the attribute was used. Since code elsewhere cannot assume
1314 // that the NamespaceEntry is right, just overwrite it.
1316 // Precondition: RootContext.Tree.Types == null
1318 if (RootContext.Tree.Types.NamespaceEntry != null)
1319 throw new InternalErrorException (Location + " non-null NamespaceEntry");
1321 RootContext.Tree.Types.NamespaceEntry = ns;
1326 RootContext.Tree.Types.NamespaceEntry = null;
1329 protected override FullNamedExpression ResolveAsTypeStep (Expression expr, EmitContext ec, bool silent)
1333 return base.ResolveAsTypeStep (expr, ec, silent);
1341 protected override FullNamedExpression ResolveAsTypeTerminal (Expression expr, EmitContext ec, bool silent)
1345 return base.ResolveAsTypeTerminal (expr, ec, silent);
1352 protected override ConstructorInfo ResolveArguments (EmitContext ec)
1356 return base.ResolveArguments (ec);
1364 public class Attributes {
1365 public ArrayList Attrs;
1367 public Attributes (Attribute a)
1369 Attrs = new ArrayList ();
1373 public Attributes (ArrayList attrs)
1378 public void AddAttributes (ArrayList attrs)
1380 Attrs.AddRange (attrs);
1384 /// Checks whether attribute target is valid for the current element
1386 public bool CheckTargets (Attributable member)
1388 string[] valid_targets = member.ValidAttributeTargets;
1389 foreach (Attribute a in Attrs) {
1390 if (a.ExplicitTarget == null || a.ExplicitTarget == valid_targets [0]) {
1391 a.Target = member.AttributeTargets;
1395 // TODO: we can skip the first item
1396 if (((IList) valid_targets).Contains (a.ExplicitTarget)) {
1397 switch (a.ExplicitTarget) {
1398 case "return": a.Target = AttributeTargets.ReturnValue; continue;
1399 case "param": a.Target = AttributeTargets.Parameter; continue;
1400 case "field": a.Target = AttributeTargets.Field; continue;
1401 case "method": a.Target = AttributeTargets.Method; continue;
1402 case "property": a.Target = AttributeTargets.Property; continue;
1404 throw new InternalErrorException ("Unknown explicit target: " + a.ExplicitTarget);
1407 StringBuilder sb = new StringBuilder ();
1408 foreach (string s in valid_targets) {
1412 sb.Remove (sb.Length - 2, 2);
1413 Report.Error (657, a.Location, "`{0}' is not a valid attribute location for this declaration. " +
1414 "Valid attribute locations for this declaration are `{1}'", a.ExplicitTarget, sb.ToString ());
1420 public Attribute Search (Type t, EmitContext ec)
1422 foreach (Attribute a in Attrs) {
1423 if (a.ResolveType (ec) == t)
1430 /// Returns all attributes of type 't'. Use it when attribute is AllowMultiple = true
1432 public Attribute[] SearchMulti (Type t, EmitContext ec)
1434 ArrayList ar = null;
1436 foreach (Attribute a in Attrs) {
1437 if (a.ResolveType (ec) == t) {
1439 ar = new ArrayList ();
1444 return ar == null ? null : ar.ToArray (typeof (Attribute)) as Attribute[];
1447 public void Emit (EmitContext ec, Attributable ias)
1451 ListDictionary ld = new ListDictionary ();
1453 foreach (Attribute a in Attrs)
1454 a.Emit (ec, ias, ld);
1457 public bool Contains (Type t, EmitContext ec)
1459 return Search (t, ec) != null;
1464 /// Helper class for attribute verification routine.
1466 sealed class AttributeTester
1468 static PtrHashtable analyzed_types = new PtrHashtable ();
1469 static PtrHashtable analyzed_types_obsolete = new PtrHashtable ();
1470 static PtrHashtable analyzed_member_obsolete = new PtrHashtable ();
1471 static PtrHashtable analyzed_method_excluded = new PtrHashtable ();
1474 static PtrHashtable fixed_buffer_cache = new PtrHashtable ();
1477 static object TRUE = new object ();
1478 static object FALSE = new object ();
1480 private AttributeTester ()
1484 public enum Result {
1491 /// Returns true if parameters of two compared methods are CLS-Compliant.
1492 /// It tests differing only in ref or out, or in array rank.
1494 public static Result AreOverloadedMethodParamsClsCompliant (Type[] types_a, Type[] types_b)
1496 if (types_a == null || types_b == null)
1499 if (types_a.Length != types_b.Length)
1502 Result result = Result.Ok;
1503 for (int i = 0; i < types_b.Length; ++i) {
1504 Type aType = types_a [i];
1505 Type bType = types_b [i];
1507 if (aType.IsArray && bType.IsArray) {
1508 Type a_el_type = aType.GetElementType ();
1509 Type b_el_type = bType.GetElementType ();
1510 if (aType.GetArrayRank () != bType.GetArrayRank () && a_el_type == b_el_type) {
1511 result = Result.RefOutArrayError;
1515 if (a_el_type.IsArray || b_el_type.IsArray) {
1516 result = Result.ArrayArrayError;
1521 Type aBaseType = aType;
1522 bool is_either_ref_or_out = false;
1524 if (aType.IsByRef || aType.IsPointer) {
1525 aBaseType = aType.GetElementType ();
1526 is_either_ref_or_out = true;
1529 Type bBaseType = bType;
1530 if (bType.IsByRef || bType.IsPointer)
1532 bBaseType = bType.GetElementType ();
1533 is_either_ref_or_out = !is_either_ref_or_out;
1536 if (aBaseType != bBaseType)
1539 if (is_either_ref_or_out)
1540 result = Result.RefOutArrayError;
1546 /// This method tests the CLS compliance of external types. It doesn't test type visibility.
1548 public static bool IsClsCompliant (Type type)
1553 object type_compliance = analyzed_types[type];
1554 if (type_compliance != null)
1555 return type_compliance == TRUE;
1557 if (type.IsPointer) {
1558 analyzed_types.Add (type, null);
1563 if (type.IsArray || type.IsByRef) {
1564 result = IsClsCompliant (TypeManager.GetElementType (type));
1566 result = AnalyzeTypeCompliance (type);
1568 analyzed_types.Add (type, result ? TRUE : FALSE);
1573 /// Returns IFixedBuffer implementation if field is fixed buffer else null.
1575 public static IFixedBuffer GetFixedBuffer (FieldInfo fi)
1577 FieldBase fb = TypeManager.GetField (fi);
1579 return fb as IFixedBuffer;
1583 object o = fixed_buffer_cache [fi];
1585 if (System.Attribute.GetCustomAttribute (fi, TypeManager.fixed_buffer_attr_type) == null) {
1586 fixed_buffer_cache.Add (fi, FALSE);
1590 IFixedBuffer iff = new FixedFieldExternal (fi);
1591 fixed_buffer_cache.Add (fi, iff);
1598 return (IFixedBuffer)o;
1604 public static void VerifyModulesClsCompliance ()
1606 Module[] modules = RootNamespace.Global.Modules;
1607 if (modules == null)
1610 // The first module is generated assembly
1611 for (int i = 1; i < modules.Length; ++i) {
1612 Module module = modules [i];
1613 if (!IsClsCompliant (module)) {
1614 Report.Error (3013, "Added modules must be marked with the CLSCompliant attribute " +
1615 "to match the assembly", module.Name);
1621 public static Type GetImportedIgnoreCaseClsType (string name)
1623 foreach (Assembly a in RootNamespace.Global.Assemblies) {
1624 Type t = a.GetType (name, false, true);
1628 if (IsClsCompliant (t))
1634 static bool IsClsCompliant (ICustomAttributeProvider attribute_provider)
1636 object[] CompliantAttribute = attribute_provider.GetCustomAttributes (TypeManager.cls_compliant_attribute_type, false);
1637 if (CompliantAttribute.Length == 0)
1640 return ((CLSCompliantAttribute)CompliantAttribute[0]).IsCompliant;
1643 static bool AnalyzeTypeCompliance (Type type)
1645 DeclSpace ds = TypeManager.LookupDeclSpace (type);
1647 return ds.IsClsComplianceRequired (ds.Parent);
1650 object[] CompliantAttribute = type.GetCustomAttributes (TypeManager.cls_compliant_attribute_type, false);
1651 if (CompliantAttribute.Length == 0)
1652 return IsClsCompliant (type.Assembly);
1654 return ((CLSCompliantAttribute)CompliantAttribute[0]).IsCompliant;
1658 /// Returns instance of ObsoleteAttribute when type is obsolete
1660 public static ObsoleteAttribute GetObsoleteAttribute (Type type)
1662 object type_obsolete = analyzed_types_obsolete [type];
1663 if (type_obsolete == FALSE)
1666 if (type_obsolete != null)
1667 return (ObsoleteAttribute)type_obsolete;
1669 ObsoleteAttribute result = null;
1670 if (type.IsByRef || type.IsArray || type.IsPointer) {
1671 result = GetObsoleteAttribute (TypeManager.GetElementType (type));
1673 DeclSpace type_ds = TypeManager.LookupDeclSpace (type);
1675 // Type is external, we can get attribute directly
1676 if (type_ds == null) {
1677 object[] attribute = type.GetCustomAttributes (TypeManager.obsolete_attribute_type, false);
1678 if (attribute.Length == 1)
1679 result = (ObsoleteAttribute)attribute [0];
1681 result = type_ds.GetObsoleteAttribute ();
1685 // Cannot use .Add because of corlib bootstrap
1686 analyzed_types_obsolete [type] = result == null ? FALSE : result;
1691 /// Returns instance of ObsoleteAttribute when method is obsolete
1693 public static ObsoleteAttribute GetMethodObsoleteAttribute (MethodBase mb)
1695 IMethodData mc = TypeManager.GetMethod (mb);
1697 return mc.GetObsoleteAttribute ();
1699 // compiler generated methods are not registered by AddMethod
1700 if (mb.DeclaringType is TypeBuilder)
1703 if (mb.IsSpecialName) {
1704 PropertyInfo pi = PropertyExpr.AccessorTable [mb] as PropertyInfo;
1706 // FIXME: This is buggy as properties from this assembly are included as well
1708 //return GetMemberObsoleteAttribute (pi);
1712 return GetMemberObsoleteAttribute (mb);
1716 /// Returns instance of ObsoleteAttribute when member is obsolete
1718 public static ObsoleteAttribute GetMemberObsoleteAttribute (MemberInfo mi)
1720 object type_obsolete = analyzed_member_obsolete [mi];
1721 if (type_obsolete == FALSE)
1724 if (type_obsolete != null)
1725 return (ObsoleteAttribute)type_obsolete;
1727 ObsoleteAttribute oa = System.Attribute.GetCustomAttribute (mi, TypeManager.obsolete_attribute_type, false)
1728 as ObsoleteAttribute;
1729 analyzed_member_obsolete.Add (mi, oa == null ? FALSE : oa);
1734 /// Common method for Obsolete error/warning reporting.
1736 public static void Report_ObsoleteMessage (ObsoleteAttribute oa, string member, Location loc)
1739 Report.Error (619, loc, "`{0}' is obsolete: `{1}'", member, oa.Message);
1743 if (oa.Message == null) {
1744 Report.Warning (612, 1, loc, "`{0}' is obsolete", member);
1747 Report.Warning (618, 2, loc, "`{0}' is obsolete: `{1}'", member, oa.Message);
1750 public static bool IsConditionalMethodExcluded (MethodBase mb)
1752 object excluded = analyzed_method_excluded [mb];
1753 if (excluded != null)
1754 return excluded == TRUE ? true : false;
1756 ConditionalAttribute[] attrs = mb.GetCustomAttributes (TypeManager.conditional_attribute_type, true)
1757 as ConditionalAttribute[];
1758 if (attrs.Length == 0) {
1759 analyzed_method_excluded.Add (mb, FALSE);
1763 foreach (ConditionalAttribute a in attrs) {
1764 if (RootContext.AllDefines.Contains (a.ConditionString)) {
1765 analyzed_method_excluded.Add (mb, FALSE);
1769 analyzed_method_excluded.Add (mb, TRUE);
1774 /// Analyzes class whether it has attribute which has ConditionalAttribute
1775 /// and its condition is not defined.
1777 public static bool IsAttributeExcluded (Type type)
1782 Class class_decl = TypeManager.LookupDeclSpace (type) as Class;
1784 // TODO: add caching
1785 // TODO: merge all Type bases attribute caching to one cache to save memory
1786 if (class_decl == null) {
1787 object[] attributes = type.GetCustomAttributes (TypeManager.conditional_attribute_type, false);
1788 foreach (ConditionalAttribute ca in attributes) {
1789 if (RootContext.AllDefines.Contains (ca.ConditionString))
1792 return attributes.Length > 0;
1795 return class_decl.IsExcluded ();
1798 public static Type GetCoClassAttribute (Type type)
1800 TypeContainer tc = TypeManager.LookupInterface (type);
1802 object[] o = type.GetCustomAttributes (TypeManager.coclass_attr_type, false);
1803 return ((System.Runtime.InteropServices.CoClassAttribute)o[0]).CoClass;
1806 if (tc.OptAttributes == null)
1809 Attribute a = tc.OptAttributes.Search (TypeManager.coclass_attr_type, tc.EmitContext);
1813 return a.GetCoClassAttributeValue (tc.EmitContext);