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 public readonly string Name;
76 public readonly Expression LeftExpr;
77 public readonly string Identifier;
79 public readonly ArrayList Arguments;
81 public readonly Location Location;
87 static AttributeUsageAttribute DefaultUsageAttribute = new AttributeUsageAttribute (AttributeTargets.All);
88 static Assembly orig_sec_assembly;
90 // non-null if named args present after Resolve () is called
91 PropertyInfo [] prop_info_arr;
92 FieldInfo [] field_info_arr;
93 object [] field_values_arr;
94 object [] prop_values_arr;
97 static PtrHashtable usage_attr_cache = new PtrHashtable ();
99 public Attribute (string target, Expression left_expr, string identifier, ArrayList args, Location loc)
101 LeftExpr = left_expr;
102 Identifier = identifier;
103 Name = LeftExpr == null ? identifier : LeftExpr + "." + identifier;
106 ExplicitTarget = target;
109 void Error_InvalidNamedArgument (string name)
111 Report.Error (617, Location, "`{0}' is not a valid named attribute argument. Named attribute arguments must be fields which are not readonly, static, const or read-write properties which are public and not static",
115 void Error_InvalidNamedAgrumentType (string name)
117 Report.Error (655, Location, "`{0}' is not a valid named attribute argument because it is not a valid attribute parameter type", name);
120 static void Error_AttributeArgumentNotValid (string extra, Location loc)
122 Report.Error (182, loc,
123 "An attribute argument must be a constant expression, typeof " +
124 "expression or array creation expression" + extra);
127 static void Error_AttributeArgumentNotValid (Location loc)
129 Error_AttributeArgumentNotValid ("", loc);
132 static void Error_TypeParameterInAttribute (Location loc)
135 -202, loc, "Can not use a type parameter in an attribute");
139 /// This is rather hack. We report many emit attribute error with same error to be compatible with
140 /// csc. But because csc has to report them this way because error came from ilasm we needn't.
142 public void Error_AttributeEmitError (string inner)
144 Report.Error (647, Location, "Error during emitting `{0}' attribute. The reason is `{1}'", TypeManager.CSharpName (Type), inner);
147 public void Error_InvalidSecurityParent ()
149 Error_AttributeEmitError ("it is attached to invalid parent");
152 void Error_AttributeConstructorMismatch ()
154 Report.Error (-6, Location,
155 "Could not find a constructor for this argument list.");
159 protected virtual FullNamedExpression ResolveAsTypeStep (Expression expr, EmitContext ec)
161 return expr.ResolveAsTypeStep (ec);
164 void ResolvePossibleAttributeTypes (EmitContext ec, out Type t1, out Type t2)
169 FullNamedExpression n1 = null;
170 FullNamedExpression n2 = null;
171 string IdentifierAttribute = Identifier + "Attribute";
172 if (LeftExpr == null) {
173 n1 = ResolveAsTypeStep (new SimpleName (Identifier, Location), ec);
175 // FIXME: Shouldn't do this for quoted attributes: [@A]
176 n2 = ResolveAsTypeStep (new SimpleName (IdentifierAttribute, Location), ec);
178 FullNamedExpression l = ResolveAsTypeStep (LeftExpr, ec);
180 NamespaceEntry.Error_NamespaceNotFound (Location, LeftExpr.GetSignatureForError ());
183 n1 = new MemberAccess (l, Identifier, Location).ResolveNamespaceOrType (ec, true);
185 // FIXME: Shouldn't do this for quoted attributes: [X.@A]
186 n2 = new MemberAccess (l, IdentifierAttribute, Location).ResolveNamespaceOrType (ec, true);
189 TypeExpr te1 = n1 == null ? null : n1 as TypeExpr;
190 TypeExpr te2 = n2 == null ? null : n2 as TypeExpr;
193 t1 = te1.ResolveType (ec);
195 t2 = te2.ResolveType (ec);
199 /// Tries to resolve the type of the attribute. Flags an error if it can't, and complain is true.
201 Type CheckAttributeType (EmitContext ec)
204 ResolvePossibleAttributeTypes (ec, out t1, out t2);
206 String err0616 = null;
207 if (t1 != null && ! t1.IsSubclassOf (TypeManager.attribute_type)) {
209 err0616 = "`{0}' is not an attribute class";
211 if (t2 != null && ! t2.IsSubclassOf (TypeManager.attribute_type)) {
213 err0616 = (err0616 != null)
214 ? "Neither `{0}' nor `{0}Attribute' is an attribute class"
215 : "`{0}Attribute': is not an attribute class";
218 if (t1 != null && t2 != null) {
219 Report.Error (1614, Location, "`{0}' is ambiguous between `{0}' and `{0}Attribute'. Use either `@{0}' or `{0}Attribute'", Name);
220 resolve_error = true;
227 if (err0616 != null) {
228 Report.Error (616, Location, err0616, Name);
232 NamespaceEntry.Error_NamespaceNotFound (Location, Name);
234 resolve_error = true;
238 public virtual Type ResolveType (EmitContext ec)
240 if (Type == null && !resolve_error)
241 Type = CheckAttributeType (ec);
245 string GetFullMemberName (string member)
247 return Type.FullName + '.' + member;
251 // Given an expression, if the expression is a valid attribute-argument-expression
252 // returns an object that can be used to encode it, or null on failure.
254 public static bool GetAttributeArgumentExpression (Expression e, Location loc, Type arg_type, out object result)
256 if (e is EnumConstant) {
257 if (RootContext.StdLib)
258 result = ((EnumConstant)e).GetValueAsEnumType ();
260 result = ((EnumConstant)e).GetValue ();
265 Constant constant = e as Constant;
266 if (constant != null) {
267 if (e.Type != arg_type) {
268 constant = Const.ChangeType (loc, constant, arg_type);
269 if (constant == null) {
271 Error_AttributeArgumentNotValid (loc);
275 result = constant.GetValue ();
277 } else if (e is TypeOf) {
278 result = ((TypeOf) e).TypeArg;
280 } else if (e is ArrayCreation){
281 result = ((ArrayCreation) e).EncodeAsAttribute ();
284 } else if (e is EmptyCast) {
285 Expression child = ((EmptyCast)e).Child;
286 return GetAttributeArgumentExpression (child, loc, child.Type, out result);
290 Error_AttributeArgumentNotValid (loc);
294 bool IsValidArgumentType (Type t)
296 return TypeManager.IsPrimitiveType (t) ||
297 (t.IsArray && TypeManager.IsPrimitiveType (t.GetElementType ())) ||
298 TypeManager.IsEnumType (t) ||
299 t == TypeManager.string_type ||
300 t == TypeManager.object_type ||
301 t == TypeManager.type_type;
304 // Cache for parameter-less attributes
305 static PtrHashtable att_cache = new PtrHashtable ();
307 public CustomAttributeBuilder Resolve (EmitContext ec)
312 resolve_error = true;
315 Type = CheckAttributeType (ec);
321 if (Type.IsAbstract) {
322 Report.Error (653, Location, "Cannot apply attribute class `{0}' because it is abstract", Name);
326 if (Arguments == null) {
327 object o = att_cache [Type];
329 resolve_error = false;
330 return (CustomAttributeBuilder)o;
334 ConstructorInfo ctor = ResolveArguments (ec);
335 CustomAttributeBuilder cb;
338 if (prop_info_arr != null || field_info_arr != null) {
339 cb = new CustomAttributeBuilder (
341 prop_info_arr, prop_values_arr,
342 field_info_arr, field_values_arr);
344 cb = new CustomAttributeBuilder (
347 if (pos_values.Length == 0)
348 att_cache.Add (Type, cb);
352 Error_AttributeArgumentNotValid (Location);
356 resolve_error = false;
360 protected virtual ConstructorInfo ResolveArguments (EmitContext ec)
362 // Now we extract the positional and named arguments
364 ArrayList pos_args = null;
365 ArrayList named_args = null;
366 int pos_arg_count = 0;
367 int named_arg_count = 0;
369 if (Arguments != null) {
370 pos_args = (ArrayList) Arguments [0];
371 if (pos_args != null)
372 pos_arg_count = pos_args.Count;
373 if (Arguments.Count > 1) {
374 named_args = (ArrayList) Arguments [1];
375 named_arg_count = named_args.Count;
379 pos_values = new object [pos_arg_count];
382 // First process positional arguments
386 for (i = 0; i < pos_arg_count; i++) {
387 Argument a = (Argument) pos_args [i];
390 if (!a.Resolve (ec, Location))
396 if (!GetAttributeArgumentExpression (e, Location, a.Type, out val))
399 pos_values [i] = val;
401 if (i == 0 && Type == TypeManager.attribute_usage_type && (int)val == 0) {
402 Report.Error (591, Location, "Invalid value for argument to 'System.AttributeUsage' attribute");
408 // Now process named arguments
411 ArrayList field_infos = null;
412 ArrayList prop_infos = null;
413 ArrayList field_values = null;
414 ArrayList prop_values = null;
415 Hashtable seen_names = null;
417 if (named_arg_count > 0) {
418 field_infos = new ArrayList ();
419 prop_infos = new ArrayList ();
420 field_values = new ArrayList ();
421 prop_values = new ArrayList ();
423 seen_names = new Hashtable();
426 for (i = 0; i < named_arg_count; i++) {
427 DictionaryEntry de = (DictionaryEntry) named_args [i];
428 string member_name = (string) de.Key;
429 Argument a = (Argument) de.Value;
432 if (seen_names.Contains(member_name)) {
433 Report.Error(643, Location, "'" + member_name + "' duplicate named attribute argument");
436 seen_names.Add(member_name, 1);
438 if (!a.Resolve (ec, Location))
441 Expression member = Expression.MemberLookup (
442 ec, Type, member_name,
443 MemberTypes.Field | MemberTypes.Property,
444 BindingFlags.Public | BindingFlags.Instance,
447 if (member == null) {
448 member = Expression.MemberLookup (ec, Type, member_name,
449 MemberTypes.Field | MemberTypes.Property, BindingFlags.NonPublic | BindingFlags.Instance,
452 if (member != null) {
453 Expression.ErrorIsInaccesible (Location, GetFullMemberName (member_name));
459 Report.Error (117, Location, "`{0}' does not contain a definition for `{1}'",
464 if (!(member is PropertyExpr || member is FieldExpr)) {
465 Error_InvalidNamedArgument (member_name);
470 if (e is TypeParameterExpr){
471 Error_TypeParameterInAttribute (Location);
475 if (member is PropertyExpr) {
476 PropertyExpr pe = (PropertyExpr) member;
477 PropertyInfo pi = pe.PropertyInfo;
479 if (!pi.CanWrite || !pi.CanRead) {
480 Report.SymbolRelatedToPreviousError (pi);
481 Error_InvalidNamedArgument (member_name);
485 if (!IsValidArgumentType (pi.PropertyType)) {
486 Report.SymbolRelatedToPreviousError (pi);
487 Error_InvalidNamedAgrumentType (member_name);
492 if (!GetAttributeArgumentExpression (e, Location, pi.PropertyType, out value))
495 prop_values.Add (value);
498 } else if (member is FieldExpr) {
499 FieldExpr fe = (FieldExpr) member;
500 FieldInfo fi = fe.FieldInfo;
503 Error_InvalidNamedArgument (member_name);
507 if (!IsValidArgumentType (fi.FieldType)) {
508 Report.SymbolRelatedToPreviousError (fi);
509 Error_InvalidNamedAgrumentType (member_name);
514 if (!GetAttributeArgumentExpression (e, Location, fi.FieldType, out value))
517 field_values.Add (value);
519 field_infos.Add (fi);
523 Expression mg = Expression.MemberLookup (
524 ec, Type, ".ctor", MemberTypes.Constructor,
525 BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly,
529 Error_AttributeConstructorMismatch ();
533 MethodBase constructor = Invocation.OverloadResolve (
534 ec, (MethodGroupExpr) mg, pos_args, false, Location);
536 if (constructor == null) {
541 // Here we do the checks which should be done by corlib or by runtime.
542 // However Zoltan doesn't like it and every Mono compiler has to do it again.
544 if (Type == TypeManager.guid_attr_type) {
546 new Guid ((string)pos_values [0]);
548 catch (Exception e) {
549 Error_AttributeEmitError (e.Message);
553 // if (Type == TypeManager.methodimpl_attr_type &&
554 // pos_values.Length == 1 && ((Argument)pos_args [0]).Type == TypeManager.short_type &&
555 // !System.Enum.IsDefined (TypeManager.method_impl_options, pos_values [0])) {
556 // Error_AttributeEmitError ("Incorrect argument value.");
560 // Now we perform some checks on the positional args as they
561 // cannot be null for a constructor which expects a parameter
565 ParameterData pd = TypeManager.GetParameterData (constructor);
567 int last_real_param = pd.Count;
569 // When the params is not filled we need to put one
570 if (last_real_param > pos_arg_count) {
571 object [] new_pos_values = new object [pos_arg_count + 1];
572 pos_values.CopyTo (new_pos_values, 0);
573 new_pos_values [pos_arg_count] = new object [] {} ;
574 pos_values = new_pos_values;
579 for (int j = 0; j < pos_arg_count; ++j) {
580 Argument a = (Argument) pos_args [j];
582 if (a.Expr is NullLiteral && pd.ParameterType (j) == TypeManager.object_type) {
583 Error_AttributeArgumentNotValid (Location);
587 object value = pos_values [j];
588 if (value != null && a.Type != value.GetType () && TypeManager.IsPrimitiveType (a.Type)) {
590 pos_values [j] = TypeManager.ChangeType (value, a.Type, out fail);
592 // TODO: Can failed ?
593 throw new NotImplementedException ();
597 if (j < last_real_param)
600 if (j == last_real_param) {
601 object [] array = new object [pos_arg_count - last_real_param];
602 array [0] = pos_values [j];
603 pos_values [j] = array;
607 object [] params_array = (object []) pos_values [last_real_param];
608 params_array [j - last_real_param] = pos_values [j];
611 // Adjust the size of the pos_values if it had params
612 if (last_real_param != pos_arg_count) {
613 object [] new_pos_values = new object [last_real_param + 1];
614 Array.Copy (pos_values, new_pos_values, last_real_param + 1);
615 pos_values = new_pos_values;
618 if (named_arg_count > 0) {
619 prop_info_arr = new PropertyInfo [prop_infos.Count];
620 field_info_arr = new FieldInfo [field_infos.Count];
621 field_values_arr = new object [field_values.Count];
622 prop_values_arr = new object [prop_values.Count];
624 field_infos.CopyTo (field_info_arr, 0);
625 field_values.CopyTo (field_values_arr, 0);
627 prop_values.CopyTo (prop_values_arr, 0);
628 prop_infos.CopyTo (prop_info_arr, 0);
631 return (ConstructorInfo) constructor;
635 /// Get a string containing a list of valid targets for the attribute 'attr'
637 public string GetValidTargets ()
639 StringBuilder sb = new StringBuilder ();
640 AttributeTargets targets = GetAttributeUsage (null).ValidOn;
642 if ((targets & AttributeTargets.Assembly) != 0)
643 sb.Append ("assembly, ");
645 if ((targets & AttributeTargets.Module) != 0)
646 sb.Append ("module, ");
648 if ((targets & AttributeTargets.Class) != 0)
649 sb.Append ("class, ");
651 if ((targets & AttributeTargets.Struct) != 0)
652 sb.Append ("struct, ");
654 if ((targets & AttributeTargets.Enum) != 0)
655 sb.Append ("enum, ");
657 if ((targets & AttributeTargets.Constructor) != 0)
658 sb.Append ("constructor, ");
660 if ((targets & AttributeTargets.Method) != 0)
661 sb.Append ("method, ");
663 if ((targets & AttributeTargets.Property) != 0)
664 sb.Append ("property, indexer, ");
666 if ((targets & AttributeTargets.Field) != 0)
667 sb.Append ("field, ");
669 if ((targets & AttributeTargets.Event) != 0)
670 sb.Append ("event, ");
672 if ((targets & AttributeTargets.Interface) != 0)
673 sb.Append ("interface, ");
675 if ((targets & AttributeTargets.Parameter) != 0)
676 sb.Append ("parameter, ");
678 if ((targets & AttributeTargets.Delegate) != 0)
679 sb.Append ("delegate, ");
681 if ((targets & AttributeTargets.ReturnValue) != 0)
682 sb.Append ("return, ");
684 if ((targets & AttributeTargets.GenericParameter) != 0)
685 sb.Append ("type parameter, ");
686 return sb.Remove (sb.Length - 2, 2).ToString ();
690 /// Returns AttributeUsage attribute for this type
692 AttributeUsageAttribute GetAttributeUsage (EmitContext ec)
694 AttributeUsageAttribute ua = usage_attr_cache [Type] as AttributeUsageAttribute;
698 Class attr_class = TypeManager.LookupClass (Type);
700 if (attr_class == null) {
701 object[] usage_attr = Type.GetCustomAttributes (TypeManager.attribute_usage_type, true);
702 ua = (AttributeUsageAttribute)usage_attr [0];
703 usage_attr_cache.Add (Type, ua);
707 Attribute a = attr_class.OptAttributes == null
709 : attr_class.OptAttributes.Search (TypeManager.attribute_usage_type, attr_class.EmitContext);
712 ? DefaultUsageAttribute
713 : a.GetAttributeUsageAttribute (attr_class.EmitContext);
715 usage_attr_cache.Add (Type, ua);
719 AttributeUsageAttribute GetAttributeUsageAttribute (EmitContext ec)
721 if (pos_values == null)
722 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
723 // But because a lot of attribute class code must be rewritten will be better to wait...
727 return DefaultUsageAttribute;
729 AttributeUsageAttribute usage_attribute = new AttributeUsageAttribute ((AttributeTargets)pos_values [0]);
731 object field = GetPropertyValue ("AllowMultiple");
733 usage_attribute.AllowMultiple = (bool)field;
735 field = GetPropertyValue ("Inherited");
737 usage_attribute.Inherited = (bool)field;
739 return usage_attribute;
743 /// Returns custom name of indexer
745 public string GetIndexerAttributeValue (EmitContext ec)
747 if (pos_values == null)
748 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
749 // But because a lot of attribute class code must be rewritten will be better to wait...
755 return pos_values [0] as string;
759 /// Returns condition of ConditionalAttribute
761 public string GetConditionalAttributeValue (EmitContext ec)
763 if (pos_values == null)
764 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
765 // But because a lot of attribute class code must be rewritten will be better to wait...
771 return (string)pos_values [0];
775 /// Creates the instance of ObsoleteAttribute from this attribute instance
777 public ObsoleteAttribute GetObsoleteAttribute (EmitContext ec)
779 if (pos_values == null)
780 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
781 // But because a lot of attribute class code must be rewritten will be better to wait...
787 if (pos_values == null || pos_values.Length == 0)
788 return new ObsoleteAttribute ();
790 if (pos_values.Length == 1)
791 return new ObsoleteAttribute ((string)pos_values [0]);
793 return new ObsoleteAttribute ((string)pos_values [0], (bool)pos_values [1]);
797 /// Returns value of CLSCompliantAttribute contructor parameter but because the method can be called
798 /// before ApplyAttribute. We need to resolve the arguments.
799 /// This situation occurs when class deps is differs from Emit order.
801 public bool GetClsCompliantAttributeValue (EmitContext ec)
803 if (pos_values == null)
804 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
805 // But because a lot of attribute class code must be rewritten will be better to wait...
811 return (bool)pos_values [0];
815 /// Tests permitted SecurityAction for assembly or other types
817 public bool CheckSecurityActionValidity (bool for_assembly)
819 SecurityAction action = GetSecurityActionValue ();
822 case SecurityAction.Demand:
823 case SecurityAction.Assert:
824 case SecurityAction.Deny:
825 case SecurityAction.PermitOnly:
826 case SecurityAction.LinkDemand:
827 case SecurityAction.InheritanceDemand:
832 case SecurityAction.RequestMinimum:
833 case SecurityAction.RequestOptional:
834 case SecurityAction.RequestRefuse:
840 Error_AttributeEmitError ("SecurityAction is out of range X");
844 Error_AttributeEmitError (String.Concat ("SecurityAction '", action, "' is not valid for this declaration"));
848 System.Security.Permissions.SecurityAction GetSecurityActionValue ()
850 return (SecurityAction)pos_values [0];
854 /// Creates instance of SecurityAttribute class and add result of CreatePermission method to permission table.
856 /// <returns></returns>
857 public void ExtractSecurityPermissionSet (ListDictionary permissions)
859 Type orig_assembly_type = null;
861 if (TypeManager.LookupDeclSpace (Type) != null) {
862 if (!RootContext.StdLib) {
863 orig_assembly_type = Type.GetType (Type.FullName);
865 string orig_version_path = Environment.GetEnvironmentVariable ("__SECURITY_BOOTSTRAP_DB");
866 if (orig_version_path == null) {
867 Error_AttributeEmitError ("security custom attributes can not be referenced from defining assembly");
871 if (orig_sec_assembly == null) {
872 string file = Path.Combine (orig_version_path, Driver.OutputFile);
873 orig_sec_assembly = Assembly.LoadFile (file);
876 orig_assembly_type = orig_sec_assembly.GetType (Type.FullName, true);
877 if (orig_assembly_type == null) {
878 Report.Warning (-112, 1, Location, "Self-referenced security attribute `{0}' was not found in previous version of assembly");
884 SecurityAttribute sa;
885 // For all non-selfreferencing security attributes we can avoid all hacks
886 if (orig_assembly_type == null) {
887 sa = (SecurityAttribute) Activator.CreateInstance (Type, pos_values);
889 if (prop_info_arr != null) {
890 for (int i = 0; i < prop_info_arr.Length; ++i) {
891 PropertyInfo pi = prop_info_arr [i];
892 pi.SetValue (sa, prop_values_arr [i], null);
896 // HACK: All security attributes have same ctor syntax
897 sa = (SecurityAttribute) Activator.CreateInstance (orig_assembly_type, new object[] { GetSecurityActionValue () } );
899 // All types are from newly created assembly but for invocation with old one we need to convert them
900 if (prop_info_arr != null) {
901 for (int i = 0; i < prop_info_arr.Length; ++i) {
902 PropertyInfo emited_pi = prop_info_arr [i];
903 PropertyInfo pi = orig_assembly_type.GetProperty (emited_pi.Name, emited_pi.PropertyType);
905 object old_instance = pi.PropertyType.IsEnum ?
906 System.Enum.ToObject (pi.PropertyType, prop_values_arr [i]) :
909 pi.SetValue (sa, old_instance, null);
915 perm = sa.CreatePermission ();
916 SecurityAction action = GetSecurityActionValue ();
918 // IS is correct because for corlib we are using an instance from old corlib
919 if (!(perm is System.Security.CodeAccessPermission)) {
921 case SecurityAction.Demand:
922 action = (SecurityAction)13;
924 case SecurityAction.LinkDemand:
925 action = (SecurityAction)14;
927 case SecurityAction.InheritanceDemand:
928 action = (SecurityAction)15;
933 PermissionSet ps = (PermissionSet)permissions [action];
935 if (sa is PermissionSetAttribute)
936 ps = new PermissionSet (sa.Unrestricted ? PermissionState.Unrestricted : PermissionState.None);
938 ps = new PermissionSet (PermissionState.None);
940 permissions.Add (action, ps);
941 } else if (!ps.IsUnrestricted () && (sa is PermissionSetAttribute) && sa.Unrestricted) {
942 ps = ps.Union (new PermissionSet (PermissionState.Unrestricted));
943 permissions [action] = ps;
945 ps.AddPermission (perm);
948 object GetValue (object value)
950 if (value is EnumConstant)
951 return ((EnumConstant) value).GetValue ();
956 object GetPropertyValue (string name)
958 if (prop_info_arr == null)
961 for (int i = 0; i < prop_info_arr.Length; ++i) {
962 if (prop_info_arr [i].Name == name)
963 return prop_values_arr [i];
969 object GetFieldValue (string name)
972 if (field_info_arr == null)
975 foreach (FieldInfo fi in field_info_arr) {
977 return GetValue (field_values_arr [i]);
983 public UnmanagedMarshal GetMarshal (Attributable attr)
985 UnmanagedType UnmanagedType = (UnmanagedType)System.Enum.Parse (typeof (UnmanagedType), pos_values [0].ToString ());
987 object value = GetFieldValue ("SizeParamIndex");
988 if (value != null && UnmanagedType != UnmanagedType.LPArray) {
989 Error_AttributeEmitError ("SizeParamIndex field is not valid for the specified unmanaged type");
993 object o = GetFieldValue ("ArraySubType");
994 UnmanagedType array_sub_type = o == null ? UnmanagedType.I4 : (UnmanagedType) o;
996 switch (UnmanagedType) {
997 case UnmanagedType.CustomMarshaler: {
998 MethodInfo define_custom = typeof (UnmanagedMarshal).GetMethod ("DefineCustom",
999 BindingFlags.Static | BindingFlags.Public);
1000 if (define_custom == null) {
1001 Report.RuntimeMissingSupport (Location, "set marshal info");
1005 object [] args = new object [4];
1006 args [0] = GetFieldValue ("MarshalTypeRef");
1007 args [1] = GetFieldValue ("MarshalCookie");
1008 args [2] = GetFieldValue ("MarshalType");
1009 args [3] = Guid.Empty;
1010 return (UnmanagedMarshal) define_custom.Invoke (null, args);
1012 case UnmanagedType.LPArray: {
1013 object size_const = GetFieldValue ("SizeConst");
1014 object size_param_index = GetFieldValue ("SizeParamIndex");
1016 if ((size_const != null) || (size_param_index != null)) {
1017 MethodInfo define_array = typeof (UnmanagedMarshal).GetMethod ("DefineLPArrayInternal", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
1018 if (define_array == null) {
1019 Report.RuntimeMissingSupport (Location, "set marshal info");
1023 object [] args = new object [3];
1024 args [0] = array_sub_type;
1025 args [1] = size_const == null ? -1 : size_const;
1026 args [2] = size_param_index == null ? -1 : size_param_index;
1027 return (UnmanagedMarshal) define_array.Invoke (null, args);
1030 return UnmanagedMarshal.DefineLPArray (array_sub_type);
1032 case UnmanagedType.SafeArray:
1033 return UnmanagedMarshal.DefineSafeArray (array_sub_type);
1035 case UnmanagedType.ByValArray:
1036 FieldMember fm = attr as FieldMember;
1038 Error_AttributeEmitError ("Specified unmanaged type is only valid on fields");
1041 return UnmanagedMarshal.DefineByValArray ((int) GetFieldValue ("SizeConst"));
1043 case UnmanagedType.ByValTStr:
1044 return UnmanagedMarshal.DefineByValTStr ((int) GetFieldValue ("SizeConst"));
1047 return UnmanagedMarshal.DefineUnmanagedMarshal (UnmanagedType);
1051 public CharSet GetCharSetValue ()
1053 return (CharSet)System.Enum.Parse (typeof (CharSet), pos_values [0].ToString ());
1056 public MethodImplOptions GetMethodImplOptions ()
1058 return (MethodImplOptions)System.Enum.Parse (typeof (MethodImplOptions), pos_values [0].ToString ());
1061 public LayoutKind GetLayoutKindValue ()
1063 return (LayoutKind)System.Enum.Parse (typeof (LayoutKind), pos_values [0].ToString ());
1067 /// Emit attribute for Attributable symbol
1069 public void Emit (EmitContext ec, Attributable ias, ListDictionary emitted_attr)
1071 CustomAttributeBuilder cb = Resolve (ec);
1075 AttributeUsageAttribute usage_attr = GetAttributeUsage (ec);
1076 if ((usage_attr.ValidOn & Target) == 0) {
1077 Report.Error (592, Location, "Attribute `{0}' is not valid on this declaration type. It is valid on `{1}' declarations only",
1078 Name, GetValidTargets ());
1083 ias.ApplyAttributeBuilder (this, cb);
1085 catch (Exception e) {
1086 Error_AttributeEmitError (e.Message);
1090 if (!usage_attr.AllowMultiple) {
1091 ArrayList emitted_targets = (ArrayList)emitted_attr [Type];
1092 if (emitted_targets == null) {
1093 emitted_targets = new ArrayList ();
1094 emitted_attr.Add (Type, emitted_targets);
1095 } else if (emitted_targets.Contains (Target)) {
1096 Report.Error (579, Location, "Duplicate '" + Name + "' attribute");
1099 emitted_targets.Add (Target);
1102 if (!RootContext.VerifyClsCompliance)
1105 // Here we are testing attribute arguments for array usage (error 3016)
1106 if (ias.IsClsComplianceRequired (ec.DeclSpace)) {
1107 if (Arguments == null)
1110 ArrayList pos_args = (ArrayList) Arguments [0];
1111 if (pos_args != null) {
1112 foreach (Argument arg in pos_args) {
1113 // Type is undefined (was error 246)
1114 if (arg.Type == null)
1117 if (arg.Type.IsArray) {
1118 Report.Error (3016, Location, "Arrays as attribute arguments are not CLS-compliant");
1124 if (Arguments.Count < 2)
1127 ArrayList named_args = (ArrayList) Arguments [1];
1128 foreach (DictionaryEntry de in named_args) {
1129 Argument arg = (Argument) de.Value;
1131 // Type is undefined (was error 246)
1132 if (arg.Type == null)
1135 if (arg.Type.IsArray) {
1136 Report.Error (3016, Location, "Arrays as attribute arguments are not CLS-compliant");
1143 public MethodBuilder DefinePInvokeMethod (EmitContext ec, TypeBuilder builder, string name,
1144 MethodAttributes flags, Type ret_type, Type [] param_types)
1146 if (pos_values == null)
1147 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
1148 // But because a lot of attribute class code must be rewritten will be better to wait...
1154 string dll_name = (string)pos_values [0];
1157 CallingConvention cc = CallingConvention.Winapi;
1158 CharSet charset = CodeGen.Module.DefaultCharSet;
1159 bool preserve_sig = true;
1160 string entry_point = name;
1161 bool best_fit_mapping = false;
1162 bool throw_on_unmappable = false;
1163 bool exact_spelling = false;
1164 bool set_last_error = false;
1166 bool best_fit_mapping_set = false;
1167 bool throw_on_unmappable_set = false;
1168 bool exact_spelling_set = false;
1169 bool set_last_error_set = false;
1171 MethodInfo set_best_fit = null;
1172 MethodInfo set_throw_on = null;
1173 MethodInfo set_exact_spelling = null;
1174 MethodInfo set_set_last_error = null;
1176 if (field_info_arr != null) {
1178 for (int i = 0; i < field_info_arr.Length; i++) {
1179 switch (field_info_arr [i].Name) {
1180 case "BestFitMapping":
1181 best_fit_mapping = (bool) field_values_arr [i];
1182 best_fit_mapping_set = true;
1184 case "CallingConvention":
1185 cc = (CallingConvention) field_values_arr [i];
1188 charset = (CharSet) field_values_arr [i];
1191 entry_point = (string) field_values_arr [i];
1193 case "ExactSpelling":
1194 exact_spelling = (bool) field_values_arr [i];
1195 exact_spelling_set = true;
1198 preserve_sig = (bool) field_values_arr [i];
1200 case "SetLastError":
1201 set_last_error = (bool) field_values_arr [i];
1202 set_last_error_set = true;
1204 case "ThrowOnUnmappableChar":
1205 throw_on_unmappable = (bool) field_values_arr [i];
1206 throw_on_unmappable_set = true;
1209 throw new InternalErrorException (field_info_arr [i].ToString ());
1214 if (throw_on_unmappable_set || best_fit_mapping_set || exact_spelling_set || set_last_error_set) {
1215 set_best_fit = typeof (MethodBuilder).GetMethod ("set_BestFitMapping", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
1216 set_throw_on = typeof (MethodBuilder).GetMethod ("set_ThrowOnUnmappableChar", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
1217 set_exact_spelling = typeof (MethodBuilder).GetMethod ("set_ExactSpelling", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
1218 set_set_last_error = typeof (MethodBuilder).GetMethod ("set_SetLastError", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
1220 if ((set_best_fit == null) || (set_throw_on == null) || (set_exact_spelling == null) || (set_set_last_error == null)) {
1221 Report.Error (-1, Location,
1222 "The ThrowOnUnmappableChar, BestFitMapping, SetLastError, and ExactSpelling attributes can only be emitted when running on the mono runtime.");
1228 MethodBuilder mb = builder.DefinePInvokeMethod (
1229 name, dll_name, entry_point, flags | MethodAttributes.HideBySig | MethodAttributes.PinvokeImpl,
1230 CallingConventions.Standard, ret_type, param_types, cc, charset);
1233 mb.SetImplementationFlags (MethodImplAttributes.PreserveSig);
1235 if (throw_on_unmappable_set)
1236 set_throw_on.Invoke (mb, 0, null, new object [] { throw_on_unmappable }, null);
1237 if (best_fit_mapping_set)
1238 set_best_fit.Invoke (mb, 0, null, new object [] { best_fit_mapping }, null);
1239 if (exact_spelling_set)
1240 set_exact_spelling.Invoke (mb, 0, null, new object [] { exact_spelling }, null);
1241 if (set_last_error_set)
1242 set_set_last_error.Invoke (mb, 0, null, new object [] { set_last_error }, null);
1246 catch (ArgumentException e) {
1247 Error_AttributeEmitError (e.Message);
1252 private Expression GetValue ()
1254 if ((Arguments == null) || (Arguments.Count < 1))
1256 ArrayList al = (ArrayList) Arguments [0];
1257 if ((al == null) || (al.Count < 1))
1259 Argument arg = (Argument) al [0];
1260 if ((arg == null) || (arg.Expr == null))
1265 public string GetString ()
1267 Expression e = GetValue ();
1268 if (e is StringLiteral)
1269 return (e as StringLiteral).Value;
1273 public bool GetBoolean ()
1275 Expression e = GetValue ();
1276 if (e is BoolLiteral)
1277 return (e as BoolLiteral).Value;
1284 /// For global attributes (assembly, module) we need special handling.
1285 /// Attributes can be located in the several files
1287 public class GlobalAttribute: Attribute
1289 public readonly NamespaceEntry ns;
1291 public GlobalAttribute (TypeContainer container, string target,
1292 Expression left_expr, string identifier, ArrayList args, Location loc):
1293 base (target, left_expr, identifier, args, loc)
1295 ns = container.NamespaceEntry;
1300 // RootContext.Tree.Types has a single NamespaceEntry which gets overwritten
1301 // each time a new file is parsed. However, we need to use the NamespaceEntry
1302 // in effect where the attribute was used. Since code elsewhere cannot assume
1303 // that the NamespaceEntry is right, just overwrite it.
1305 // Precondition: RootContext.Tree.Types == null
1307 if (RootContext.Tree.Types.NamespaceEntry != null)
1308 throw new InternalErrorException (Location + " non-null NamespaceEntry");
1310 RootContext.Tree.Types.NamespaceEntry = ns;
1315 RootContext.Tree.Types.NamespaceEntry = null;
1318 protected override FullNamedExpression ResolveAsTypeStep (Expression expr, EmitContext ec)
1322 return base.ResolveAsTypeStep (expr, ec);
1329 protected override ConstructorInfo ResolveArguments (EmitContext ec)
1333 return base.ResolveArguments (ec);
1341 public class Attributes {
1342 public ArrayList Attrs;
1344 public Attributes (Attribute a)
1346 Attrs = new ArrayList ();
1350 public Attributes (ArrayList attrs)
1355 public void AddAttributes (ArrayList attrs)
1357 Attrs.AddRange (attrs);
1361 /// Checks whether attribute target is valid for the current element
1363 public bool CheckTargets (Attributable member)
1365 string[] valid_targets = member.ValidAttributeTargets;
1366 foreach (Attribute a in Attrs) {
1367 if (a.ExplicitTarget == null || a.ExplicitTarget == valid_targets [0]) {
1368 a.Target = member.AttributeTargets;
1372 // TODO: we can skip the first item
1373 if (((IList) valid_targets).Contains (a.ExplicitTarget)) {
1374 switch (a.ExplicitTarget) {
1375 case "return": a.Target = AttributeTargets.ReturnValue; continue;
1376 case "param": a.Target = AttributeTargets.Parameter; continue;
1377 case "field": a.Target = AttributeTargets.Field; continue;
1378 case "method": a.Target = AttributeTargets.Method; continue;
1379 case "property": a.Target = AttributeTargets.Property; continue;
1381 throw new InternalErrorException ("Unknown explicit target: " + a.ExplicitTarget);
1384 StringBuilder sb = new StringBuilder ();
1385 foreach (string s in valid_targets) {
1389 sb.Remove (sb.Length - 2, 2);
1390 Report.Error (657, a.Location, "`{0}' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are `{1}'", a.ExplicitTarget, sb.ToString ());
1396 public Attribute Search (Type t, EmitContext ec)
1398 foreach (Attribute a in Attrs) {
1399 if (a.ResolveType (ec) == t)
1406 /// Returns all attributes of type 't'. Use it when attribute is AllowMultiple = true
1408 public Attribute[] SearchMulti (Type t, EmitContext ec)
1410 ArrayList ar = null;
1412 foreach (Attribute a in Attrs) {
1413 if (a.ResolveType (ec) == t) {
1415 ar = new ArrayList ();
1420 return ar == null ? null : ar.ToArray (typeof (Attribute)) as Attribute[];
1423 public void Emit (EmitContext ec, Attributable ias)
1427 ListDictionary ld = new ListDictionary ();
1429 foreach (Attribute a in Attrs)
1430 a.Emit (ec, ias, ld);
1433 public bool Contains (Type t, EmitContext ec)
1435 return Search (t, ec) != null;
1440 /// Helper class for attribute verification routine.
1442 sealed class AttributeTester
1444 static PtrHashtable analyzed_types = new PtrHashtable ();
1445 static PtrHashtable analyzed_types_obsolete = new PtrHashtable ();
1446 static PtrHashtable analyzed_member_obsolete = new PtrHashtable ();
1447 static PtrHashtable analyzed_method_excluded = new PtrHashtable ();
1449 static PtrHashtable fixed_buffer_cache = new PtrHashtable ();
1451 static object TRUE = new object ();
1452 static object FALSE = new object ();
1454 private AttributeTester ()
1458 public enum Result {
1465 /// Returns true if parameters of two compared methods are CLS-Compliant.
1466 /// It tests differing only in ref or out, or in array rank.
1468 public static Result AreOverloadedMethodParamsClsCompliant (Type[] types_a, Type[] types_b)
1470 if (types_a == null || types_b == null)
1473 if (types_a.Length != types_b.Length)
1476 Result result = Result.Ok;
1477 for (int i = 0; i < types_b.Length; ++i) {
1478 Type aType = types_a [i];
1479 Type bType = types_b [i];
1481 if (aType.IsArray && bType.IsArray) {
1482 Type a_el_type = aType.GetElementType ();
1483 Type b_el_type = bType.GetElementType ();
1484 if (aType.GetArrayRank () != bType.GetArrayRank () && a_el_type == b_el_type) {
1485 result = Result.RefOutArrayError;
1489 if (a_el_type.IsArray || b_el_type.IsArray) {
1490 result = Result.ArrayArrayError;
1495 Type aBaseType = aType;
1496 bool is_either_ref_or_out = false;
1498 if (aType.IsByRef || aType.IsPointer) {
1499 aBaseType = aType.GetElementType ();
1500 is_either_ref_or_out = true;
1503 Type bBaseType = bType;
1504 if (bType.IsByRef || bType.IsPointer)
1506 bBaseType = bType.GetElementType ();
1507 is_either_ref_or_out = !is_either_ref_or_out;
1510 if (aBaseType != bBaseType)
1513 if (is_either_ref_or_out)
1514 result = Result.RefOutArrayError;
1520 /// Goes through all parameters and test if they are CLS-Compliant.
1522 public static bool AreParametersCompliant (Parameter[] fixedParameters, Location loc)
1524 if (fixedParameters == null)
1527 foreach (Parameter arg in fixedParameters) {
1528 if (!AttributeTester.IsClsCompliant (arg.ParameterType)) {
1529 Report.Error (3001, loc, "Argument type `{0}' is not CLS-compliant", arg.GetSignatureForError ());
1538 /// This method tests the CLS compliance of external types. It doesn't test type visibility.
1540 public static bool IsClsCompliant (Type type)
1545 object type_compliance = analyzed_types[type];
1546 if (type_compliance != null)
1547 return type_compliance == TRUE;
1549 if (type.IsPointer) {
1550 analyzed_types.Add (type, null);
1555 if (type.IsArray || type.IsByRef) {
1556 result = IsClsCompliant (TypeManager.GetElementType (type));
1558 result = AnalyzeTypeCompliance (type);
1560 analyzed_types.Add (type, result ? TRUE : FALSE);
1565 /// Returns IFixedBuffer implementation if field is fixed buffer else null.
1567 public static IFixedBuffer GetFixedBuffer (FieldInfo fi)
1569 FieldBase fb = TypeManager.GetField (fi);
1571 return fb as IFixedBuffer;
1574 object o = fixed_buffer_cache [fi];
1576 if (System.Attribute.GetCustomAttribute (fi, TypeManager.fixed_buffer_attr_type) == null) {
1577 fixed_buffer_cache.Add (fi, FALSE);
1581 IFixedBuffer iff = new FixedFieldExternal (fi);
1582 fixed_buffer_cache.Add (fi, iff);
1589 return (IFixedBuffer)o;
1592 public static void VerifyModulesClsCompliance ()
1594 Module[] modules = TypeManager.Modules;
1595 if (modules == null)
1598 // The first module is generated assembly
1599 for (int i = 1; i < modules.Length; ++i) {
1600 Module module = modules [i];
1601 if (!IsClsCompliant (module)) {
1602 Report.Error (3013, "Added modules must be marked with the CLSCompliant attribute to match the assembly", module.Name);
1609 /// Tests container name for CLS-Compliant name (differing only in case)
1611 public static void VerifyTopLevelNameClsCompliance ()
1613 Hashtable locase_table = new Hashtable ();
1615 // Convert imported type names to lower case and ignore not cls compliant
1616 foreach (DictionaryEntry de in TypeManager.all_imported_types) {
1617 Type t = (Type)de.Value;
1618 if (!AttributeTester.IsClsCompliant (t))
1621 locase_table.Add (((string)de.Key).ToLower (System.Globalization.CultureInfo.InvariantCulture), t);
1624 foreach (DictionaryEntry de in RootContext.Tree.AllDecls) {
1625 if (!(de.Key is MemberName))
1626 throw new InternalErrorException ("");
1627 DeclSpace decl = (DeclSpace) de.Value;
1628 if (!decl.IsClsComplianceRequired (decl))
1631 string lcase = decl.Name.ToLower (System.Globalization.CultureInfo.InvariantCulture);
1632 if (!locase_table.Contains (lcase)) {
1633 locase_table.Add (lcase, decl);
1637 object conflict = locase_table [lcase];
1638 if (conflict is Type)
1639 Report.SymbolRelatedToPreviousError ((Type)conflict);
1641 Report.SymbolRelatedToPreviousError ((MemberCore)conflict);
1643 Report.Error (3005, decl.Location, "Identifier `{0}' differing only in case is not CLS-compliant", decl.GetSignatureForError ());
1647 static bool IsClsCompliant (ICustomAttributeProvider attribute_provider)
1649 object[] CompliantAttribute = attribute_provider.GetCustomAttributes (TypeManager.cls_compliant_attribute_type, false);
1650 if (CompliantAttribute.Length == 0)
1653 return ((CLSCompliantAttribute)CompliantAttribute[0]).IsCompliant;
1656 static bool AnalyzeTypeCompliance (Type type)
1658 if (type.IsGenericInstance)
1659 type = type.GetGenericTypeDefinition ();
1660 DeclSpace ds = TypeManager.LookupDeclSpace (type);
1662 return ds.IsClsComplianceRequired (ds.Parent);
1664 if (type.IsGenericParameter)
1667 object[] CompliantAttribute = type.GetCustomAttributes (TypeManager.cls_compliant_attribute_type, false);
1668 if (CompliantAttribute.Length == 0)
1669 return IsClsCompliant (type.Assembly);
1671 return ((CLSCompliantAttribute)CompliantAttribute[0]).IsCompliant;
1675 /// Returns instance of ObsoleteAttribute when type is obsolete
1677 public static ObsoleteAttribute GetObsoleteAttribute (Type type)
1679 object type_obsolete = analyzed_types_obsolete [type];
1680 if (type_obsolete == FALSE)
1683 if (type_obsolete != null)
1684 return (ObsoleteAttribute)type_obsolete;
1686 ObsoleteAttribute result = null;
1687 if (type.IsByRef || type.IsArray || type.IsPointer) {
1688 result = GetObsoleteAttribute (TypeManager.GetElementType (type));
1689 } else if (type.IsGenericParameter || type.IsGenericInstance)
1692 DeclSpace type_ds = TypeManager.LookupDeclSpace (type);
1694 // Type is external, we can get attribute directly
1695 if (type_ds == null) {
1696 object[] attribute = type.GetCustomAttributes (TypeManager.obsolete_attribute_type, false);
1697 if (attribute.Length == 1)
1698 result = (ObsoleteAttribute)attribute [0];
1700 result = type_ds.GetObsoleteAttribute (type_ds);
1704 analyzed_types_obsolete.Add (type, result == null ? FALSE : result);
1709 /// Returns instance of ObsoleteAttribute when method is obsolete
1711 public static ObsoleteAttribute GetMethodObsoleteAttribute (MethodBase mb)
1713 IMethodData mc = TypeManager.GetMethod (mb);
1715 return mc.GetObsoleteAttribute ();
1717 // compiler generated methods are not registered by AddMethod
1718 if (mb.DeclaringType is TypeBuilder)
1721 PropertyInfo pi = PropertyExpr.AccessorTable [mb] as PropertyInfo;
1723 return GetMemberObsoleteAttribute (pi);
1725 return GetMemberObsoleteAttribute (mb);
1729 /// Returns instance of ObsoleteAttribute when member is obsolete
1731 public static ObsoleteAttribute GetMemberObsoleteAttribute (MemberInfo mi)
1733 object type_obsolete = analyzed_member_obsolete [mi];
1734 if (type_obsolete == FALSE)
1737 if (type_obsolete != null)
1738 return (ObsoleteAttribute)type_obsolete;
1740 if ((mi.DeclaringType is TypeBuilder) || mi.DeclaringType.IsGenericInstance)
1743 ObsoleteAttribute oa = System.Attribute.GetCustomAttribute (mi, TypeManager.obsolete_attribute_type, false) as ObsoleteAttribute;
1744 analyzed_member_obsolete.Add (mi, oa == null ? FALSE : oa);
1749 /// Common method for Obsolete error/warning reporting.
1751 public static void Report_ObsoleteMessage (ObsoleteAttribute oa, string member, Location loc)
1754 Report.Error (619, loc, "`{0}' is obsolete: `{1}'", member, oa.Message);
1758 if (oa.Message == null) {
1759 Report.Warning (612, loc, "`{0}' is obsolete", member);
1762 if (RootContext.WarningLevel >= 2)
1763 Report.Warning (618, loc, "`{0}' is obsolete: `{1}'", member, oa.Message);
1766 public static bool IsConditionalMethodExcluded (MethodBase mb)
1768 object excluded = analyzed_method_excluded [mb];
1769 if (excluded != null)
1770 return excluded == TRUE ? true : false;
1772 if (mb.Mono_IsInflatedMethod)
1775 ConditionalAttribute[] attrs = mb.GetCustomAttributes (TypeManager.conditional_attribute_type, true) as ConditionalAttribute[];
1776 if (attrs.Length == 0) {
1777 analyzed_method_excluded.Add (mb, FALSE);
1781 foreach (ConditionalAttribute a in attrs) {
1782 if (RootContext.AllDefines.Contains (a.ConditionString)) {
1783 analyzed_method_excluded.Add (mb, FALSE);
1787 analyzed_method_excluded.Add (mb, TRUE);
1792 /// Analyzes class whether it has attribute which has ConditionalAttribute
1793 /// and its condition is not defined.
1795 public static bool IsAttributeExcluded (Type type)
1800 Class class_decl = TypeManager.LookupDeclSpace (type) as Class;
1802 // TODO: add caching
1803 // TODO: merge all Type bases attribute caching to one cache to save memory
1804 if (class_decl == null) {
1805 object[] attributes = type.GetCustomAttributes (TypeManager.conditional_attribute_type, false);
1806 foreach (ConditionalAttribute ca in attributes) {
1807 if (RootContext.AllDefines.Contains (ca.ConditionString))
1810 return attributes.Length > 0;
1813 return class_decl.IsExcluded ();