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);
139 static void Error_TypeParameterInAttribute (Location loc)
142 -202, loc, "Can not use a type parameter in an attribute");
146 /// This is rather hack. We report many emit attribute error with same error to be compatible with
147 /// csc. But because csc has to report them this way because error came from ilasm we needn't.
149 public void Error_AttributeEmitError (string inner)
151 Report.Error (647, Location, "Error during emitting `{0}' attribute. The reason is `{1}'",
152 TypeManager.CSharpName (Type), inner);
155 public void Error_InvalidSecurityParent ()
157 Error_AttributeEmitError ("it is attached to invalid parent");
160 protected virtual FullNamedExpression ResolveAsTypeTerminal (Expression expr, EmitContext ec, bool silent)
162 return expr.ResolveAsTypeTerminal (ec, silent);
165 protected virtual FullNamedExpression ResolveAsTypeStep (Expression expr, EmitContext ec, bool silent)
167 return expr.ResolveAsTypeStep (ec, silent);
170 Type ResolvePossibleAttributeType (EmitContext ec, string name, bool silent, ref bool is_attr)
172 FullNamedExpression fn;
173 if (LeftExpr == null) {
174 fn = ResolveAsTypeTerminal (new SimpleName (name, Location), ec, silent);
176 fn = ResolveAsTypeStep (LeftExpr, ec, silent);
179 fn = new MemberAccess (fn, name, Location).ResolveAsTypeTerminal (ec, silent);
182 TypeExpr te = fn as TypeExpr;
187 if (t.IsSubclassOf (TypeManager.attribute_type)) {
189 } else if (!silent) {
190 Report.SymbolRelatedToPreviousError (t);
191 Report.Error (616, Location, "`{0}': is not an attribute class", TypeManager.CSharpName (t));
197 /// Tries to resolve the type of the attribute. Flags an error if it can't, and complain is true.
199 void ResolveAttributeType (EmitContext ec)
201 bool t1_is_attr = false;
202 Type t1 = ResolvePossibleAttributeType (ec, Identifier, true, ref t1_is_attr);
203 bool t2_is_attr = false;
204 Type t2 = nameEscaped ? null :
205 ResolvePossibleAttributeType (ec, Identifier + "Attribute", true, ref t2_is_attr);
207 if (t1_is_attr && t2_is_attr) {
208 Report.Error (1614, Location, "`{0}' is ambiguous between `{0}' and `{0}Attribute'. " +
209 "Use either `@{0}' or `{0}Attribute'", GetSignatureForError ());
210 resolve_error = true;
223 if (t1 == null && t2 == null)
224 ResolvePossibleAttributeType (ec, Identifier, false, ref t1_is_attr);
226 ResolvePossibleAttributeType (ec, Identifier, false, ref t1_is_attr);
228 ResolvePossibleAttributeType (ec, Identifier + "Attribute", false, ref t2_is_attr);
229 resolve_error = true;
232 public virtual Type ResolveType (EmitContext ec)
234 if (Type == null && !resolve_error)
235 ResolveAttributeType (ec);
239 public string GetSignatureForError ()
241 return LeftExpr == null ? Identifier : LeftExpr.GetSignatureForError () + "." + Identifier;
245 // Given an expression, if the expression is a valid attribute-argument-expression
246 // returns an object that can be used to encode it, or null on failure.
248 public static bool GetAttributeArgumentExpression (Expression e, Location loc, Type arg_type, out object result)
250 Constant constant = e as Constant;
251 if (constant != null) {
252 constant = constant.ToType (arg_type, loc);
253 if (constant == null) {
257 result = constant.GetTypedValue ();
259 } else if (e is TypeOf) {
260 result = ((TypeOf) e).TypeArg;
262 } else if (e is ArrayCreation){
263 result = ((ArrayCreation) e).EncodeAsAttribute ();
266 } else if (e is EmptyCast) {
267 Expression child = ((EmptyCast)e).Child;
268 return GetAttributeArgumentExpression (child, loc, child.Type, out result);
269 } else if (e is As) {
271 return GetAttributeArgumentExpression (as_e.Expr, loc, as_e.ProbeType.Type, out result);
275 Error_AttributeArgumentNotValid (loc);
279 bool IsValidArgumentType (Type t)
282 t = t.GetElementType ();
284 return TypeManager.IsPrimitiveType (t) ||
285 TypeManager.IsEnumType (t) ||
286 t == TypeManager.string_type ||
287 t == TypeManager.object_type ||
288 t == TypeManager.type_type;
291 // Cache for parameter-less attributes
292 static PtrHashtable att_cache = new PtrHashtable ();
294 public CustomAttributeBuilder Resolve (EmitContext ec)
299 resolve_error = true;
302 ResolveAttributeType (ec);
307 if (Type.IsAbstract) {
308 Report.Error (653, Location, "Cannot apply attribute class `{0}' because it is abstract", GetSignatureForError ());
312 ObsoleteAttribute obsolete_attr = AttributeTester.GetObsoleteAttribute (Type);
313 if (obsolete_attr != null) {
314 AttributeTester.Report_ObsoleteMessage (obsolete_attr, TypeManager.CSharpName (Type), Location);
317 if (Arguments == null) {
318 object o = att_cache [Type];
320 resolve_error = false;
321 return (CustomAttributeBuilder)o;
325 ConstructorInfo ctor = ResolveArguments (ec);
327 if (Type is TypeBuilder &&
328 TypeManager.LookupDeclSpace (Type).MemberCache == null)
329 // The attribute type has been DefineType'd, but not Defined. Let's not treat it as an error.
330 // It'll be resolved again when the attached-to entity is emitted.
331 resolve_error = false;
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, member.GetSignatureForError ());
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 // FIXME: Punt the issue for now.
530 if (Type is TypeBuilder)
532 throw new InternalErrorException ("Type " + Type + " doesn't have constructors");
535 MethodBase constructor = Invocation.OverloadResolve (
536 ec, (MethodGroupExpr) mg, pos_args, false, Location);
538 if (constructor == null) {
543 // Here we do the checks which should be done by corlib or by runtime.
544 // However Zoltan doesn't like it and every Mono compiler has to do it again.
546 if (Type == TypeManager.guid_attr_type) {
548 new Guid ((string)pos_values [0]);
550 catch (Exception e) {
551 Error_AttributeEmitError (e.Message);
556 if (Type == TypeManager.methodimpl_attr_type &&
557 pos_values.Length == 1 && ((Argument)pos_args [0]).Type == TypeManager.short_type &&
558 !System.Enum.IsDefined (typeof (MethodImplOptions), pos_values [0])) {
559 Error_AttributeEmitError ("Incorrect argument value.");
564 // Now we perform some checks on the positional args as they
565 // cannot be null for a constructor which expects a parameter
569 ParameterData pd = TypeManager.GetParameterData (constructor);
571 int last_real_param = pd.Count;
573 // When the params is not filled we need to put one
574 if (last_real_param > pos_arg_count) {
575 object [] new_pos_values = new object [pos_arg_count + 1];
576 pos_values.CopyTo (new_pos_values, 0);
577 new_pos_values [pos_arg_count] = new object [] {} ;
578 pos_values = new_pos_values;
583 for (int j = 0; j < pos_arg_count; ++j) {
584 Argument a = (Argument) pos_args [j];
586 if (a.Expr is NullLiteral && pd.ParameterType (j) == TypeManager.object_type) {
587 Error_AttributeArgumentNotValid (Location);
591 object value = pos_values [j];
592 if (value != null && a.Type != value.GetType () && TypeManager.IsPrimitiveType (a.Type)) {
594 pos_values [j] = TypeManager.ChangeType (value, a.Type, out fail);
596 // TODO: Can failed ?
597 throw new NotImplementedException ();
601 if (j < last_real_param)
604 if (j == last_real_param) {
605 object [] array = new object [pos_arg_count - last_real_param];
606 array [0] = pos_values [j];
607 pos_values [j] = array;
611 object [] params_array = (object []) pos_values [last_real_param];
612 params_array [j - last_real_param] = pos_values [j];
615 // Adjust the size of the pos_values if it had params
616 if (last_real_param != pos_arg_count) {
617 object [] new_pos_values = new object [last_real_param + 1];
618 Array.Copy (pos_values, new_pos_values, last_real_param + 1);
619 pos_values = new_pos_values;
622 if (named_arg_count > 0) {
623 prop_info_arr = new PropertyInfo [prop_infos.Count];
624 field_info_arr = new FieldInfo [field_infos.Count];
625 field_values_arr = new object [field_values.Count];
626 prop_values_arr = new object [prop_values.Count];
628 field_infos.CopyTo (field_info_arr, 0);
629 field_values.CopyTo (field_values_arr, 0);
631 prop_values.CopyTo (prop_values_arr, 0);
632 prop_infos.CopyTo (prop_info_arr, 0);
635 return (ConstructorInfo) constructor;
639 /// Get a string containing a list of valid targets for the attribute 'attr'
641 public string GetValidTargets ()
643 StringBuilder sb = new StringBuilder ();
644 AttributeTargets targets = GetAttributeUsage (null).ValidOn;
646 if ((targets & AttributeTargets.Assembly) != 0)
647 sb.Append ("assembly, ");
649 if ((targets & AttributeTargets.Module) != 0)
650 sb.Append ("module, ");
652 if ((targets & AttributeTargets.Class) != 0)
653 sb.Append ("class, ");
655 if ((targets & AttributeTargets.Struct) != 0)
656 sb.Append ("struct, ");
658 if ((targets & AttributeTargets.Enum) != 0)
659 sb.Append ("enum, ");
661 if ((targets & AttributeTargets.Constructor) != 0)
662 sb.Append ("constructor, ");
664 if ((targets & AttributeTargets.Method) != 0)
665 sb.Append ("method, ");
667 if ((targets & AttributeTargets.Property) != 0)
668 sb.Append ("property, indexer, ");
670 if ((targets & AttributeTargets.Field) != 0)
671 sb.Append ("field, ");
673 if ((targets & AttributeTargets.Event) != 0)
674 sb.Append ("event, ");
676 if ((targets & AttributeTargets.Interface) != 0)
677 sb.Append ("interface, ");
679 if ((targets & AttributeTargets.Parameter) != 0)
680 sb.Append ("parameter, ");
682 if ((targets & AttributeTargets.Delegate) != 0)
683 sb.Append ("delegate, ");
685 if ((targets & AttributeTargets.ReturnValue) != 0)
686 sb.Append ("return, ");
688 if ((targets & AttributeTargets.GenericParameter) != 0)
689 sb.Append ("type parameter, ");
690 return sb.Remove (sb.Length - 2, 2).ToString ();
694 /// Returns AttributeUsage attribute for this type
696 AttributeUsageAttribute GetAttributeUsage (EmitContext ec)
698 AttributeUsageAttribute ua = usage_attr_cache [Type] as AttributeUsageAttribute;
702 Class attr_class = TypeManager.LookupClass (Type);
704 if (attr_class == null) {
705 object[] usage_attr = Type.GetCustomAttributes (TypeManager.attribute_usage_type, true);
706 ua = (AttributeUsageAttribute)usage_attr [0];
707 usage_attr_cache.Add (Type, ua);
711 Attribute a = attr_class.OptAttributes == null
713 : attr_class.OptAttributes.Search (TypeManager.attribute_usage_type, attr_class.EmitContext);
716 ? DefaultUsageAttribute
717 : a.GetAttributeUsageAttribute (attr_class.EmitContext);
719 usage_attr_cache.Add (Type, ua);
723 AttributeUsageAttribute GetAttributeUsageAttribute (EmitContext ec)
725 if (pos_values == null)
726 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
727 // But because a lot of attribute class code must be rewritten will be better to wait...
731 return DefaultUsageAttribute;
733 AttributeUsageAttribute usage_attribute = new AttributeUsageAttribute ((AttributeTargets)pos_values [0]);
735 object field = GetPropertyValue ("AllowMultiple");
737 usage_attribute.AllowMultiple = (bool)field;
739 field = GetPropertyValue ("Inherited");
741 usage_attribute.Inherited = (bool)field;
743 return usage_attribute;
747 /// Returns custom name of indexer
749 public string GetIndexerAttributeValue (EmitContext ec)
751 if (pos_values == null)
752 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
753 // But because a lot of attribute class code must be rewritten will be better to wait...
759 return pos_values [0] as string;
763 /// Returns condition of ConditionalAttribute
765 public string GetConditionalAttributeValue (EmitContext ec)
767 if (pos_values == null)
768 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
769 // But because a lot of attribute class code must be rewritten will be better to wait...
775 return (string)pos_values [0];
779 /// Creates the instance of ObsoleteAttribute from this attribute instance
781 public ObsoleteAttribute GetObsoleteAttribute (EmitContext ec)
783 if (pos_values == null)
784 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
785 // But because a lot of attribute class code must be rewritten will be better to wait...
791 if (pos_values == null || pos_values.Length == 0)
792 return new ObsoleteAttribute ();
794 if (pos_values.Length == 1)
795 return new ObsoleteAttribute ((string)pos_values [0]);
797 return new ObsoleteAttribute ((string)pos_values [0], (bool)pos_values [1]);
801 /// Returns value of CLSCompliantAttribute contructor parameter but because the method can be called
802 /// before ApplyAttribute. We need to resolve the arguments.
803 /// This situation occurs when class deps is differs from Emit order.
805 public bool GetClsCompliantAttributeValue (EmitContext ec)
807 if (pos_values == null)
808 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
809 // But because a lot of attribute class code must be rewritten will be better to wait...
815 return (bool)pos_values [0];
819 /// Tests permitted SecurityAction for assembly or other types
821 public bool CheckSecurityActionValidity (bool for_assembly)
823 SecurityAction action = GetSecurityActionValue ();
826 case SecurityAction.Demand:
827 case SecurityAction.Assert:
828 case SecurityAction.Deny:
829 case SecurityAction.PermitOnly:
830 case SecurityAction.LinkDemand:
831 case SecurityAction.InheritanceDemand:
836 case SecurityAction.RequestMinimum:
837 case SecurityAction.RequestOptional:
838 case SecurityAction.RequestRefuse:
844 Error_AttributeEmitError ("SecurityAction is out of range X");
848 Error_AttributeEmitError (String.Concat ("SecurityAction '", action, "' is not valid for this declaration"));
852 System.Security.Permissions.SecurityAction GetSecurityActionValue ()
854 return (SecurityAction)pos_values [0];
858 /// Creates instance of SecurityAttribute class and add result of CreatePermission method to permission table.
860 /// <returns></returns>
861 public void ExtractSecurityPermissionSet (ListDictionary permissions)
863 Type orig_assembly_type = null;
865 if (TypeManager.LookupDeclSpace (Type) != null) {
866 if (!RootContext.StdLib) {
867 orig_assembly_type = Type.GetType (Type.FullName);
869 string orig_version_path = Environment.GetEnvironmentVariable ("__SECURITY_BOOTSTRAP_DB");
870 if (orig_version_path == null) {
871 Error_AttributeEmitError ("security custom attributes can not be referenced from defining assembly");
875 if (orig_sec_assembly == null) {
876 string file = Path.Combine (orig_version_path, Driver.OutputFile);
877 orig_sec_assembly = Assembly.LoadFile (file);
880 orig_assembly_type = orig_sec_assembly.GetType (Type.FullName, true);
881 if (orig_assembly_type == null) {
882 Report.Warning (-112, 1, Location, "Self-referenced security attribute `{0}' " +
883 "was not found in previous version of assembly");
889 SecurityAttribute sa;
890 // For all non-selfreferencing security attributes we can avoid all hacks
891 if (orig_assembly_type == null) {
892 sa = (SecurityAttribute) Activator.CreateInstance (Type, pos_values);
894 if (prop_info_arr != null) {
895 for (int i = 0; i < prop_info_arr.Length; ++i) {
896 PropertyInfo pi = prop_info_arr [i];
897 pi.SetValue (sa, prop_values_arr [i], null);
901 // HACK: All security attributes have same ctor syntax
902 sa = (SecurityAttribute) Activator.CreateInstance (orig_assembly_type, new object[] { GetSecurityActionValue () } );
904 // All types are from newly created assembly but for invocation with old one we need to convert them
905 if (prop_info_arr != null) {
906 for (int i = 0; i < prop_info_arr.Length; ++i) {
907 PropertyInfo emited_pi = prop_info_arr [i];
908 PropertyInfo pi = orig_assembly_type.GetProperty (emited_pi.Name, emited_pi.PropertyType);
910 object old_instance = pi.PropertyType.IsEnum ?
911 System.Enum.ToObject (pi.PropertyType, prop_values_arr [i]) :
914 pi.SetValue (sa, old_instance, null);
920 perm = sa.CreatePermission ();
921 SecurityAction action = GetSecurityActionValue ();
923 // IS is correct because for corlib we are using an instance from old corlib
924 if (!(perm is System.Security.CodeAccessPermission)) {
926 case SecurityAction.Demand:
927 action = (SecurityAction)13;
929 case SecurityAction.LinkDemand:
930 action = (SecurityAction)14;
932 case SecurityAction.InheritanceDemand:
933 action = (SecurityAction)15;
938 PermissionSet ps = (PermissionSet)permissions [action];
940 if (sa is PermissionSetAttribute)
941 ps = new PermissionSet (sa.Unrestricted ? PermissionState.Unrestricted : PermissionState.None);
943 ps = new PermissionSet (PermissionState.None);
945 permissions.Add (action, ps);
946 } else if (!ps.IsUnrestricted () && (sa is PermissionSetAttribute) && sa.Unrestricted) {
947 ps = ps.Union (new PermissionSet (PermissionState.Unrestricted));
948 permissions [action] = ps;
950 ps.AddPermission (perm);
953 object GetValue (object value)
955 if (value is EnumConstant)
956 return ((EnumConstant) value).GetValue ();
961 object GetPropertyValue (string name)
963 if (prop_info_arr == null)
966 for (int i = 0; i < prop_info_arr.Length; ++i) {
967 if (prop_info_arr [i].Name == name)
968 return prop_values_arr [i];
974 object GetFieldValue (string name)
977 if (field_info_arr == null)
980 foreach (FieldInfo fi in field_info_arr) {
982 return GetValue (field_values_arr [i]);
989 // Theoretically, we can get rid of this, since FieldBuilder.SetCustomAttribute()
990 // and ParameterBuilder.SetCustomAttribute() are supposed to handle this attribute.
991 // However, we can't, since it appears that the .NET 1.1 SRE hangs when given a MarshalAsAttribute.
993 public UnmanagedMarshal GetMarshal (Attributable attr)
995 UnmanagedType UnmanagedType;
996 if (!RootContext.StdLib || pos_values [0].GetType () != typeof (UnmanagedType))
997 UnmanagedType = (UnmanagedType) System.Enum.ToObject (typeof (UnmanagedType), pos_values [0]);
999 UnmanagedType = (UnmanagedType) pos_values [0];
1001 object value = GetFieldValue ("SizeParamIndex");
1002 if (value != null && UnmanagedType != UnmanagedType.LPArray) {
1003 Error_AttributeEmitError ("SizeParamIndex field is not valid for the specified unmanaged type");
1007 object o = GetFieldValue ("ArraySubType");
1008 UnmanagedType array_sub_type = o == null ? (UnmanagedType) 0x50 /* NATIVE_MAX */ : (UnmanagedType) o;
1010 switch (UnmanagedType) {
1011 case UnmanagedType.CustomMarshaler: {
1012 MethodInfo define_custom = typeof (UnmanagedMarshal).GetMethod ("DefineCustom",
1013 BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
1014 if (define_custom == null) {
1015 Report.RuntimeMissingSupport (Location, "set marshal info");
1019 object [] args = new object [4];
1020 args [0] = GetFieldValue ("MarshalTypeRef");
1021 args [1] = GetFieldValue ("MarshalCookie");
1022 args [2] = GetFieldValue ("MarshalType");
1023 args [3] = Guid.Empty;
1024 return (UnmanagedMarshal) define_custom.Invoke (null, args);
1026 case UnmanagedType.LPArray: {
1027 object size_const = GetFieldValue ("SizeConst");
1028 object size_param_index = GetFieldValue ("SizeParamIndex");
1030 if ((size_const != null) || (size_param_index != null)) {
1031 MethodInfo define_array = typeof (UnmanagedMarshal).GetMethod ("DefineLPArrayInternal",
1032 BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
1033 if (define_array == null) {
1034 Report.RuntimeMissingSupport (Location, "set marshal info");
1038 object [] args = new object [3];
1039 args [0] = array_sub_type;
1040 args [1] = size_const == null ? -1 : size_const;
1041 args [2] = size_param_index == null ? -1 : size_param_index;
1042 return (UnmanagedMarshal) define_array.Invoke (null, args);
1045 return UnmanagedMarshal.DefineLPArray (array_sub_type);
1047 case UnmanagedType.SafeArray:
1048 return UnmanagedMarshal.DefineSafeArray (array_sub_type);
1050 case UnmanagedType.ByValArray:
1051 FieldMember fm = attr as FieldMember;
1053 Error_AttributeEmitError ("Specified unmanaged type is only valid on fields");
1056 return UnmanagedMarshal.DefineByValArray ((int) GetFieldValue ("SizeConst"));
1058 case UnmanagedType.ByValTStr:
1059 return UnmanagedMarshal.DefineByValTStr ((int) GetFieldValue ("SizeConst"));
1062 return UnmanagedMarshal.DefineUnmanagedMarshal (UnmanagedType);
1066 public CharSet GetCharSetValue ()
1068 return (CharSet)System.Enum.Parse (typeof (CharSet), pos_values [0].ToString ());
1071 public MethodImplOptions GetMethodImplOptions ()
1073 if (pos_values [0].GetType () != typeof (MethodImplOptions))
1074 return (MethodImplOptions)System.Enum.ToObject (typeof (MethodImplOptions), pos_values [0]);
1075 return (MethodImplOptions)pos_values [0];
1078 public LayoutKind GetLayoutKindValue ()
1080 if (!RootContext.StdLib || pos_values [0].GetType () != typeof (LayoutKind))
1081 return (LayoutKind)System.Enum.ToObject (typeof (LayoutKind), pos_values [0]);
1083 return (LayoutKind)pos_values [0];
1087 /// Emit attribute for Attributable symbol
1089 public void Emit (EmitContext ec, Attributable ias, ListDictionary emitted_attr)
1091 CustomAttributeBuilder cb = Resolve (ec);
1095 AttributeUsageAttribute usage_attr = GetAttributeUsage (ec);
1096 if ((usage_attr.ValidOn & Target) == 0) {
1097 Report.Error (592, Location, "Attribute `{0}' is not valid on this declaration type. " +
1098 "It is valid on `{1}' declarations only",
1099 GetSignatureForError (), GetValidTargets ());
1104 ias.ApplyAttributeBuilder (this, cb);
1106 catch (Exception e) {
1107 Error_AttributeEmitError (e.Message);
1111 if (!usage_attr.AllowMultiple) {
1112 ArrayList emitted_targets = (ArrayList)emitted_attr [Type];
1113 if (emitted_targets == null) {
1114 emitted_targets = new ArrayList ();
1115 emitted_attr.Add (Type, emitted_targets);
1116 } else if (emitted_targets.Contains (Target)) {
1117 Report.Error (579, Location, "Duplicate `{0}' attribute", GetSignatureForError ());
1120 emitted_targets.Add (Target);
1123 if (!RootContext.VerifyClsCompliance)
1126 // Here we are testing attribute arguments for array usage (error 3016)
1127 if (ias.IsClsComplianceRequired (ec.DeclSpace)) {
1128 if (Arguments == null)
1131 ArrayList pos_args = (ArrayList) Arguments [0];
1132 if (pos_args != null) {
1133 foreach (Argument arg in pos_args) {
1134 // Type is undefined (was error 246)
1135 if (arg.Type == null)
1138 if (arg.Type.IsArray) {
1139 Report.Error (3016, Location, "Arrays as attribute arguments are not CLS-compliant");
1145 if (Arguments.Count < 2)
1148 ArrayList named_args = (ArrayList) Arguments [1];
1149 foreach (DictionaryEntry de in named_args) {
1150 Argument arg = (Argument) de.Value;
1152 // Type is undefined (was error 246)
1153 if (arg.Type == null)
1156 if (arg.Type.IsArray) {
1157 Report.Error (3016, Location, "Arrays as attribute arguments are not CLS-compliant");
1164 public MethodBuilder DefinePInvokeMethod (EmitContext ec, TypeBuilder builder, string name,
1165 MethodAttributes flags, Type ret_type, Type [] param_types)
1167 if (pos_values == null)
1168 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
1169 // But because a lot of attribute class code must be rewritten will be better to wait...
1175 string dll_name = (string)pos_values [0];
1178 CallingConvention cc = CallingConvention.Winapi;
1179 CharSet charset = CodeGen.Module.DefaultCharSet;
1180 bool preserve_sig = true;
1181 string entry_point = name;
1182 bool best_fit_mapping = false;
1183 bool throw_on_unmappable = false;
1184 bool exact_spelling = false;
1185 bool set_last_error = false;
1187 bool best_fit_mapping_set = false;
1188 bool throw_on_unmappable_set = false;
1189 bool exact_spelling_set = false;
1190 bool set_last_error_set = false;
1192 MethodInfo set_best_fit = null;
1193 MethodInfo set_throw_on = null;
1194 MethodInfo set_exact_spelling = null;
1195 MethodInfo set_set_last_error = null;
1197 if (field_info_arr != null) {
1199 for (int i = 0; i < field_info_arr.Length; i++) {
1200 switch (field_info_arr [i].Name) {
1201 case "BestFitMapping":
1202 best_fit_mapping = (bool) field_values_arr [i];
1203 best_fit_mapping_set = true;
1205 case "CallingConvention":
1206 cc = (CallingConvention) field_values_arr [i];
1209 charset = (CharSet) field_values_arr [i];
1212 entry_point = (string) field_values_arr [i];
1214 case "ExactSpelling":
1215 exact_spelling = (bool) field_values_arr [i];
1216 exact_spelling_set = true;
1219 preserve_sig = (bool) field_values_arr [i];
1221 case "SetLastError":
1222 set_last_error = (bool) field_values_arr [i];
1223 set_last_error_set = true;
1225 case "ThrowOnUnmappableChar":
1226 throw_on_unmappable = (bool) field_values_arr [i];
1227 throw_on_unmappable_set = true;
1230 throw new InternalErrorException (field_info_arr [i].ToString ());
1235 if (throw_on_unmappable_set || best_fit_mapping_set || exact_spelling_set || set_last_error_set) {
1236 set_best_fit = typeof (MethodBuilder).
1237 GetMethod ("set_BestFitMapping", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
1238 set_throw_on = typeof (MethodBuilder).
1239 GetMethod ("set_ThrowOnUnmappableChar", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
1240 set_exact_spelling = typeof (MethodBuilder).
1241 GetMethod ("set_ExactSpelling", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
1242 set_set_last_error = typeof (MethodBuilder).
1243 GetMethod ("set_SetLastError", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
1245 if ((set_best_fit == null) || (set_throw_on == null) ||
1246 (set_exact_spelling == null) || (set_set_last_error == null)) {
1247 Report.Error (-1, Location,
1248 "The ThrowOnUnmappableChar, BestFitMapping, SetLastError, " +
1249 "and ExactSpelling attributes can only be emitted when running on the mono runtime.");
1255 MethodBuilder mb = builder.DefinePInvokeMethod (
1256 name, dll_name, entry_point, flags | MethodAttributes.HideBySig | MethodAttributes.PinvokeImpl,
1257 CallingConventions.Standard, ret_type, param_types, cc, charset);
1260 mb.SetImplementationFlags (MethodImplAttributes.PreserveSig);
1262 if (throw_on_unmappable_set)
1263 set_throw_on.Invoke (mb, 0, null, new object [] { throw_on_unmappable }, null);
1264 if (best_fit_mapping_set)
1265 set_best_fit.Invoke (mb, 0, null, new object [] { best_fit_mapping }, null);
1266 if (exact_spelling_set)
1267 set_exact_spelling.Invoke (mb, 0, null, new object [] { exact_spelling }, null);
1268 if (set_last_error_set)
1269 set_set_last_error.Invoke (mb, 0, null, new object [] { set_last_error }, null);
1273 catch (ArgumentException e) {
1274 Error_AttributeEmitError (e.Message);
1279 private Expression GetValue ()
1281 if ((Arguments == null) || (Arguments.Count < 1))
1283 ArrayList al = (ArrayList) Arguments [0];
1284 if ((al == null) || (al.Count < 1))
1286 Argument arg = (Argument) al [0];
1287 if ((arg == null) || (arg.Expr == null))
1292 public string GetString ()
1294 Expression e = GetValue ();
1295 if (e is StringLiteral)
1296 return (e as StringLiteral).Value;
1300 public bool GetBoolean ()
1302 Expression e = GetValue ();
1303 if (e is BoolLiteral)
1304 return (e as BoolLiteral).Value;
1311 /// For global attributes (assembly, module) we need special handling.
1312 /// Attributes can be located in the several files
1314 public class GlobalAttribute : Attribute
1316 public readonly NamespaceEntry ns;
1318 public GlobalAttribute (TypeContainer container, string target,
1319 Expression left_expr, string identifier, ArrayList args, Location loc, bool nameEscaped):
1320 base (target, left_expr, identifier, args, loc, nameEscaped)
1322 ns = container.NamespaceEntry;
1327 // RootContext.Tree.Types has a single NamespaceEntry which gets overwritten
1328 // each time a new file is parsed. However, we need to use the NamespaceEntry
1329 // in effect where the attribute was used. Since code elsewhere cannot assume
1330 // that the NamespaceEntry is right, just overwrite it.
1332 // Precondition: RootContext.Tree.Types == null
1334 if (RootContext.Tree.Types.NamespaceEntry != null)
1335 throw new InternalErrorException (Location + " non-null NamespaceEntry");
1337 RootContext.Tree.Types.NamespaceEntry = ns;
1342 RootContext.Tree.Types.NamespaceEntry = null;
1345 protected override FullNamedExpression ResolveAsTypeStep (Expression expr, EmitContext ec, bool silent)
1349 return base.ResolveAsTypeStep (expr, ec, silent);
1357 protected override FullNamedExpression ResolveAsTypeTerminal (Expression expr, EmitContext ec, bool silent)
1361 return base.ResolveAsTypeTerminal (expr, ec, silent);
1368 protected override ConstructorInfo ResolveArguments (EmitContext ec)
1372 return base.ResolveArguments (ec);
1380 public class Attributes {
1381 public ArrayList Attrs;
1383 public Attributes (Attribute a)
1385 Attrs = new ArrayList ();
1389 public Attributes (ArrayList attrs)
1394 public void AddAttributes (ArrayList attrs)
1396 Attrs.AddRange (attrs);
1400 /// Checks whether attribute target is valid for the current element
1402 public bool CheckTargets (Attributable member)
1404 string[] valid_targets = member.ValidAttributeTargets;
1405 foreach (Attribute a in Attrs) {
1406 if (a.ExplicitTarget == null || a.ExplicitTarget == valid_targets [0]) {
1407 a.Target = member.AttributeTargets;
1411 // TODO: we can skip the first item
1412 if (((IList) valid_targets).Contains (a.ExplicitTarget)) {
1413 switch (a.ExplicitTarget) {
1414 case "return": a.Target = AttributeTargets.ReturnValue; continue;
1415 case "param": a.Target = AttributeTargets.Parameter; continue;
1416 case "field": a.Target = AttributeTargets.Field; continue;
1417 case "method": a.Target = AttributeTargets.Method; continue;
1418 case "property": a.Target = AttributeTargets.Property; continue;
1420 throw new InternalErrorException ("Unknown explicit target: " + a.ExplicitTarget);
1423 StringBuilder sb = new StringBuilder ();
1424 foreach (string s in valid_targets) {
1428 sb.Remove (sb.Length - 2, 2);
1429 Report.Error (657, a.Location, "`{0}' is not a valid attribute location for this declaration. " +
1430 "Valid attribute locations for this declaration are `{1}'", a.ExplicitTarget, sb.ToString ());
1436 public Attribute Search (Type t, EmitContext ec)
1438 foreach (Attribute a in Attrs) {
1439 if (a.ResolveType (ec) == t)
1446 /// Returns all attributes of type 't'. Use it when attribute is AllowMultiple = true
1448 public Attribute[] SearchMulti (Type t, EmitContext ec)
1450 ArrayList ar = null;
1452 foreach (Attribute a in Attrs) {
1453 if (a.ResolveType (ec) == t) {
1455 ar = new ArrayList ();
1460 return ar == null ? null : ar.ToArray (typeof (Attribute)) as Attribute[];
1463 public void Emit (EmitContext ec, Attributable ias)
1467 ListDictionary ld = new ListDictionary ();
1469 foreach (Attribute a in Attrs)
1470 a.Emit (ec, ias, ld);
1473 public bool Contains (Type t, EmitContext ec)
1475 return Search (t, ec) != null;
1480 /// Helper class for attribute verification routine.
1482 sealed class AttributeTester
1484 static PtrHashtable analyzed_types = new PtrHashtable ();
1485 static PtrHashtable analyzed_types_obsolete = new PtrHashtable ();
1486 static PtrHashtable analyzed_member_obsolete = new PtrHashtable ();
1487 static PtrHashtable analyzed_method_excluded = new PtrHashtable ();
1489 static PtrHashtable fixed_buffer_cache = new PtrHashtable ();
1491 static object TRUE = new object ();
1492 static object FALSE = new object ();
1494 private AttributeTester ()
1498 public enum Result {
1505 /// Returns true if parameters of two compared methods are CLS-Compliant.
1506 /// It tests differing only in ref or out, or in array rank.
1508 public static Result AreOverloadedMethodParamsClsCompliant (Type[] types_a, Type[] types_b)
1510 if (types_a == null || types_b == null)
1513 if (types_a.Length != types_b.Length)
1516 Result result = Result.Ok;
1517 for (int i = 0; i < types_b.Length; ++i) {
1518 Type aType = types_a [i];
1519 Type bType = types_b [i];
1521 if (aType.IsArray && bType.IsArray) {
1522 Type a_el_type = aType.GetElementType ();
1523 Type b_el_type = bType.GetElementType ();
1524 if (aType.GetArrayRank () != bType.GetArrayRank () && a_el_type == b_el_type) {
1525 result = Result.RefOutArrayError;
1529 if (a_el_type.IsArray || b_el_type.IsArray) {
1530 result = Result.ArrayArrayError;
1535 Type aBaseType = aType;
1536 bool is_either_ref_or_out = false;
1538 if (aType.IsByRef || aType.IsPointer) {
1539 aBaseType = aType.GetElementType ();
1540 is_either_ref_or_out = true;
1543 Type bBaseType = bType;
1544 if (bType.IsByRef || bType.IsPointer)
1546 bBaseType = bType.GetElementType ();
1547 is_either_ref_or_out = !is_either_ref_or_out;
1550 if (aBaseType != bBaseType)
1553 if (is_either_ref_or_out)
1554 result = Result.RefOutArrayError;
1560 /// Goes through all parameters and test if they are CLS-Compliant.
1562 public static bool AreParametersCompliant (Parameter[] fixedParameters, Location loc)
1564 if (fixedParameters == null)
1567 foreach (Parameter arg in fixedParameters) {
1568 if (!AttributeTester.IsClsCompliant (arg.ParameterType)) {
1569 Report.Error (3001, loc, "Argument type `{0}' is not CLS-compliant", arg.GetSignatureForError ());
1578 /// This method tests the CLS compliance of external types. It doesn't test type visibility.
1580 public static bool IsClsCompliant (Type type)
1585 object type_compliance = analyzed_types[type];
1586 if (type_compliance != null)
1587 return type_compliance == TRUE;
1589 if (type.IsPointer) {
1590 analyzed_types.Add (type, null);
1595 if (type.IsArray || type.IsByRef) {
1596 result = IsClsCompliant (TypeManager.GetElementType (type));
1598 result = AnalyzeTypeCompliance (type);
1600 analyzed_types.Add (type, result ? TRUE : FALSE);
1605 /// Returns IFixedBuffer implementation if field is fixed buffer else null.
1607 public static IFixedBuffer GetFixedBuffer (FieldInfo fi)
1609 FieldBase fb = TypeManager.GetField (fi);
1611 return fb as IFixedBuffer;
1614 object o = fixed_buffer_cache [fi];
1616 if (System.Attribute.GetCustomAttribute (fi, TypeManager.fixed_buffer_attr_type) == null) {
1617 fixed_buffer_cache.Add (fi, FALSE);
1621 IFixedBuffer iff = new FixedFieldExternal (fi);
1622 fixed_buffer_cache.Add (fi, iff);
1629 return (IFixedBuffer)o;
1632 public static void VerifyModulesClsCompliance ()
1634 Module[] modules = TypeManager.Modules;
1635 if (modules == null)
1638 // The first module is generated assembly
1639 for (int i = 1; i < modules.Length; ++i) {
1640 Module module = modules [i];
1641 if (!IsClsCompliant (module)) {
1642 Report.Error (3013, "Added modules must be marked with the CLSCompliant attribute " +
1643 "to match the assembly", module.Name);
1649 public static Type GetImportedIgnoreCaseClsType (string name)
1651 foreach (Assembly a in TypeManager.GetAssemblies ()) {
1652 Type t = a.GetType (name, false, true);
1656 if (IsClsCompliant (t))
1662 static bool IsClsCompliant (ICustomAttributeProvider attribute_provider)
1664 object[] CompliantAttribute = attribute_provider.GetCustomAttributes (TypeManager.cls_compliant_attribute_type, false);
1665 if (CompliantAttribute.Length == 0)
1668 return ((CLSCompliantAttribute)CompliantAttribute[0]).IsCompliant;
1671 static bool AnalyzeTypeCompliance (Type type)
1673 if (type.IsGenericInstance)
1674 type = type.GetGenericTypeDefinition ();
1675 DeclSpace ds = TypeManager.LookupDeclSpace (type);
1677 return ds.IsClsComplianceRequired (ds);
1679 if (type.IsGenericParameter)
1682 object[] CompliantAttribute = type.GetCustomAttributes (TypeManager.cls_compliant_attribute_type, false);
1683 if (CompliantAttribute.Length == 0)
1684 return IsClsCompliant (type.Assembly);
1686 return ((CLSCompliantAttribute)CompliantAttribute[0]).IsCompliant;
1690 /// Returns instance of ObsoleteAttribute when type is obsolete
1692 public static ObsoleteAttribute GetObsoleteAttribute (Type type)
1694 object type_obsolete = analyzed_types_obsolete [type];
1695 if (type_obsolete == FALSE)
1698 if (type_obsolete != null)
1699 return (ObsoleteAttribute)type_obsolete;
1701 ObsoleteAttribute result = null;
1702 if (type.IsByRef || type.IsArray || type.IsPointer) {
1703 result = GetObsoleteAttribute (TypeManager.GetElementType (type));
1704 } else if (type.IsGenericParameter || type.IsGenericInstance)
1707 DeclSpace type_ds = TypeManager.LookupDeclSpace (type);
1709 // Type is external, we can get attribute directly
1710 if (type_ds == null) {
1711 object[] attribute = type.GetCustomAttributes (TypeManager.obsolete_attribute_type, false);
1712 if (attribute.Length == 1)
1713 result = (ObsoleteAttribute)attribute [0];
1715 result = type_ds.GetObsoleteAttribute ();
1719 // Cannot use .Add because of corlib bootstrap
1720 analyzed_types_obsolete [type] = result == null ? FALSE : result;
1725 /// Returns instance of ObsoleteAttribute when method is obsolete
1727 public static ObsoleteAttribute GetMethodObsoleteAttribute (MethodBase mb)
1729 IMethodData mc = TypeManager.GetMethod (mb);
1731 return mc.GetObsoleteAttribute ();
1733 // compiler generated methods are not registered by AddMethod
1734 if (mb.DeclaringType is TypeBuilder)
1737 if (mb.IsSpecialName) {
1738 PropertyInfo pi = PropertyExpr.AccessorTable [mb] as PropertyInfo;
1740 // FIXME: This is buggy as properties from this assembly are included as well
1742 //return GetMemberObsoleteAttribute (pi);
1746 return GetMemberObsoleteAttribute (mb);
1750 /// Returns instance of ObsoleteAttribute when member is obsolete
1752 public static ObsoleteAttribute GetMemberObsoleteAttribute (MemberInfo mi)
1754 object type_obsolete = analyzed_member_obsolete [mi];
1755 if (type_obsolete == FALSE)
1758 if (type_obsolete != null)
1759 return (ObsoleteAttribute)type_obsolete;
1761 if ((mi.DeclaringType is TypeBuilder) || mi.DeclaringType.IsGenericInstance)
1764 ObsoleteAttribute oa = System.Attribute.GetCustomAttribute (mi, TypeManager.obsolete_attribute_type, false)
1765 as ObsoleteAttribute;
1766 analyzed_member_obsolete.Add (mi, oa == null ? FALSE : oa);
1771 /// Common method for Obsolete error/warning reporting.
1773 public static void Report_ObsoleteMessage (ObsoleteAttribute oa, string member, Location loc)
1776 Report.Error (619, loc, "`{0}' is obsolete: `{1}'", member, oa.Message);
1780 if (oa.Message == null) {
1781 Report.Warning (612, loc, "`{0}' is obsolete", member);
1784 if (RootContext.WarningLevel >= 2)
1785 Report.Warning (618, loc, "`{0}' is obsolete: `{1}'", member, oa.Message);
1788 public static bool IsConditionalMethodExcluded (MethodBase mb)
1790 object excluded = analyzed_method_excluded [mb];
1791 if (excluded != null)
1792 return excluded == TRUE ? true : false;
1794 if (mb.Mono_IsInflatedMethod)
1797 ConditionalAttribute[] attrs = mb.GetCustomAttributes (TypeManager.conditional_attribute_type, true)
1798 as ConditionalAttribute[];
1799 if (attrs.Length == 0) {
1800 analyzed_method_excluded.Add (mb, FALSE);
1804 foreach (ConditionalAttribute a in attrs) {
1805 if (RootContext.AllDefines.Contains (a.ConditionString)) {
1806 analyzed_method_excluded.Add (mb, FALSE);
1810 analyzed_method_excluded.Add (mb, TRUE);
1815 /// Analyzes class whether it has attribute which has ConditionalAttribute
1816 /// and its condition is not defined.
1818 public static bool IsAttributeExcluded (Type type)
1823 Class class_decl = TypeManager.LookupDeclSpace (type) as Class;
1825 // TODO: add caching
1826 // TODO: merge all Type bases attribute caching to one cache to save memory
1827 if (class_decl == null) {
1828 object[] attributes = type.GetCustomAttributes (TypeManager.conditional_attribute_type, false);
1829 foreach (ConditionalAttribute ca in attributes) {
1830 if (RootContext.AllDefines.Contains (ca.ConditionString))
1833 return attributes.Length > 0;
1836 return class_decl.IsExcluded ();