2 // attribute.cs: Attribute Handler
4 // Author: Ravi Pratap (ravi@ximian.com)
5 // Marek Safar (marek.safar@seznam.cz)
7 // Licensed under the terms of the GNU GPL
9 // (C) 2001 Ximian, Inc (http://www.ximian.com)
14 using System.Diagnostics;
15 using System.Collections;
16 using System.Collections.Specialized;
17 using System.Reflection;
18 using System.Reflection.Emit;
19 using System.Runtime.InteropServices;
20 using System.Runtime.CompilerServices;
21 using System.Security;
22 using System.Security.Permissions;
26 namespace Mono.CSharp {
29 /// Base class for objects that can have Attributes applied to them.
31 public abstract class Attributable {
33 /// Attributes for this type
35 protected Attributes attributes;
37 public Attributable (Attributes attrs)
40 OptAttributes = attrs;
43 public Attributes OptAttributes
51 if (attributes != null) {
52 attributes.AttachTo (this);
58 /// Use member-specific procedure to apply attribute @a in @cb to the entity being built in @builder
60 public abstract void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb);
63 /// Returns one AttributeTarget for this element.
65 public abstract AttributeTargets AttributeTargets { get; }
67 public abstract IResolveContext ResolveContext { get; }
69 public abstract bool IsClsComplianceRequired ();
72 /// Gets list of valid attribute targets for explicit target declaration.
73 /// The first array item is default target. Don't break this rule.
75 public abstract string[] ValidAttributeTargets { get; }
78 public class Attribute {
79 public readonly string ExplicitTarget;
80 public AttributeTargets Target;
82 // TODO: remove this member
83 public readonly string Name;
84 public readonly Expression LeftExpr;
85 public readonly string Identifier;
87 readonly ArrayList PosArguments;
88 readonly ArrayList NamedArguments;
90 public readonly Location Location;
95 readonly bool nameEscaped;
97 // It can contain more onwers when the attribute is applied to multiple fiels.
98 Attributable[] owners;
100 static readonly AttributeUsageAttribute DefaultUsageAttribute = new AttributeUsageAttribute (AttributeTargets.All);
101 static Assembly orig_sec_assembly;
102 public static readonly object[] EmptyObject = new object [0];
104 // non-null if named args present after Resolve () is called
105 PropertyInfo [] prop_info_arr;
106 FieldInfo [] field_info_arr;
107 object [] field_values_arr;
108 object [] prop_values_arr;
109 object [] pos_values;
111 static PtrHashtable usage_attr_cache;
112 // Cache for parameter-less attributes
113 static PtrHashtable att_cache;
115 public Attribute (string target, Expression left_expr, string identifier, object[] args, Location loc, bool nameEscaped)
117 LeftExpr = left_expr;
118 Identifier = identifier;
119 Name = LeftExpr == null ? identifier : LeftExpr + "." + identifier;
121 PosArguments = (ArrayList)args [0];
122 NamedArguments = (ArrayList)args [1];
125 ExplicitTarget = target;
126 this.nameEscaped = nameEscaped;
134 public static void Reset ()
136 usage_attr_cache = new PtrHashtable ();
137 att_cache = new PtrHashtable ();
140 public void AttachTo (Attributable owner)
142 if (this.owners == null) {
143 this.owners = new Attributable[1] { owner };
147 // When the same attribute is attached to multiple fiels
148 // we use this extra_owners as a list of owners. The attribute
149 // then can be removed because will be emitted when first owner
151 Attributable[] new_array = new Attributable [this.owners.Length + 1];
152 owners.CopyTo (new_array, 0);
153 new_array [owners.Length] = owner;
154 this.owners = new_array;
155 owner.OptAttributes = null;
158 void Error_InvalidNamedArgument (string name)
160 Report.Error (617, Location, "`{0}' is not a valid named attribute argument. Named attribute arguments " +
161 "must be fields which are not readonly, static, const or read-write properties which are " +
162 "public and not static",
166 void Error_InvalidNamedAgrumentType (string name)
168 Report.Error (655, Location, "`{0}' is not a valid named attribute argument because it is not a valid " +
169 "attribute parameter type", name);
172 public static void Error_AttributeArgumentNotValid (Location loc)
174 Report.Error (182, loc,
175 "An attribute argument must be a constant expression, typeof " +
176 "expression or array creation expression");
179 static void Error_TypeParameterInAttribute (Location loc)
182 -202, loc, "Can not use a type parameter in an attribute");
185 public void Error_MissingGuidAttribute ()
187 Report.Error (596, Location, "The Guid attribute must be specified with the ComImport attribute");
190 public void Error_MisusedExtensionAttribute ()
192 //Report.Error (1112, Location, "Do not use `{0}' directly. Use parameter modifier `this' instead", GetSignatureForError ());
196 /// This is rather hack. We report many emit attribute error with same error to be compatible with
197 /// csc. But because csc has to report them this way because error came from ilasm we needn't.
199 public void Error_AttributeEmitError (string inner)
201 Report.Error (647, Location, "Error during emitting `{0}' attribute. The reason is `{1}'",
202 TypeManager.CSharpName (Type), inner);
205 public void Error_InvalidSecurityParent ()
207 Error_AttributeEmitError ("it is attached to invalid parent");
216 protected virtual TypeExpr ResolveAsTypeTerminal (Expression expr, IResolveContext ec, bool silent)
218 return expr.ResolveAsTypeTerminal (ec, silent);
221 Type ResolvePossibleAttributeType (string name, bool silent, ref bool is_attr)
223 IResolveContext rc = Owner.ResolveContext;
226 if (LeftExpr == null) {
227 te = ResolveAsTypeTerminal (new SimpleName (name, Location), rc, silent);
229 te = ResolveAsTypeTerminal (new MemberAccess (LeftExpr, name), rc, silent);
236 if (TypeManager.IsSubclassOf (t, TypeManager.attribute_type)) {
238 } else if (!silent) {
239 Report.SymbolRelatedToPreviousError (t);
240 Report.Error (616, Location, "`{0}': is not an attribute class", TypeManager.CSharpName (t));
246 /// Tries to resolve the type of the attribute. Flags an error if it can't, and complain is true.
248 void ResolveAttributeType ()
250 bool t1_is_attr = false;
251 Type t1 = ResolvePossibleAttributeType (Identifier, true, ref t1_is_attr);
253 bool t2_is_attr = false;
254 Type t2 = nameEscaped ? null :
255 ResolvePossibleAttributeType (Identifier + "Attribute", true, ref t2_is_attr);
257 if (t1_is_attr && t2_is_attr) {
258 Report.Error (1614, Location, "`{0}' is ambiguous between `{0}' and `{0}Attribute'. " +
259 "Use either `@{0}' or `{0}Attribute'", GetSignatureForError ());
260 resolve_error = true;
274 if (t1 == null && t2 == null)
275 ResolvePossibleAttributeType (Identifier, false, ref t1_is_attr);
277 ResolvePossibleAttributeType (Identifier, false, ref t1_is_attr);
279 ResolvePossibleAttributeType (Identifier + "Attribute", false, ref t2_is_attr);
281 resolve_error = true;
284 public virtual Type ResolveType ()
286 if (Type == null && !resolve_error)
287 ResolveAttributeType ();
291 public string GetSignatureForError ()
294 return TypeManager.CSharpName (Type);
296 return LeftExpr == null ? Identifier : LeftExpr.GetSignatureForError () + "." + Identifier;
299 bool IsValidArgumentType (Type t)
302 t = t.GetElementType ();
304 return TypeManager.IsPrimitiveType (t) ||
305 TypeManager.IsEnumType (t) ||
306 t == TypeManager.string_type ||
307 t == TypeManager.object_type ||
308 t == TypeManager.type_type;
311 public CustomAttributeBuilder Resolve ()
316 resolve_error = true;
319 ResolveAttributeType ();
324 if (Type.IsAbstract) {
325 Report.Error (653, Location, "Cannot apply attribute class `{0}' because it is abstract", GetSignatureForError ());
329 ObsoleteAttribute obsolete_attr = AttributeTester.GetObsoleteAttribute (Type);
330 if (obsolete_attr != null) {
331 AttributeTester.Report_ObsoleteMessage (obsolete_attr, TypeManager.CSharpName (Type), Location);
334 if (PosArguments == null && NamedArguments == null) {
335 object o = att_cache [Type];
337 resolve_error = false;
338 return (CustomAttributeBuilder)o;
342 Attributable owner = Owner;
343 EmitContext ec = new EmitContext (owner.ResolveContext, owner.ResolveContext.DeclContainer, owner.ResolveContext.DeclContainer,
344 Location, null, null, owner.ResolveContext.DeclContainer.ModFlags, false);
345 ec.IsAnonymousMethodAllowed = false;
347 ConstructorInfo ctor = ResolveConstructor (ec);
349 if (Type is TypeBuilder &&
350 TypeManager.LookupDeclSpace (Type).MemberCache == null)
351 // The attribute type has been DefineType'd, but not Defined. Let's not treat it as an error.
352 // It'll be resolved again when the attached-to entity is emitted.
353 resolve_error = false;
357 CustomAttributeBuilder cb;
360 if (NamedArguments == null) {
361 cb = new CustomAttributeBuilder (ctor, pos_values);
363 if (pos_values.Length == 0)
364 att_cache.Add (Type, cb);
366 resolve_error = false;
370 if (!ResolveNamedArguments (ec)) {
374 cb = new CustomAttributeBuilder (ctor, pos_values,
375 prop_info_arr, prop_values_arr,
376 field_info_arr, field_values_arr);
378 resolve_error = false;
382 Error_AttributeArgumentNotValid (Location);
387 protected virtual ConstructorInfo ResolveConstructor (EmitContext ec)
389 if (PosArguments != null) {
390 for (int i = 0; i < PosArguments.Count; i++) {
391 Argument a = (Argument) PosArguments [i];
393 if (!a.Resolve (ec, Location))
398 Expression mg = Expression.MemberLookup (ec.ContainerType,
399 Type, ".ctor", MemberTypes.Constructor,
400 BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly,
406 MethodBase constructor = ((MethodGroupExpr)mg).OverloadResolve (
407 ec, PosArguments, false, Location);
409 if (constructor == null)
412 ObsoleteAttribute oa = AttributeTester.GetMethodObsoleteAttribute (constructor);
413 if (oa != null && !Owner.ResolveContext.IsInObsoleteScope) {
414 AttributeTester.Report_ObsoleteMessage (oa, mg.GetSignatureForError (), mg.Location);
417 if (PosArguments == null) {
418 pos_values = EmptyObject;
419 return (ConstructorInfo)constructor;
422 ParameterData pd = TypeManager.GetParameterData (constructor);
424 int pos_arg_count = PosArguments.Count;
425 int last_real_param = pd.Count;
427 pos_values = new object [pos_arg_count];
430 // When the params is not filled we need to put one
431 if (last_real_param > pos_arg_count) {
432 object [] new_pos_values = new object [pos_arg_count + 1];
433 pos_values.CopyTo (new_pos_values, 0);
434 new_pos_values [pos_arg_count] = new object [] {} ;
435 pos_values = new_pos_values;
440 for (int j = 0; j < pos_arg_count; ++j) {
441 Argument a = (Argument) PosArguments [j];
443 if (!a.Expr.GetAttributableValue (a.Type, out pos_values [j]))
446 if (j < last_real_param)
449 if (j == last_real_param) {
450 object [] array = new object [pos_arg_count - last_real_param];
451 array [0] = pos_values [j];
452 pos_values [j] = array;
456 object [] params_array = (object []) pos_values [last_real_param];
457 params_array [j - last_real_param] = pos_values [j];
460 // Adjust the size of the pos_values if it had params
461 if (last_real_param != pos_arg_count) {
462 object [] new_pos_values = new object [last_real_param + 1];
463 Array.Copy (pos_values, new_pos_values, last_real_param + 1);
464 pos_values = new_pos_values;
467 // Here we do the checks which should be done by corlib or by runtime.
468 // However Zoltan doesn't like it and every Mono compiler has to do it again.
470 if (Type == TypeManager.guid_attr_type) {
472 new Guid ((string)pos_values [0]);
474 catch (Exception e) {
475 Error_AttributeEmitError (e.Message);
480 if (Type == TypeManager.attribute_usage_type && (int)pos_values [0] == 0) {
481 Report.Error (591, Location, "Invalid value for argument to `System.AttributeUsage' attribute");
485 if (Type == TypeManager.indexer_name_type || Type == TypeManager.conditional_attribute_type) {
486 if (!Tokenizer.IsValidIdentifier ((string)pos_values [0])) {
487 Report.Error (633, ((Argument)PosArguments[0]).Expr.Location,
488 "The argument to the `{0}' attribute must be a valid identifier", GetSignatureForError ());
493 if (Type == TypeManager.methodimpl_attr_type && pos_values.Length == 1 &&
494 pd.ParameterType (0) == TypeManager.short_type &&
495 !System.Enum.IsDefined (typeof (MethodImplOptions), pos_values [0].ToString ())) {
496 Error_AttributeEmitError ("Incorrect argument value.");
500 return (ConstructorInfo)constructor;
503 protected virtual bool ResolveNamedArguments (EmitContext ec)
505 int named_arg_count = NamedArguments.Count;
507 ArrayList field_infos = new ArrayList (named_arg_count);
508 ArrayList prop_infos = new ArrayList (named_arg_count);
509 ArrayList field_values = new ArrayList (named_arg_count);
510 ArrayList prop_values = new ArrayList (named_arg_count);
512 ArrayList seen_names = new ArrayList(named_arg_count);
514 foreach (DictionaryEntry de in NamedArguments) {
515 string member_name = (string) de.Key;
517 if (seen_names.Contains(member_name)) {
518 Report.Error(643, Location, "'" + member_name + "' duplicate named attribute argument");
521 seen_names.Add(member_name);
523 Argument a = (Argument) de.Value;
524 if (!a.Resolve (ec, Location))
527 Expression member = Expression.MemberLookup (
528 ec.ContainerType, Type, member_name,
529 MemberTypes.Field | MemberTypes.Property,
530 BindingFlags.Public | BindingFlags.Instance,
533 if (member == null) {
534 member = Expression.MemberLookup (ec.ContainerType, Type, member_name,
535 MemberTypes.Field | MemberTypes.Property, BindingFlags.NonPublic | BindingFlags.Instance,
538 if (member != null) {
539 Report.SymbolRelatedToPreviousError (member.Type);
540 Expression.ErrorIsInaccesible (Location, member.GetSignatureForError ());
546 Expression.Error_TypeDoesNotContainDefinition (Location, Type, member_name);
550 if (!(member is PropertyExpr || member is FieldExpr)) {
551 Error_InvalidNamedArgument (member_name);
555 if (a.Expr is TypeParameterExpr){
556 Error_TypeParameterInAttribute (Location);
560 ObsoleteAttribute obsolete_attr;
562 if (member is PropertyExpr) {
563 PropertyInfo pi = ((PropertyExpr) member).PropertyInfo;
565 if (!pi.CanWrite || !pi.CanRead) {
566 Report.SymbolRelatedToPreviousError (pi);
567 Error_InvalidNamedArgument (member_name);
571 if (!IsValidArgumentType (pi.PropertyType)) {
572 Report.SymbolRelatedToPreviousError (pi);
573 Error_InvalidNamedAgrumentType (member_name);
578 if (!a.Expr.GetAttributableValue (pi.PropertyType, out value))
581 PropertyBase pb = TypeManager.GetProperty (pi);
583 obsolete_attr = pb.GetObsoleteAttribute ();
585 obsolete_attr = AttributeTester.GetMemberObsoleteAttribute (pi);
587 prop_values.Add (value);
591 FieldInfo fi = ((FieldExpr) member).FieldInfo;
594 Error_InvalidNamedArgument (member_name);
598 if (!IsValidArgumentType (fi.FieldType)) {
599 Report.SymbolRelatedToPreviousError (fi);
600 Error_InvalidNamedAgrumentType (member_name);
605 if (!a.Expr.GetAttributableValue (fi.FieldType, out value))
608 FieldBase fb = TypeManager.GetField (fi);
610 obsolete_attr = fb.GetObsoleteAttribute ();
612 obsolete_attr = AttributeTester.GetMemberObsoleteAttribute (fi);
614 field_values.Add (value);
615 field_infos.Add (fi);
618 if (obsolete_attr != null && !Owner.ResolveContext.IsInObsoleteScope)
619 AttributeTester.Report_ObsoleteMessage (obsolete_attr, member.GetSignatureForError (), member.Location);
622 prop_info_arr = new PropertyInfo [prop_infos.Count];
623 field_info_arr = new FieldInfo [field_infos.Count];
624 field_values_arr = new object [field_values.Count];
625 prop_values_arr = new object [prop_values.Count];
627 field_infos.CopyTo (field_info_arr, 0);
628 field_values.CopyTo (field_values_arr, 0);
630 prop_values.CopyTo (prop_values_arr, 0);
631 prop_infos.CopyTo (prop_info_arr, 0);
637 /// Get a string containing a list of valid targets for the attribute 'attr'
639 public string GetValidTargets ()
641 StringBuilder sb = new StringBuilder ();
642 AttributeTargets targets = GetAttributeUsage ().ValidOn;
644 if ((targets & AttributeTargets.Assembly) != 0)
645 sb.Append ("assembly, ");
647 if ((targets & AttributeTargets.Module) != 0)
648 sb.Append ("module, ");
650 if ((targets & AttributeTargets.Class) != 0)
651 sb.Append ("class, ");
653 if ((targets & AttributeTargets.Struct) != 0)
654 sb.Append ("struct, ");
656 if ((targets & AttributeTargets.Enum) != 0)
657 sb.Append ("enum, ");
659 if ((targets & AttributeTargets.Constructor) != 0)
660 sb.Append ("constructor, ");
662 if ((targets & AttributeTargets.Method) != 0)
663 sb.Append ("method, ");
665 if ((targets & AttributeTargets.Property) != 0)
666 sb.Append ("property, indexer, ");
668 if ((targets & AttributeTargets.Field) != 0)
669 sb.Append ("field, ");
671 if ((targets & AttributeTargets.Event) != 0)
672 sb.Append ("event, ");
674 if ((targets & AttributeTargets.Interface) != 0)
675 sb.Append ("interface, ");
677 if ((targets & AttributeTargets.Parameter) != 0)
678 sb.Append ("parameter, ");
680 if ((targets & AttributeTargets.Delegate) != 0)
681 sb.Append ("delegate, ");
683 if ((targets & AttributeTargets.ReturnValue) != 0)
684 sb.Append ("return, ");
687 if ((targets & AttributeTargets.GenericParameter) != 0)
688 sb.Append ("type parameter, ");
690 return sb.Remove (sb.Length - 2, 2).ToString ();
694 /// Returns AttributeUsage attribute for this type
696 AttributeUsageAttribute GetAttributeUsage ()
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);
716 ? DefaultUsageAttribute
717 : a.GetAttributeUsageAttribute ();
719 usage_attr_cache.Add (Type, ua);
723 AttributeUsageAttribute GetAttributeUsageAttribute ()
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 ()
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 ()
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 ()
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 ()
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];
818 public Type GetCoClassAttributeValue ()
820 if (pos_values == null)
826 return (Type)pos_values [0];
829 public bool CheckTarget ()
831 string[] valid_targets = Owner.ValidAttributeTargets;
832 if (ExplicitTarget == null || ExplicitTarget == valid_targets [0]) {
833 Target = Owner.AttributeTargets;
837 // TODO: we can skip the first item
838 if (((IList) valid_targets).Contains (ExplicitTarget)) {
839 switch (ExplicitTarget) {
840 case "return": Target = AttributeTargets.ReturnValue; return true;
841 case "param": Target = AttributeTargets.Parameter; return true;
842 case "field": Target = AttributeTargets.Field; return true;
843 case "method": Target = AttributeTargets.Method; return true;
844 case "property": Target = AttributeTargets.Property; return true;
846 throw new InternalErrorException ("Unknown explicit target: " + ExplicitTarget);
849 StringBuilder sb = new StringBuilder ();
850 foreach (string s in valid_targets) {
854 sb.Remove (sb.Length - 2, 2);
855 Report.Error (657, Location, "`{0}' is not a valid attribute location for this declaration. " +
856 "Valid attribute locations for this declaration are `{1}'", ExplicitTarget, sb.ToString ());
861 /// Tests permitted SecurityAction for assembly or other types
863 public bool CheckSecurityActionValidity (bool for_assembly)
865 SecurityAction action = GetSecurityActionValue ();
868 case SecurityAction.Demand:
869 case SecurityAction.Assert:
870 case SecurityAction.Deny:
871 case SecurityAction.PermitOnly:
872 case SecurityAction.LinkDemand:
873 case SecurityAction.InheritanceDemand:
878 case SecurityAction.RequestMinimum:
879 case SecurityAction.RequestOptional:
880 case SecurityAction.RequestRefuse:
886 Error_AttributeEmitError ("SecurityAction is out of range");
890 Error_AttributeEmitError (String.Concat ("SecurityAction `", action, "' is not valid for this declaration"));
894 System.Security.Permissions.SecurityAction GetSecurityActionValue ()
896 return (SecurityAction)pos_values [0];
900 /// Creates instance of SecurityAttribute class and add result of CreatePermission method to permission table.
902 /// <returns></returns>
903 public void ExtractSecurityPermissionSet (ListDictionary permissions)
905 Type orig_assembly_type = null;
907 if (TypeManager.LookupDeclSpace (Type) != null) {
908 if (!RootContext.StdLib) {
909 orig_assembly_type = Type.GetType (Type.FullName);
911 string orig_version_path = Environment.GetEnvironmentVariable ("__SECURITY_BOOTSTRAP_DB");
912 if (orig_version_path == null) {
913 Error_AttributeEmitError ("security custom attributes can not be referenced from defining assembly");
917 if (orig_sec_assembly == null) {
918 string file = Path.Combine (orig_version_path, Driver.OutputFile);
919 orig_sec_assembly = Assembly.LoadFile (file);
922 orig_assembly_type = orig_sec_assembly.GetType (Type.FullName, true);
923 if (orig_assembly_type == null) {
924 Report.Warning (-112, 1, Location, "Self-referenced security attribute `{0}' " +
925 "was not found in previous version of assembly");
931 SecurityAttribute sa;
932 // For all non-selfreferencing security attributes we can avoid all hacks
933 if (orig_assembly_type == null) {
934 sa = (SecurityAttribute) Activator.CreateInstance (Type, pos_values);
936 if (prop_info_arr != null) {
937 for (int i = 0; i < prop_info_arr.Length; ++i) {
938 PropertyInfo pi = prop_info_arr [i];
939 pi.SetValue (sa, prop_values_arr [i], null);
943 // HACK: All security attributes have same ctor syntax
944 sa = (SecurityAttribute) Activator.CreateInstance (orig_assembly_type, new object[] { GetSecurityActionValue () } );
946 // All types are from newly created assembly but for invocation with old one we need to convert them
947 if (prop_info_arr != null) {
948 for (int i = 0; i < prop_info_arr.Length; ++i) {
949 PropertyInfo emited_pi = prop_info_arr [i];
950 PropertyInfo pi = orig_assembly_type.GetProperty (emited_pi.Name, emited_pi.PropertyType);
952 object old_instance = pi.PropertyType.IsEnum ?
953 System.Enum.ToObject (pi.PropertyType, prop_values_arr [i]) :
956 pi.SetValue (sa, old_instance, null);
962 perm = sa.CreatePermission ();
963 SecurityAction action = GetSecurityActionValue ();
965 // IS is correct because for corlib we are using an instance from old corlib
966 if (!(perm is System.Security.CodeAccessPermission)) {
968 case SecurityAction.Demand:
969 action = (SecurityAction)13;
971 case SecurityAction.LinkDemand:
972 action = (SecurityAction)14;
974 case SecurityAction.InheritanceDemand:
975 action = (SecurityAction)15;
980 PermissionSet ps = (PermissionSet)permissions [action];
982 if (sa is PermissionSetAttribute)
983 ps = new PermissionSet (sa.Unrestricted ? PermissionState.Unrestricted : PermissionState.None);
985 ps = new PermissionSet (PermissionState.None);
987 permissions.Add (action, ps);
988 } else if (!ps.IsUnrestricted () && (sa is PermissionSetAttribute) && sa.Unrestricted) {
989 ps = ps.Union (new PermissionSet (PermissionState.Unrestricted));
990 permissions [action] = ps;
992 ps.AddPermission (perm);
995 static object GetValue (object value)
997 if (value is EnumConstant)
998 return ((EnumConstant) value).GetValue ();
1003 public object GetPropertyValue (string name)
1005 if (prop_info_arr == null)
1008 for (int i = 0; i < prop_info_arr.Length; ++i) {
1009 if (prop_info_arr [i].Name == name)
1010 return prop_values_arr [i];
1016 object GetFieldValue (string name)
1019 if (field_info_arr == null)
1022 foreach (FieldInfo fi in field_info_arr) {
1023 if (fi.Name == name)
1024 return GetValue (field_values_arr [i]);
1031 // Theoretically, we can get rid of this, since FieldBuilder.SetCustomAttribute()
1032 // and ParameterBuilder.SetCustomAttribute() are supposed to handle this attribute.
1033 // However, we can't, since it appears that the .NET 1.1 SRE hangs when given a MarshalAsAttribute.
1035 public UnmanagedMarshal GetMarshal (Attributable attr)
1037 UnmanagedType UnmanagedType;
1038 if (!RootContext.StdLib || pos_values [0].GetType () != typeof (UnmanagedType))
1039 UnmanagedType = (UnmanagedType) System.Enum.ToObject (typeof (UnmanagedType), pos_values [0]);
1041 UnmanagedType = (UnmanagedType) pos_values [0];
1043 object value = GetFieldValue ("SizeParamIndex");
1044 if (value != null && UnmanagedType != UnmanagedType.LPArray) {
1045 Error_AttributeEmitError ("SizeParamIndex field is not valid for the specified unmanaged type");
1049 object o = GetFieldValue ("ArraySubType");
1050 UnmanagedType array_sub_type = o == null ? (UnmanagedType) 0x50 /* NATIVE_MAX */ : (UnmanagedType) o;
1052 switch (UnmanagedType) {
1053 case UnmanagedType.CustomMarshaler: {
1054 MethodInfo define_custom = typeof (UnmanagedMarshal).GetMethod ("DefineCustom",
1055 BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
1056 if (define_custom == null) {
1057 Report.RuntimeMissingSupport (Location, "set marshal info");
1061 object [] args = new object [4];
1062 args [0] = GetFieldValue ("MarshalTypeRef");
1063 args [1] = GetFieldValue ("MarshalCookie");
1064 args [2] = GetFieldValue ("MarshalType");
1065 args [3] = Guid.Empty;
1066 return (UnmanagedMarshal) define_custom.Invoke (null, args);
1068 case UnmanagedType.LPArray: {
1069 object size_const = GetFieldValue ("SizeConst");
1070 object size_param_index = GetFieldValue ("SizeParamIndex");
1072 if ((size_const != null) || (size_param_index != null)) {
1073 MethodInfo define_array = typeof (UnmanagedMarshal).GetMethod ("DefineLPArrayInternal",
1074 BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
1075 if (define_array == null) {
1076 Report.RuntimeMissingSupport (Location, "set marshal info");
1080 object [] args = new object [3];
1081 args [0] = array_sub_type;
1082 args [1] = size_const == null ? -1 : size_const;
1083 args [2] = size_param_index == null ? -1 : size_param_index;
1084 return (UnmanagedMarshal) define_array.Invoke (null, args);
1087 return UnmanagedMarshal.DefineLPArray (array_sub_type);
1089 case UnmanagedType.SafeArray:
1090 return UnmanagedMarshal.DefineSafeArray (array_sub_type);
1092 case UnmanagedType.ByValArray:
1093 FieldBase fm = attr as FieldBase;
1095 Error_AttributeEmitError ("Specified unmanaged type is only valid on fields");
1098 return UnmanagedMarshal.DefineByValArray ((int) GetFieldValue ("SizeConst"));
1100 case UnmanagedType.ByValTStr:
1101 return UnmanagedMarshal.DefineByValTStr ((int) GetFieldValue ("SizeConst"));
1104 return UnmanagedMarshal.DefineUnmanagedMarshal (UnmanagedType);
1108 public CharSet GetCharSetValue ()
1110 return (CharSet)System.Enum.Parse (typeof (CharSet), pos_values [0].ToString ());
1113 public MethodImplOptions GetMethodImplOptions ()
1115 if (pos_values [0].GetType () != typeof (MethodImplOptions))
1116 return (MethodImplOptions)System.Enum.ToObject (typeof (MethodImplOptions), pos_values [0]);
1117 return (MethodImplOptions)pos_values [0];
1120 public LayoutKind GetLayoutKindValue ()
1122 if (!RootContext.StdLib || pos_values [0].GetType () != typeof (LayoutKind))
1123 return (LayoutKind)System.Enum.ToObject (typeof (LayoutKind), pos_values [0]);
1125 return (LayoutKind)pos_values [0];
1128 public object GetParameterDefaultValue ()
1130 return pos_values [0];
1133 public override bool Equals (object obj)
1135 Attribute a = obj as Attribute;
1139 return Type == a.Type && Target == a.Target;
1142 public override int GetHashCode ()
1144 return base.GetHashCode ();
1148 /// Emit attribute for Attributable symbol
1150 public void Emit (ListDictionary allEmitted)
1152 CustomAttributeBuilder cb = Resolve ();
1156 AttributeUsageAttribute usage_attr = GetAttributeUsage ();
1157 if ((usage_attr.ValidOn & Target) == 0) {
1158 Report.Error (592, Location, "The attribute `{0}' is not valid on this declaration type. " +
1159 "It is valid on `{1}' declarations only",
1160 GetSignatureForError (), GetValidTargets ());
1165 foreach (Attributable owner in owners)
1166 owner.ApplyAttributeBuilder (this, cb);
1168 catch (Exception e) {
1169 Error_AttributeEmitError (e.Message);
1173 if (!usage_attr.AllowMultiple && allEmitted != null) {
1174 if (allEmitted.Contains (this)) {
1175 ArrayList a = allEmitted [this] as ArrayList;
1177 a = new ArrayList (2);
1178 allEmitted [this] = a;
1182 allEmitted.Add (this, null);
1186 if (!RootContext.VerifyClsCompliance)
1189 // Here we are testing attribute arguments for array usage (error 3016)
1190 if (Owner.IsClsComplianceRequired ()) {
1191 if (PosArguments != null) {
1192 foreach (Argument arg in PosArguments) {
1193 // Type is undefined (was error 246)
1194 if (arg.Type == null)
1197 if (arg.Type.IsArray) {
1198 Report.Error (3016, Location, "Arrays as attribute arguments are not CLS-compliant");
1204 if (NamedArguments == null)
1207 foreach (DictionaryEntry de in NamedArguments) {
1208 Argument arg = (Argument) de.Value;
1210 // Type is undefined (was error 246)
1211 if (arg.Type == null)
1214 if (arg.Type.IsArray) {
1215 Report.Error (3016, Location, "Arrays as attribute arguments are not CLS-compliant");
1222 public MethodBuilder DefinePInvokeMethod (TypeBuilder builder, string name,
1223 MethodAttributes flags, IMethodData method, Type [] param_types)
1225 if (pos_values == null)
1226 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
1227 // But because a lot of attribute class code must be rewritten will be better to wait...
1233 string dll_name = (string)pos_values [0];
1236 CallingConvention cc = CallingConvention.Winapi;
1237 CharSet charset = CodeGen.Module.DefaultCharSet;
1238 bool preserve_sig = true;
1239 string entry_point = name;
1240 bool best_fit_mapping = false;
1241 bool throw_on_unmappable = false;
1242 bool exact_spelling = false;
1243 bool set_last_error = false;
1245 bool best_fit_mapping_set = false;
1246 bool throw_on_unmappable_set = false;
1247 bool exact_spelling_set = false;
1248 bool set_last_error_set = false;
1250 MethodInfo set_best_fit = null;
1251 MethodInfo set_throw_on = null;
1252 MethodInfo set_exact_spelling = null;
1253 MethodInfo set_set_last_error = null;
1255 if (field_info_arr != null) {
1257 for (int i = 0; i < field_info_arr.Length; i++) {
1258 switch (field_info_arr [i].Name) {
1259 case "BestFitMapping":
1260 best_fit_mapping = (bool) field_values_arr [i];
1261 best_fit_mapping_set = true;
1263 case "CallingConvention":
1264 cc = (CallingConvention) field_values_arr [i];
1267 charset = (CharSet) field_values_arr [i];
1270 entry_point = (string) field_values_arr [i];
1272 case "ExactSpelling":
1273 exact_spelling = (bool) field_values_arr [i];
1274 exact_spelling_set = true;
1277 preserve_sig = (bool) field_values_arr [i];
1279 case "SetLastError":
1280 set_last_error = (bool) field_values_arr [i];
1281 set_last_error_set = true;
1283 case "ThrowOnUnmappableChar":
1284 throw_on_unmappable = (bool) field_values_arr [i];
1285 throw_on_unmappable_set = true;
1288 throw new InternalErrorException (field_info_arr [i].ToString ());
1293 if (throw_on_unmappable_set || best_fit_mapping_set || exact_spelling_set || set_last_error_set) {
1294 set_best_fit = typeof (MethodBuilder).
1295 GetMethod ("set_BestFitMapping", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
1296 set_throw_on = typeof (MethodBuilder).
1297 GetMethod ("set_ThrowOnUnmappableChar", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
1298 set_exact_spelling = typeof (MethodBuilder).
1299 GetMethod ("set_ExactSpelling", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
1300 set_set_last_error = typeof (MethodBuilder).
1301 GetMethod ("set_SetLastError", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
1303 if ((set_best_fit == null) || (set_throw_on == null) ||
1304 (set_exact_spelling == null) || (set_set_last_error == null)) {
1305 Report.Error (-1, Location,
1306 "The ThrowOnUnmappableChar, BestFitMapping, SetLastError, " +
1307 "and ExactSpelling attributes can only be emitted when running on the mono runtime.");
1313 MethodBuilder mb = builder.DefinePInvokeMethod (
1314 name, dll_name, entry_point, flags | MethodAttributes.HideBySig | MethodAttributes.PinvokeImpl,
1315 method.ParameterInfo.CallingConvention, method.ReturnType, param_types, cc, charset);
1318 mb.SetImplementationFlags (MethodImplAttributes.PreserveSig);
1320 if (throw_on_unmappable_set)
1321 set_throw_on.Invoke (mb, 0, null, new object [] { throw_on_unmappable }, null);
1322 if (best_fit_mapping_set)
1323 set_best_fit.Invoke (mb, 0, null, new object [] { best_fit_mapping }, null);
1324 if (exact_spelling_set)
1325 set_exact_spelling.Invoke (mb, 0, null, new object [] { exact_spelling }, null);
1326 if (set_last_error_set)
1327 set_set_last_error.Invoke (mb, 0, null, new object [] { set_last_error }, null);
1331 catch (ArgumentException e) {
1332 Error_AttributeEmitError (e.Message);
1337 private Expression GetValue ()
1339 if (PosArguments == null || PosArguments.Count < 1)
1342 return ((Argument) PosArguments [0]).Expr;
1345 public string GetString ()
1347 Expression e = GetValue ();
1348 if (e is StringLiteral)
1349 return (e as StringLiteral).Value;
1353 public bool GetBoolean ()
1355 Expression e = GetValue ();
1356 if (e is BoolLiteral)
1357 return (e as BoolLiteral).Value;
1361 public Type GetArgumentType ()
1363 TypeOf e = GetValue () as TypeOf;
1366 return e.TypeArgument;
1372 /// For global attributes (assembly, module) we need special handling.
1373 /// Attributes can be located in the several files
1375 public class GlobalAttribute : Attribute
1377 public readonly NamespaceEntry ns;
1379 public GlobalAttribute (NamespaceEntry ns, string target,
1380 Expression left_expr, string identifier, object[] args, Location loc, bool nameEscaped):
1381 base (target, left_expr, identifier, args, loc, nameEscaped)
1388 // RootContext.ToplevelTypes has a single NamespaceEntry which gets overwritten
1389 // each time a new file is parsed. However, we need to use the NamespaceEntry
1390 // in effect where the attribute was used. Since code elsewhere cannot assume
1391 // that the NamespaceEntry is right, just overwrite it.
1393 // Precondition: RootContext.ToplevelTypes == null
1395 if (RootContext.ToplevelTypes.NamespaceEntry != null)
1396 throw new InternalErrorException (Location + " non-null NamespaceEntry");
1398 RootContext.ToplevelTypes.NamespaceEntry = ns;
1403 RootContext.ToplevelTypes.NamespaceEntry = null;
1406 protected override TypeExpr ResolveAsTypeTerminal (Expression expr, IResolveContext ec, bool silent)
1410 return base.ResolveAsTypeTerminal (expr, ec, silent);
1417 protected override ConstructorInfo ResolveConstructor (EmitContext ec)
1421 return base.ResolveConstructor (ec);
1428 protected override bool ResolveNamedArguments (EmitContext ec)
1432 return base.ResolveNamedArguments (ec);
1440 public class Attributes {
1441 public readonly ArrayList Attrs;
1443 public Attributes (Attribute a)
1445 Attrs = new ArrayList ();
1449 public Attributes (ArrayList attrs)
1454 public void AddAttributes (ArrayList attrs)
1456 Attrs.AddRange (attrs);
1459 public void AttachTo (Attributable attributable)
1461 foreach (Attribute a in Attrs)
1462 a.AttachTo (attributable);
1466 /// Checks whether attribute target is valid for the current element
1468 public bool CheckTargets ()
1470 foreach (Attribute a in Attrs) {
1471 if (!a.CheckTarget ())
1477 public Attribute Search (Type t)
1479 foreach (Attribute a in Attrs) {
1480 if (a.ResolveType () == t)
1487 /// Returns all attributes of type 't'. Use it when attribute is AllowMultiple = true
1489 public Attribute[] SearchMulti (Type t)
1491 ArrayList ar = null;
1493 foreach (Attribute a in Attrs) {
1494 if (a.ResolveType () == t) {
1496 ar = new ArrayList ();
1501 return ar == null ? null : ar.ToArray (typeof (Attribute)) as Attribute[];
1508 ListDictionary ld = Attrs.Count > 1 ? new ListDictionary () : null;
1510 foreach (Attribute a in Attrs)
1513 if (ld == null || ld.Count == 0)
1516 foreach (DictionaryEntry d in ld) {
1517 if (d.Value == null)
1520 foreach (Attribute collision in (ArrayList)d.Value)
1521 Report.SymbolRelatedToPreviousError (collision.Location, "");
1523 Attribute a = (Attribute)d.Key;
1524 Report.Error (579, a.Location, "The attribute `{0}' cannot be applied multiple times", a.GetSignatureForError ());
1528 public bool Contains (Type t)
1530 return Search (t) != null;
1535 /// Helper class for attribute verification routine.
1537 sealed class AttributeTester
1539 static PtrHashtable analyzed_types;
1540 static PtrHashtable analyzed_types_obsolete;
1541 static PtrHashtable analyzed_member_obsolete;
1542 static PtrHashtable analyzed_method_excluded;
1545 static PtrHashtable fixed_buffer_cache;
1548 static object TRUE = new object ();
1549 static object FALSE = new object ();
1551 static AttributeTester ()
1556 private AttributeTester ()
1560 public static void Reset ()
1562 analyzed_types = new PtrHashtable ();
1563 analyzed_types_obsolete = new PtrHashtable ();
1564 analyzed_member_obsolete = new PtrHashtable ();
1565 analyzed_method_excluded = new PtrHashtable ();
1567 fixed_buffer_cache = new PtrHashtable ();
1571 public enum Result {
1578 /// Returns true if parameters of two compared methods are CLS-Compliant.
1579 /// It tests differing only in ref or out, or in array rank.
1581 public static Result AreOverloadedMethodParamsClsCompliant (Type[] types_a, Type[] types_b)
1583 if (types_a == null || types_b == null)
1586 if (types_a.Length != types_b.Length)
1589 Result result = Result.Ok;
1590 for (int i = 0; i < types_b.Length; ++i) {
1591 Type aType = types_a [i];
1592 Type bType = types_b [i];
1594 if (aType.IsArray && bType.IsArray) {
1595 Type a_el_type = aType.GetElementType ();
1596 Type b_el_type = bType.GetElementType ();
1597 if (aType.GetArrayRank () != bType.GetArrayRank () && a_el_type == b_el_type) {
1598 result = Result.RefOutArrayError;
1602 if (a_el_type.IsArray || b_el_type.IsArray) {
1603 result = Result.ArrayArrayError;
1608 Type aBaseType = aType;
1609 bool is_either_ref_or_out = false;
1611 if (aType.IsByRef || aType.IsPointer) {
1612 aBaseType = aType.GetElementType ();
1613 is_either_ref_or_out = true;
1616 Type bBaseType = bType;
1617 if (bType.IsByRef || bType.IsPointer)
1619 bBaseType = bType.GetElementType ();
1620 is_either_ref_or_out = !is_either_ref_or_out;
1623 if (aBaseType != bBaseType)
1626 if (is_either_ref_or_out)
1627 result = Result.RefOutArrayError;
1633 /// This method tests the CLS compliance of external types. It doesn't test type visibility.
1635 public static bool IsClsCompliant (Type type)
1640 object type_compliance = analyzed_types[type];
1641 if (type_compliance != null)
1642 return type_compliance == TRUE;
1644 if (type.IsPointer) {
1645 analyzed_types.Add (type, null);
1650 if (type.IsArray || type.IsByRef) {
1651 result = IsClsCompliant (TypeManager.GetElementType (type));
1653 result = AnalyzeTypeCompliance (type);
1655 analyzed_types.Add (type, result ? TRUE : FALSE);
1660 /// Returns IFixedBuffer implementation if field is fixed buffer else null.
1662 public static IFixedBuffer GetFixedBuffer (FieldInfo fi)
1664 // Fixed buffer helper type is generated as value type
1665 if (!fi.FieldType.IsValueType)
1668 FieldBase fb = TypeManager.GetField (fi);
1670 return fb as IFixedBuffer;
1674 object o = fixed_buffer_cache [fi];
1676 if (System.Attribute.GetCustomAttribute (fi, TypeManager.fixed_buffer_attr_type) == null) {
1677 fixed_buffer_cache.Add (fi, FALSE);
1681 IFixedBuffer iff = new FixedFieldExternal (fi);
1682 fixed_buffer_cache.Add (fi, iff);
1689 return (IFixedBuffer)o;
1695 public static void VerifyModulesClsCompliance ()
1697 Module[] modules = RootNamespace.Global.Modules;
1698 if (modules == null)
1701 // The first module is generated assembly
1702 for (int i = 1; i < modules.Length; ++i) {
1703 Module module = modules [i];
1704 if (!IsClsCompliant (module)) {
1705 Report.Error (3013, "Added modules must be marked with the CLSCompliant attribute " +
1706 "to match the assembly", module.Name);
1712 public static Type GetImportedIgnoreCaseClsType (string name)
1714 foreach (Assembly a in RootNamespace.Global.Assemblies) {
1715 Type t = a.GetType (name, false, true);
1719 if (IsClsCompliant (t))
1725 static bool IsClsCompliant (ICustomAttributeProvider attribute_provider)
1727 object[] CompliantAttribute = attribute_provider.GetCustomAttributes (TypeManager.cls_compliant_attribute_type, false);
1728 if (CompliantAttribute.Length == 0)
1731 return ((CLSCompliantAttribute)CompliantAttribute[0]).IsCompliant;
1734 static bool AnalyzeTypeCompliance (Type type)
1736 type = TypeManager.DropGenericTypeArguments (type);
1737 DeclSpace ds = TypeManager.LookupDeclSpace (type);
1739 return ds.IsClsComplianceRequired ();
1742 if (TypeManager.IsGenericParameter (type))
1745 object[] CompliantAttribute = type.GetCustomAttributes (TypeManager.cls_compliant_attribute_type, false);
1746 if (CompliantAttribute.Length == 0)
1747 return IsClsCompliant (type.Assembly);
1749 return ((CLSCompliantAttribute)CompliantAttribute[0]).IsCompliant;
1752 // Registers the core type as we assume that they will never be obsolete which
1753 // makes things easier for bootstrap and faster (we don't need to query Obsolete attribute).
1754 public static void RegisterNonObsoleteType (Type type)
1756 analyzed_types_obsolete [type] = FALSE;
1760 /// Returns instance of ObsoleteAttribute when type is obsolete
1762 public static ObsoleteAttribute GetObsoleteAttribute (Type type)
1764 object type_obsolete = analyzed_types_obsolete [type];
1765 if (type_obsolete == FALSE)
1768 if (type_obsolete != null)
1769 return (ObsoleteAttribute)type_obsolete;
1771 ObsoleteAttribute result = null;
1772 if (TypeManager.HasElementType (type)) {
1773 result = GetObsoleteAttribute (TypeManager.GetElementType (type));
1774 } else if (TypeManager.IsGenericParameter (type) || TypeManager.IsGenericType (type))
1777 DeclSpace type_ds = TypeManager.LookupDeclSpace (type);
1779 // Type is external, we can get attribute directly
1780 if (type_ds == null) {
1781 object[] attribute = type.GetCustomAttributes (TypeManager.obsolete_attribute_type, false);
1782 if (attribute.Length == 1)
1783 result = (ObsoleteAttribute)attribute [0];
1785 result = type_ds.GetObsoleteAttribute ();
1789 // Cannot use .Add because of corlib bootstrap
1790 analyzed_types_obsolete [type] = result == null ? FALSE : result;
1795 /// Returns instance of ObsoleteAttribute when method is obsolete
1797 public static ObsoleteAttribute GetMethodObsoleteAttribute (MethodBase mb)
1799 IMethodData mc = TypeManager.GetMethod (mb);
1801 return mc.GetObsoleteAttribute ();
1803 // compiler generated methods are not registered by AddMethod
1804 if (mb.DeclaringType is TypeBuilder)
1807 MemberInfo mi = TypeManager.GetPropertyFromAccessor (mb);
1809 return GetMemberObsoleteAttribute (mi);
1811 mi = TypeManager.GetEventFromAccessor (mb);
1813 return GetMemberObsoleteAttribute (mi);
1815 return GetMemberObsoleteAttribute (mb);
1819 /// Returns instance of ObsoleteAttribute when member is obsolete
1821 public static ObsoleteAttribute GetMemberObsoleteAttribute (MemberInfo mi)
1823 object type_obsolete = analyzed_member_obsolete [mi];
1824 if (type_obsolete == FALSE)
1827 if (type_obsolete != null)
1828 return (ObsoleteAttribute)type_obsolete;
1830 if ((mi.DeclaringType is TypeBuilder) || TypeManager.IsGenericType (mi.DeclaringType))
1833 ObsoleteAttribute oa = System.Attribute.GetCustomAttribute (mi, TypeManager.obsolete_attribute_type, false)
1834 as ObsoleteAttribute;
1835 analyzed_member_obsolete.Add (mi, oa == null ? FALSE : oa);
1840 /// Common method for Obsolete error/warning reporting.
1842 public static void Report_ObsoleteMessage (ObsoleteAttribute oa, string member, Location loc)
1845 Report.Error (619, loc, "`{0}' is obsolete: `{1}'", member, oa.Message);
1849 if (oa.Message == null) {
1850 Report.Warning (612, 1, loc, "`{0}' is obsolete", member);
1853 Report.Warning (618, 2, loc, "`{0}' is obsolete: `{1}'", member, oa.Message);
1856 public static bool IsConditionalMethodExcluded (MethodBase mb)
1858 mb = TypeManager.DropGenericMethodArguments (mb);
1859 if ((mb is MethodBuilder) || (mb is ConstructorBuilder))
1862 object excluded = analyzed_method_excluded [mb];
1863 if (excluded != null)
1864 return excluded == TRUE ? true : false;
1866 ConditionalAttribute[] attrs = mb.GetCustomAttributes (TypeManager.conditional_attribute_type, true)
1867 as ConditionalAttribute[];
1868 if (attrs.Length == 0) {
1869 analyzed_method_excluded.Add (mb, FALSE);
1873 foreach (ConditionalAttribute a in attrs) {
1874 if (RootContext.AllDefines.Contains (a.ConditionString)) {
1875 analyzed_method_excluded.Add (mb, FALSE);
1879 analyzed_method_excluded.Add (mb, TRUE);
1884 /// Analyzes class whether it has attribute which has ConditionalAttribute
1885 /// and its condition is not defined.
1887 public static bool IsAttributeExcluded (Type type)
1892 Class class_decl = TypeManager.LookupDeclSpace (type) as Class;
1894 // TODO: add caching
1895 // TODO: merge all Type bases attribute caching to one cache to save memory
1896 if (class_decl == null) {
1897 object[] attributes = type.GetCustomAttributes (TypeManager.conditional_attribute_type, false);
1898 foreach (ConditionalAttribute ca in attributes) {
1899 if (RootContext.AllDefines.Contains (ca.ConditionString))
1902 return attributes.Length > 0;
1905 return class_decl.IsExcluded ();
1908 public static Type GetCoClassAttribute (Type type)
1910 TypeContainer tc = TypeManager.LookupInterface (type);
1912 object[] o = type.GetCustomAttributes (TypeManager.coclass_attr_type, false);
1915 return ((System.Runtime.InteropServices.CoClassAttribute)o[0]).CoClass;
1918 if (tc.OptAttributes == null)
1921 Attribute a = tc.OptAttributes.Search (TypeManager.coclass_attr_type);
1925 return a.GetCoClassAttributeValue ();