2 // attribute.cs: Attribute Handler
4 // Author: Ravi Pratap (ravi@ximian.com)
5 // Marek Safar (marek.safar@seznam.cz)
7 // Dual licensed under the terms of the MIT X11 or GNU GPL
9 // Copyright 2001-2003 Ximian, Inc (http://www.ximian.com)
10 // Copyright 2003-2008 Novell, Inc.
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, PredefinedAttributes pa);
63 /// Returns one AttributeTarget for this element.
65 public abstract AttributeTargets AttributeTargets { get; }
67 public abstract IResolveContext ResolveContext { get; }
69 public abstract bool IsClsComplianceRequired ();
72 /// Gets list of valid attribute targets for explicit target declaration.
73 /// The first array item is default target. Don't break this rule.
75 public abstract string[] ValidAttributeTargets { get; }
78 public class Attribute : Expression
81 // Wraps owner resolve context, the owner is an attribute
82 // parent and the rest is exactly same
84 struct AttributeResolveContext : IResolveContext
86 readonly IResolveContext rc;
88 public AttributeResolveContext (IResolveContext rc)
93 #region IResolveContext Members
95 public DeclSpace DeclContainer {
97 DeclSpace ds = rc as DeclSpace;
99 return rc.DeclContainer;
105 public bool IsInObsoleteScope {
106 get { return rc.IsInObsoleteScope; }
109 public bool IsInUnsafeScope {
110 get { return rc.IsInUnsafeScope; }
113 public DeclSpace GenericDeclContainer {
114 get { return rc.GenericDeclContainer; }
120 public readonly string ExplicitTarget;
121 public AttributeTargets Target;
123 // TODO: remove this member
124 public readonly string Name;
125 public readonly Expression LeftExpr;
126 public readonly string Identifier;
128 ArrayList PosArguments;
129 ArrayList NamedArguments;
132 readonly bool nameEscaped;
134 // It can contain more onwers when the attribute is applied to multiple fiels.
135 protected Attributable[] owners;
137 static readonly AttributeUsageAttribute DefaultUsageAttribute = new AttributeUsageAttribute (AttributeTargets.All);
138 static Assembly orig_sec_assembly;
139 public static readonly object[] EmptyObject = new object [0];
141 // non-null if named args present after Resolve () is called
142 PropertyInfo [] prop_info_arr;
143 FieldInfo [] field_info_arr;
144 object [] field_values_arr;
145 object [] prop_values_arr;
146 object [] pos_values;
148 static PtrHashtable usage_attr_cache;
149 // Cache for parameter-less attributes
150 static PtrHashtable att_cache;
152 public Attribute (string target, Expression left_expr, string identifier, object[] args, Location loc, bool nameEscaped)
154 LeftExpr = left_expr;
155 Identifier = identifier;
156 Name = LeftExpr == null ? identifier : LeftExpr + "." + identifier;
158 PosArguments = (ArrayList)args [0];
159 NamedArguments = (ArrayList)args [1];
162 ExplicitTarget = target;
163 this.nameEscaped = nameEscaped;
166 public Attribute Clone ()
168 Attribute a = new Attribute (ExplicitTarget, LeftExpr, Identifier, null, loc, nameEscaped);
169 a.PosArguments = PosArguments;
170 a.NamedArguments = NamedArguments;
179 public static void Reset ()
181 usage_attr_cache = new PtrHashtable ();
182 att_cache = new PtrHashtable ();
185 public virtual void AttachTo (Attributable owner)
187 if (this.owners == null) {
188 this.owners = new Attributable[1] { owner };
192 // When the same attribute is attached to multiple fiels
193 // we use this extra_owners as a list of owners. The attribute
194 // then can be removed because will be emitted when first owner
196 Attributable[] new_array = new Attributable [this.owners.Length + 1];
197 owners.CopyTo (new_array, 0);
198 new_array [owners.Length] = owner;
199 this.owners = new_array;
200 owner.OptAttributes = null;
203 void Error_InvalidNamedArgument (string name)
205 Report.Error (617, Location, "`{0}' is not a valid named attribute argument. Named attribute arguments " +
206 "must be fields which are not readonly, static, const or read-write properties which are " +
207 "public and not static",
211 void Error_InvalidNamedAgrumentType (string name)
213 Report.Error (655, Location, "`{0}' is not a valid named attribute argument because it is not a valid " +
214 "attribute parameter type", name);
217 public static void Error_AttributeArgumentNotValid (Location loc)
219 Report.Error (182, loc,
220 "An attribute argument must be a constant expression, typeof " +
221 "expression or array creation expression");
224 static void Error_TypeParameterInAttribute (Location loc)
227 -202, loc, "Can not use a type parameter in an attribute");
230 public void Error_MissingGuidAttribute ()
232 Report.Error (596, Location, "The Guid attribute must be specified with the ComImport attribute");
235 public void Error_MisusedExtensionAttribute ()
237 Report.Error (1112, Location, "Do not use `{0}' directly. Use parameter modifier `this' instead", GetSignatureForError ());
241 /// This is rather hack. We report many emit attribute error with same error to be compatible with
242 /// csc. But because csc has to report them this way because error came from ilasm we needn't.
244 public void Error_AttributeEmitError (string inner)
246 Report.Error (647, Location, "Error during emitting `{0}' attribute. The reason is `{1}'",
247 TypeManager.CSharpName (Type), inner);
250 public void Error_InvalidSecurityParent ()
252 Error_AttributeEmitError ("it is attached to invalid parent");
261 protected virtual TypeExpr ResolveAsTypeTerminal (Expression expr, IResolveContext ec, bool silent)
263 return expr.ResolveAsTypeTerminal (ec, silent);
266 Type ResolvePossibleAttributeType (string name, bool silent, ref bool is_attr)
268 IResolveContext rc = new AttributeResolveContext (Owner.ResolveContext);
271 if (LeftExpr == null) {
272 te = ResolveAsTypeTerminal (new SimpleName (name, Location), rc, silent);
274 te = ResolveAsTypeTerminal (new MemberAccess (LeftExpr, name), rc, silent);
281 if (TypeManager.IsSubclassOf (t, TypeManager.attribute_type)) {
283 } else if (!silent) {
284 Report.SymbolRelatedToPreviousError (t);
285 Report.Error (616, Location, "`{0}': is not an attribute class", TypeManager.CSharpName (t));
291 /// Tries to resolve the type of the attribute. Flags an error if it can't, and complain is true.
293 void ResolveAttributeType ()
295 bool t1_is_attr = false;
296 Type t1 = ResolvePossibleAttributeType (Identifier, true, ref t1_is_attr);
298 bool t2_is_attr = false;
299 Type t2 = nameEscaped ? null :
300 ResolvePossibleAttributeType (Identifier + "Attribute", true, ref t2_is_attr);
302 if (t1_is_attr && t2_is_attr) {
303 Report.Error (1614, Location, "`{0}' is ambiguous between `{0}' and `{0}Attribute'. " +
304 "Use either `@{0}' or `{0}Attribute'", GetSignatureForError ());
305 resolve_error = true;
319 if (t1 == null && t2 == null)
320 ResolvePossibleAttributeType (Identifier, false, ref t1_is_attr);
322 ResolvePossibleAttributeType (Identifier, false, ref t1_is_attr);
324 ResolvePossibleAttributeType (Identifier + "Attribute", false, ref t2_is_attr);
326 resolve_error = true;
329 public virtual Type ResolveType ()
331 if (Type == null && !resolve_error)
332 ResolveAttributeType ();
336 public override string GetSignatureForError ()
339 return TypeManager.CSharpName (Type);
341 return LeftExpr == null ? Identifier : LeftExpr.GetSignatureForError () + "." + Identifier;
344 public bool HasSecurityAttribute {
346 PredefinedAttribute pa = PredefinedAttributes.Get.Security;
347 return pa.IsDefined && TypeManager.IsSubclassOf (type, pa.Type);
351 public bool IsValidSecurityAttribute ()
353 return HasSecurityAttribute && IsSecurityActionValid (false);
356 static bool IsValidArgumentType (Type t)
359 t = TypeManager.GetElementType (t);
361 return t == TypeManager.string_type ||
362 TypeManager.IsPrimitiveType (t) ||
363 TypeManager.IsEnumType (t) ||
364 t == TypeManager.object_type ||
365 t == TypeManager.type_type;
368 [Conditional ("GMCS_SOURCE")]
369 void ApplyModuleCharSet ()
371 if (Type != PredefinedAttributes.Get.DllImport)
374 if (!RootContext.ToplevelTypes.HasDefaultCharSet)
377 const string CharSetEnumMember = "CharSet";
378 if (NamedArguments == null) {
379 NamedArguments = new ArrayList (1);
381 foreach (DictionaryEntry de in NamedArguments) {
382 if ((string)de.Key == CharSetEnumMember)
387 NamedArguments.Add (new DictionaryEntry (CharSetEnumMember,
388 new Argument (Constant.CreateConstant (typeof (CharSet), RootContext.ToplevelTypes.DefaultCharSet, Location))));
391 public CustomAttributeBuilder Resolve ()
396 resolve_error = true;
399 ResolveAttributeType ();
404 if (Type.IsAbstract) {
405 Report.Error (653, Location, "Cannot apply attribute class `{0}' because it is abstract", GetSignatureForError ());
409 ObsoleteAttribute obsolete_attr = AttributeTester.GetObsoleteAttribute (Type);
410 if (obsolete_attr != null) {
411 AttributeTester.Report_ObsoleteMessage (obsolete_attr, TypeManager.CSharpName (Type), Location);
414 if (PosArguments == null && NamedArguments == null) {
415 object o = att_cache [Type];
417 resolve_error = false;
418 return (CustomAttributeBuilder)o;
422 Attributable owner = Owner;
423 DeclSpace ds = owner.ResolveContext as DeclSpace;
425 ds = owner.ResolveContext.DeclContainer;
427 EmitContext ec = new EmitContext (owner.ResolveContext, ds, ds,
428 Location, null, typeof (Attribute), ds.ModFlags, false);
429 ec.IsAnonymousMethodAllowed = false;
431 ConstructorInfo ctor = ResolveConstructor (ec);
433 if (Type is TypeBuilder &&
434 TypeManager.LookupDeclSpace (Type).MemberCache == null)
435 // The attribute type has been DefineType'd, but not Defined. Let's not treat it as an error.
436 // It'll be resolved again when the attached-to entity is emitted.
437 resolve_error = false;
441 ApplyModuleCharSet ();
443 CustomAttributeBuilder cb;
445 // SRE does not allow private ctor but we want to report all source code errors
449 if (NamedArguments == null) {
450 cb = new CustomAttributeBuilder (ctor, pos_values);
452 if (pos_values.Length == 0)
453 att_cache.Add (Type, cb);
455 resolve_error = false;
459 if (!ResolveNamedArguments (ec)) {
463 cb = new CustomAttributeBuilder (ctor, pos_values,
464 prop_info_arr, prop_values_arr,
465 field_info_arr, field_values_arr);
467 resolve_error = false;
471 Error_AttributeArgumentNotValid (Location);
476 protected virtual ConstructorInfo ResolveConstructor (EmitContext ec)
478 if (PosArguments != null) {
479 for (int i = 0; i < PosArguments.Count; i++) {
480 Argument a = (Argument) PosArguments [i];
482 if (!a.Resolve (ec, Location))
487 MethodGroupExpr mg = MemberLookupFinal (ec, ec.ContainerType,
488 Type, ConstructorInfo.ConstructorName, MemberTypes.Constructor,
489 BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly,
490 Location) as MethodGroupExpr;
493 throw new NotImplementedException ();
495 mg = mg.OverloadResolve (ec, ref PosArguments, false, Location);
499 ConstructorInfo constructor = (ConstructorInfo)mg;
500 if (PosArguments == null) {
501 pos_values = EmptyObject;
505 AParametersCollection pd = TypeManager.GetParameterData (constructor);
507 int pos_arg_count = PosArguments.Count;
508 pos_values = new object [pos_arg_count];
509 for (int j = 0; j < pos_arg_count; ++j) {
510 Argument a = (Argument) PosArguments [j];
512 if (!a.Expr.GetAttributableValue (ec, a.Type, out pos_values [j]))
516 // Here we do the checks which should be done by corlib or by runtime.
517 // However Zoltan doesn't like it and every Mono compiler has to do it again.
518 PredefinedAttributes pa = PredefinedAttributes.Get;
519 if (Type == pa.Guid) {
521 new Guid ((string)pos_values [0]);
523 catch (Exception e) {
524 Error_AttributeEmitError (e.Message);
529 if (Type == pa.AttributeUsage && (int)pos_values [0] == 0) {
530 Report.Error (591, Location, "Invalid value for argument to `System.AttributeUsage' attribute");
534 if (Type == pa.IndexerName || Type == pa.Conditional) {
535 string v = pos_values [0] as string;
536 if (!Tokenizer.IsValidIdentifier (v) || Tokenizer.IsKeyword (v)) {
537 Report.Error (633, ((Argument)PosArguments[0]).Expr.Location,
538 "The argument to the `{0}' attribute must be a valid identifier", GetSignatureForError ());
543 if (Type == pa.MethodImpl && pos_values.Length == 1 &&
544 pd.Types [0] == TypeManager.short_type &&
545 !System.Enum.IsDefined (typeof (MethodImplOptions), pos_values [0].ToString ())) {
546 Error_AttributeEmitError ("Incorrect argument value.");
553 protected virtual bool ResolveNamedArguments (EmitContext ec)
555 int named_arg_count = NamedArguments.Count;
557 ArrayList field_infos = new ArrayList (named_arg_count);
558 ArrayList prop_infos = new ArrayList (named_arg_count);
559 ArrayList field_values = new ArrayList (named_arg_count);
560 ArrayList prop_values = new ArrayList (named_arg_count);
562 ArrayList seen_names = new ArrayList(named_arg_count);
564 foreach (DictionaryEntry de in NamedArguments) {
565 string member_name = (string) de.Key;
567 if (seen_names.Contains(member_name)) {
568 Report.Error(643, Location, "'{0}' duplicate named attribute argument", member_name);
571 seen_names.Add(member_name);
573 Argument a = (Argument) de.Value;
574 if (!a.Resolve (ec, Location))
577 Expression member = Expression.MemberLookup (
578 ec.ContainerType, Type, member_name,
579 MemberTypes.Field | MemberTypes.Property,
580 BindingFlags.Public | BindingFlags.Instance,
583 if (member == null) {
584 member = Expression.MemberLookup (ec.ContainerType, Type, member_name,
585 MemberTypes.Field | MemberTypes.Property, BindingFlags.NonPublic | BindingFlags.Instance,
588 if (member != null) {
589 Report.SymbolRelatedToPreviousError (member.Type);
590 Expression.ErrorIsInaccesible (Location, member.GetSignatureForError ());
596 Expression.Error_TypeDoesNotContainDefinition (Location, Type, member_name);
600 if (!(member is PropertyExpr || member is FieldExpr)) {
601 Error_InvalidNamedArgument (member_name);
605 if (a.Expr is TypeParameterExpr){
606 Error_TypeParameterInAttribute (Location);
610 ObsoleteAttribute obsolete_attr;
612 if (member is PropertyExpr) {
613 PropertyInfo pi = ((PropertyExpr) member).PropertyInfo;
615 if (!pi.CanWrite || !pi.CanRead) {
616 Report.SymbolRelatedToPreviousError (pi);
617 Error_InvalidNamedArgument (member_name);
621 if (!IsValidArgumentType (member.Type)) {
622 Report.SymbolRelatedToPreviousError (pi);
623 Error_InvalidNamedAgrumentType (member_name);
628 if (!a.Expr.GetAttributableValue (ec, member.Type, out value))
631 PropertyBase pb = TypeManager.GetProperty (pi);
633 obsolete_attr = pb.GetObsoleteAttribute ();
635 obsolete_attr = AttributeTester.GetMemberObsoleteAttribute (pi);
637 prop_values.Add (value);
641 FieldInfo fi = ((FieldExpr) member).FieldInfo;
644 Error_InvalidNamedArgument (member_name);
648 if (!IsValidArgumentType (member.Type)) {
649 Report.SymbolRelatedToPreviousError (fi);
650 Error_InvalidNamedAgrumentType (member_name);
655 if (!a.Expr.GetAttributableValue (ec, member.Type, out value))
658 FieldBase fb = TypeManager.GetField (fi);
660 obsolete_attr = fb.GetObsoleteAttribute ();
662 obsolete_attr = AttributeTester.GetMemberObsoleteAttribute (fi);
664 field_values.Add (value);
665 field_infos.Add (fi);
668 if (obsolete_attr != null && !Owner.ResolveContext.IsInObsoleteScope)
669 AttributeTester.Report_ObsoleteMessage (obsolete_attr, member.GetSignatureForError (), member.Location);
672 prop_info_arr = new PropertyInfo [prop_infos.Count];
673 field_info_arr = new FieldInfo [field_infos.Count];
674 field_values_arr = new object [field_values.Count];
675 prop_values_arr = new object [prop_values.Count];
677 field_infos.CopyTo (field_info_arr, 0);
678 field_values.CopyTo (field_values_arr, 0);
680 prop_values.CopyTo (prop_values_arr, 0);
681 prop_infos.CopyTo (prop_info_arr, 0);
687 /// Get a string containing a list of valid targets for the attribute 'attr'
689 public string GetValidTargets ()
691 StringBuilder sb = new StringBuilder ();
692 AttributeTargets targets = GetAttributeUsage (Type).ValidOn;
694 if ((targets & AttributeTargets.Assembly) != 0)
695 sb.Append ("assembly, ");
697 if ((targets & AttributeTargets.Module) != 0)
698 sb.Append ("module, ");
700 if ((targets & AttributeTargets.Class) != 0)
701 sb.Append ("class, ");
703 if ((targets & AttributeTargets.Struct) != 0)
704 sb.Append ("struct, ");
706 if ((targets & AttributeTargets.Enum) != 0)
707 sb.Append ("enum, ");
709 if ((targets & AttributeTargets.Constructor) != 0)
710 sb.Append ("constructor, ");
712 if ((targets & AttributeTargets.Method) != 0)
713 sb.Append ("method, ");
715 if ((targets & AttributeTargets.Property) != 0)
716 sb.Append ("property, indexer, ");
718 if ((targets & AttributeTargets.Field) != 0)
719 sb.Append ("field, ");
721 if ((targets & AttributeTargets.Event) != 0)
722 sb.Append ("event, ");
724 if ((targets & AttributeTargets.Interface) != 0)
725 sb.Append ("interface, ");
727 if ((targets & AttributeTargets.Parameter) != 0)
728 sb.Append ("parameter, ");
730 if ((targets & AttributeTargets.Delegate) != 0)
731 sb.Append ("delegate, ");
733 if ((targets & AttributeTargets.ReturnValue) != 0)
734 sb.Append ("return, ");
737 if ((targets & AttributeTargets.GenericParameter) != 0)
738 sb.Append ("type parameter, ");
740 return sb.Remove (sb.Length - 2, 2).ToString ();
744 /// Returns AttributeUsage attribute based on types hierarchy
746 static AttributeUsageAttribute GetAttributeUsage (Type type)
748 AttributeUsageAttribute ua = usage_attr_cache [type] as AttributeUsageAttribute;
752 Class attr_class = TypeManager.LookupClass (type);
753 PredefinedAttribute pa = PredefinedAttributes.Get.AttributeUsage;
755 if (attr_class == null) {
757 return new AttributeUsageAttribute (0);
759 object[] usage_attr = type.GetCustomAttributes (pa.Type, true);
760 ua = (AttributeUsageAttribute)usage_attr [0];
761 usage_attr_cache.Add (type, ua);
766 if (attr_class.OptAttributes != null)
767 a = attr_class.OptAttributes.Search (pa);
770 if (attr_class.TypeBuilder.BaseType != TypeManager.attribute_type)
771 ua = GetAttributeUsage (attr_class.TypeBuilder.BaseType);
773 ua = DefaultUsageAttribute;
775 ua = a.GetAttributeUsageAttribute ();
778 usage_attr_cache.Add (type, ua);
782 AttributeUsageAttribute GetAttributeUsageAttribute ()
784 if (pos_values == null)
785 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
786 // But because a lot of attribute class code must be rewritten will be better to wait...
790 return DefaultUsageAttribute;
792 AttributeUsageAttribute usage_attribute = new AttributeUsageAttribute ((AttributeTargets)pos_values [0]);
794 object field = GetPropertyValue ("AllowMultiple");
796 usage_attribute.AllowMultiple = (bool)field;
798 field = GetPropertyValue ("Inherited");
800 usage_attribute.Inherited = (bool)field;
802 return usage_attribute;
806 /// Returns custom name of indexer
808 public string GetIndexerAttributeValue ()
810 if (pos_values == null)
811 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
812 // But because a lot of attribute class code must be rewritten will be better to wait...
818 return pos_values [0] as string;
822 /// Returns condition of ConditionalAttribute
824 public string GetConditionalAttributeValue ()
826 if (pos_values == null)
827 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
828 // But because a lot of attribute class code must be rewritten will be better to wait...
834 return (string)pos_values [0];
838 /// Creates the instance of ObsoleteAttribute from this attribute instance
840 public ObsoleteAttribute GetObsoleteAttribute ()
842 if (pos_values == null)
843 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
844 // But because a lot of attribute class code must be rewritten will be better to wait...
850 if (pos_values == null || pos_values.Length == 0)
851 return new ObsoleteAttribute ();
853 if (pos_values.Length == 1)
854 return new ObsoleteAttribute ((string)pos_values [0]);
856 return new ObsoleteAttribute ((string)pos_values [0], (bool)pos_values [1]);
860 /// Returns value of CLSCompliantAttribute contructor parameter but because the method can be called
861 /// before ApplyAttribute. We need to resolve the arguments.
862 /// This situation occurs when class deps is differs from Emit order.
864 public bool GetClsCompliantAttributeValue ()
866 if (pos_values == null)
867 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
868 // But because a lot of attribute class code must be rewritten will be better to wait...
874 return (bool)pos_values [0];
877 public Type GetCoClassAttributeValue ()
879 if (pos_values == null)
885 return (Type)pos_values [0];
888 public bool CheckTarget ()
890 string[] valid_targets = Owner.ValidAttributeTargets;
891 if (ExplicitTarget == null || ExplicitTarget == valid_targets [0]) {
892 Target = Owner.AttributeTargets;
896 // TODO: we can skip the first item
897 if (((IList) valid_targets).Contains (ExplicitTarget)) {
898 switch (ExplicitTarget) {
899 case "return": Target = AttributeTargets.ReturnValue; return true;
900 case "param": Target = AttributeTargets.Parameter; return true;
901 case "field": Target = AttributeTargets.Field; return true;
902 case "method": Target = AttributeTargets.Method; return true;
903 case "property": Target = AttributeTargets.Property; return true;
905 throw new InternalErrorException ("Unknown explicit target: " + ExplicitTarget);
908 StringBuilder sb = new StringBuilder ();
909 foreach (string s in valid_targets) {
913 sb.Remove (sb.Length - 2, 2);
914 Report.Error (657, Location, "`{0}' is not a valid attribute location for this declaration. " +
915 "Valid attribute locations for this declaration are `{1}'", ExplicitTarget, sb.ToString ());
920 /// Tests permitted SecurityAction for assembly or other types
922 protected virtual bool IsSecurityActionValid (bool for_assembly)
924 SecurityAction action = GetSecurityActionValue ();
927 case SecurityAction.Demand:
928 case SecurityAction.Assert:
929 case SecurityAction.Deny:
930 case SecurityAction.PermitOnly:
931 case SecurityAction.LinkDemand:
932 case SecurityAction.InheritanceDemand:
937 case SecurityAction.RequestMinimum:
938 case SecurityAction.RequestOptional:
939 case SecurityAction.RequestRefuse:
945 Error_AttributeEmitError ("SecurityAction is out of range");
949 Error_AttributeEmitError (String.Concat ("SecurityAction `", action, "' is not valid for this declaration"));
953 System.Security.Permissions.SecurityAction GetSecurityActionValue ()
955 return (SecurityAction)pos_values [0];
959 /// Creates instance of SecurityAttribute class and add result of CreatePermission method to permission table.
961 /// <returns></returns>
962 public void ExtractSecurityPermissionSet (ListDictionary permissions)
964 Type orig_assembly_type = null;
966 if (TypeManager.LookupDeclSpace (Type) != null) {
967 if (!RootContext.StdLib) {
968 orig_assembly_type = Type.GetType (Type.FullName);
970 string orig_version_path = Environment.GetEnvironmentVariable ("__SECURITY_BOOTSTRAP_DB");
971 if (orig_version_path == null) {
972 Error_AttributeEmitError ("security custom attributes can not be referenced from defining assembly");
976 if (orig_sec_assembly == null) {
977 string file = Path.Combine (orig_version_path, Driver.OutputFile);
978 orig_sec_assembly = Assembly.LoadFile (file);
981 orig_assembly_type = orig_sec_assembly.GetType (Type.FullName, true);
982 if (orig_assembly_type == null) {
983 Report.Warning (-112, 1, Location, "Self-referenced security attribute `{0}' " +
984 "was not found in previous version of assembly");
990 SecurityAttribute sa;
991 // For all non-selfreferencing security attributes we can avoid all hacks
992 if (orig_assembly_type == null) {
993 sa = (SecurityAttribute) Activator.CreateInstance (Type, pos_values);
995 if (prop_info_arr != null) {
996 for (int i = 0; i < prop_info_arr.Length; ++i) {
997 PropertyInfo pi = prop_info_arr [i];
998 pi.SetValue (sa, prop_values_arr [i], null);
1002 // HACK: All security attributes have same ctor syntax
1003 sa = (SecurityAttribute) Activator.CreateInstance (orig_assembly_type, new object[] { GetSecurityActionValue () } );
1005 // All types are from newly created assembly but for invocation with old one we need to convert them
1006 if (prop_info_arr != null) {
1007 for (int i = 0; i < prop_info_arr.Length; ++i) {
1008 PropertyInfo emited_pi = prop_info_arr [i];
1009 // FIXME: We are missing return type filter
1010 // TODO: pi can be null
1011 PropertyInfo pi = orig_assembly_type.GetProperty (emited_pi.Name);
1013 object old_instance = TypeManager.IsEnumType (pi.PropertyType) ?
1014 System.Enum.ToObject (pi.PropertyType, prop_values_arr [i]) :
1015 prop_values_arr [i];
1017 pi.SetValue (sa, old_instance, null);
1023 perm = sa.CreatePermission ();
1024 SecurityAction action = GetSecurityActionValue ();
1026 // IS is correct because for corlib we are using an instance from old corlib
1027 if (!(perm is System.Security.CodeAccessPermission)) {
1029 case SecurityAction.Demand:
1030 action = (SecurityAction)13;
1032 case SecurityAction.LinkDemand:
1033 action = (SecurityAction)14;
1035 case SecurityAction.InheritanceDemand:
1036 action = (SecurityAction)15;
1041 PermissionSet ps = (PermissionSet)permissions [action];
1043 if (sa is PermissionSetAttribute)
1044 ps = new PermissionSet (sa.Unrestricted ? PermissionState.Unrestricted : PermissionState.None);
1046 ps = new PermissionSet (PermissionState.None);
1048 permissions.Add (action, ps);
1049 } else if (!ps.IsUnrestricted () && (sa is PermissionSetAttribute) && sa.Unrestricted) {
1050 ps = ps.Union (new PermissionSet (PermissionState.Unrestricted));
1051 permissions [action] = ps;
1053 ps.AddPermission (perm);
1056 public object GetPropertyValue (string name)
1058 if (prop_info_arr == null)
1061 for (int i = 0; i < prop_info_arr.Length; ++i) {
1062 if (prop_info_arr [i].Name == name)
1063 return prop_values_arr [i];
1070 // Theoretically, we can get rid of this, since FieldBuilder.SetCustomAttribute()
1071 // and ParameterBuilder.SetCustomAttribute() are supposed to handle this attribute.
1072 // However, we can't, since it appears that the .NET 1.1 SRE hangs when given a MarshalAsAttribute.
1075 public UnmanagedMarshal GetMarshal (Attributable attr)
1077 UnmanagedType UnmanagedType;
1078 if (!RootContext.StdLib || pos_values [0].GetType () != typeof (UnmanagedType))
1079 UnmanagedType = (UnmanagedType) System.Enum.ToObject (typeof (UnmanagedType), pos_values [0]);
1081 UnmanagedType = (UnmanagedType) pos_values [0];
1083 object value = GetFieldValue ("SizeParamIndex");
1084 if (value != null && UnmanagedType != UnmanagedType.LPArray) {
1085 Error_AttributeEmitError ("SizeParamIndex field is not valid for the specified unmanaged type");
1089 object o = GetFieldValue ("ArraySubType");
1090 UnmanagedType array_sub_type = o == null ? (UnmanagedType) 0x50 /* NATIVE_MAX */ : (UnmanagedType) o;
1092 switch (UnmanagedType) {
1093 case UnmanagedType.CustomMarshaler: {
1094 MethodInfo define_custom = typeof (UnmanagedMarshal).GetMethod ("DefineCustom",
1095 BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
1096 if (define_custom == null) {
1097 Report.RuntimeMissingSupport (Location, "set marshal info");
1101 object [] args = new object [4];
1102 args [0] = GetFieldValue ("MarshalTypeRef");
1103 args [1] = GetFieldValue ("MarshalCookie");
1104 args [2] = GetFieldValue ("MarshalType");
1105 args [3] = Guid.Empty;
1106 return (UnmanagedMarshal) define_custom.Invoke (null, args);
1108 case UnmanagedType.LPArray: {
1109 object size_const = GetFieldValue ("SizeConst");
1110 object size_param_index = GetFieldValue ("SizeParamIndex");
1112 if ((size_const != null) || (size_param_index != null)) {
1113 MethodInfo define_array = typeof (UnmanagedMarshal).GetMethod ("DefineLPArrayInternal",
1114 BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
1115 if (define_array == null) {
1116 Report.RuntimeMissingSupport (Location, "set marshal info");
1120 object [] args = new object [3];
1121 args [0] = array_sub_type;
1122 args [1] = size_const == null ? -1 : size_const;
1123 args [2] = size_param_index == null ? -1 : size_param_index;
1124 return (UnmanagedMarshal) define_array.Invoke (null, args);
1127 return UnmanagedMarshal.DefineLPArray (array_sub_type);
1129 case UnmanagedType.SafeArray:
1130 return UnmanagedMarshal.DefineSafeArray (array_sub_type);
1132 case UnmanagedType.ByValArray:
1133 FieldBase fm = attr as FieldBase;
1135 Error_AttributeEmitError ("Specified unmanaged type is only valid on fields");
1138 return UnmanagedMarshal.DefineByValArray ((int) GetFieldValue ("SizeConst"));
1140 case UnmanagedType.ByValTStr:
1141 return UnmanagedMarshal.DefineByValTStr ((int) GetFieldValue ("SizeConst"));
1144 return UnmanagedMarshal.DefineUnmanagedMarshal (UnmanagedType);
1148 object GetFieldValue (string name)
1151 if (field_info_arr == null)
1154 foreach (FieldInfo fi in field_info_arr) {
1155 if (fi.Name == name)
1156 return GetValue (field_values_arr [i]);
1162 static object GetValue (object value)
1164 if (value is EnumConstant)
1165 return ((EnumConstant) value).GetValue ();
1172 public CharSet GetCharSetValue ()
1174 return (CharSet)System.Enum.Parse (typeof (CharSet), pos_values [0].ToString ());
1177 public bool HasField (string fieldName)
1179 if (field_info_arr == null)
1182 foreach (FieldInfo fi in field_info_arr) {
1183 if (fi.Name == fieldName)
1190 public bool IsInternalMethodImplAttribute {
1192 if (Type != PredefinedAttributes.Get.MethodImpl)
1195 MethodImplOptions options;
1196 if (pos_values[0].GetType () != typeof (MethodImplOptions))
1197 options = (MethodImplOptions)System.Enum.ToObject (typeof (MethodImplOptions), pos_values[0]);
1199 options = (MethodImplOptions)pos_values[0];
1201 return (options & MethodImplOptions.InternalCall) != 0;
1205 public LayoutKind GetLayoutKindValue ()
1207 if (!RootContext.StdLib || pos_values [0].GetType () != typeof (LayoutKind))
1208 return (LayoutKind)System.Enum.ToObject (typeof (LayoutKind), pos_values [0]);
1210 return (LayoutKind)pos_values [0];
1213 public object GetParameterDefaultValue ()
1215 return pos_values [0];
1218 public override bool Equals (object obj)
1220 Attribute a = obj as Attribute;
1224 return Type == a.Type && Target == a.Target;
1227 public override int GetHashCode ()
1229 return base.GetHashCode ();
1233 /// Emit attribute for Attributable symbol
1235 public void Emit (ListDictionary allEmitted)
1237 CustomAttributeBuilder cb = Resolve ();
1241 AttributeUsageAttribute usage_attr = GetAttributeUsage (Type);
1242 if ((usage_attr.ValidOn & Target) == 0) {
1243 Report.Error (592, Location, "The attribute `{0}' is not valid on this declaration type. " +
1244 "It is valid on `{1}' declarations only",
1245 GetSignatureForError (), GetValidTargets ());
1250 foreach (Attributable owner in owners)
1251 owner.ApplyAttributeBuilder (this, cb, PredefinedAttributes.Get);
1253 catch (Exception e) {
1254 Error_AttributeEmitError (e.Message);
1258 if (!usage_attr.AllowMultiple && allEmitted != null) {
1259 if (allEmitted.Contains (this)) {
1260 ArrayList a = allEmitted [this] as ArrayList;
1262 a = new ArrayList (2);
1263 allEmitted [this] = a;
1267 allEmitted.Add (this, null);
1271 if (!RootContext.VerifyClsCompliance)
1274 // Here we are testing attribute arguments for array usage (error 3016)
1275 if (Owner.IsClsComplianceRequired ()) {
1276 if (PosArguments != null) {
1277 foreach (Argument arg in PosArguments) {
1278 // Type is undefined (was error 246)
1279 if (arg.Type == null)
1282 if (arg.Type.IsArray) {
1283 Report.Warning (3016, 1, Location, "Arrays as attribute arguments are not CLS-compliant");
1289 if (NamedArguments == null)
1292 foreach (DictionaryEntry de in NamedArguments) {
1293 Argument arg = (Argument) de.Value;
1295 // Type is undefined (was error 246)
1296 if (arg.Type == null)
1299 if (arg.Type.IsArray) {
1300 Report.Warning (3016, 1, Location, "Arrays as attribute arguments are not CLS-compliant");
1307 private Expression GetValue ()
1309 if (PosArguments == null || PosArguments.Count < 1)
1312 return ((Argument) PosArguments [0]).Expr;
1315 public string GetString ()
1317 Expression e = GetValue ();
1318 if (e is StringConstant)
1319 return ((StringConstant)e).Value;
1323 public bool GetBoolean ()
1325 Expression e = GetValue ();
1326 if (e is BoolConstant)
1327 return ((BoolConstant)e).Value;
1331 public Type GetArgumentType ()
1333 TypeOf e = GetValue () as TypeOf;
1336 return e.TypeArgument;
1339 public override Expression CreateExpressionTree (EmitContext ec)
1341 throw new NotSupportedException ("ET");
1344 public override Expression DoResolve (EmitContext ec)
1346 throw new NotImplementedException ();
1349 public override void Emit (EmitContext ec)
1351 throw new NotImplementedException ();
1357 /// For global attributes (assembly, module) we need special handling.
1358 /// Attributes can be located in the several files
1360 public class GlobalAttribute : Attribute
1362 public readonly NamespaceEntry ns;
1364 public GlobalAttribute (NamespaceEntry ns, string target,
1365 Expression left_expr, string identifier, object[] args, Location loc, bool nameEscaped):
1366 base (target, left_expr, identifier, args, loc, nameEscaped)
1369 this.owners = new Attributable[1];
1372 public override void AttachTo (Attributable owner)
1374 if (ExplicitTarget == "assembly") {
1375 owners [0] = CodeGen.Assembly;
1378 if (ExplicitTarget == "module") {
1379 owners [0] = RootContext.ToplevelTypes;
1382 throw new NotImplementedException ("Unknown global explicit target " + ExplicitTarget);
1387 // RootContext.ToplevelTypes has a single NamespaceEntry which gets overwritten
1388 // each time a new file is parsed. However, we need to use the NamespaceEntry
1389 // in effect where the attribute was used. Since code elsewhere cannot assume
1390 // that the NamespaceEntry is right, just overwrite it.
1392 // Precondition: RootContext.ToplevelTypes == null
1394 if (RootContext.ToplevelTypes.NamespaceEntry != null)
1395 throw new InternalErrorException (Location + " non-null NamespaceEntry");
1397 RootContext.ToplevelTypes.NamespaceEntry = ns;
1400 protected override bool IsSecurityActionValid (bool for_assembly)
1402 return base.IsSecurityActionValid (true);
1407 RootContext.ToplevelTypes.NamespaceEntry = null;
1410 protected override TypeExpr ResolveAsTypeTerminal (Expression expr, IResolveContext ec, bool silent)
1414 return base.ResolveAsTypeTerminal (expr, ec, silent);
1421 protected override ConstructorInfo ResolveConstructor (EmitContext ec)
1425 return base.ResolveConstructor (ec);
1432 protected override bool ResolveNamedArguments (EmitContext ec)
1436 return base.ResolveNamedArguments (ec);
1444 public class Attributes {
1445 public readonly ArrayList Attrs;
1447 public Attributes (Attribute a)
1449 Attrs = new ArrayList ();
1453 public Attributes (ArrayList attrs)
1458 public void AddAttributes (ArrayList attrs)
1460 Attrs.AddRange (attrs);
1463 public void AttachTo (Attributable attributable)
1465 foreach (Attribute a in Attrs)
1466 a.AttachTo (attributable);
1469 public Attributes Clone ()
1471 ArrayList al = new ArrayList (Attrs.Count);
1472 foreach (Attribute a in Attrs)
1473 al.Add (a.Clone ());
1475 return new Attributes (al);
1479 /// Checks whether attribute target is valid for the current element
1481 public bool CheckTargets ()
1483 foreach (Attribute a in Attrs) {
1484 if (!a.CheckTarget ())
1490 public Attribute Search (PredefinedAttribute t)
1492 foreach (Attribute a in Attrs) {
1493 if (a.ResolveType () == t)
1500 /// Returns all attributes of type 't'. Use it when attribute is AllowMultiple = true
1502 public Attribute[] SearchMulti (PredefinedAttribute t)
1504 ArrayList ar = null;
1506 foreach (Attribute a in Attrs) {
1507 if (a.ResolveType () == t) {
1509 ar = new ArrayList ();
1514 return ar == null ? null : ar.ToArray (typeof (Attribute)) as Attribute[];
1521 ListDictionary ld = Attrs.Count > 1 ? new ListDictionary () : null;
1523 foreach (Attribute a in Attrs)
1526 if (ld == null || ld.Count == 0)
1529 foreach (DictionaryEntry d in ld) {
1530 if (d.Value == null)
1533 foreach (Attribute collision in (ArrayList)d.Value)
1534 Report.SymbolRelatedToPreviousError (collision.Location, "");
1536 Attribute a = (Attribute)d.Key;
1537 Report.Error (579, a.Location, "The attribute `{0}' cannot be applied multiple times",
1538 a.GetSignatureForError ());
1542 public bool Contains (PredefinedAttribute t)
1544 return Search (t) != null;
1549 /// Helper class for attribute verification routine.
1551 sealed class AttributeTester
1553 static PtrHashtable analyzed_types;
1554 static PtrHashtable analyzed_types_obsolete;
1555 static PtrHashtable analyzed_member_obsolete;
1556 static PtrHashtable analyzed_method_excluded;
1557 static PtrHashtable fixed_buffer_cache;
1559 static object TRUE = new object ();
1560 static object FALSE = new object ();
1562 static AttributeTester ()
1567 private AttributeTester ()
1571 public static void Reset ()
1573 analyzed_types = new PtrHashtable ();
1574 analyzed_types_obsolete = new PtrHashtable ();
1575 analyzed_member_obsolete = new PtrHashtable ();
1576 analyzed_method_excluded = new PtrHashtable ();
1577 fixed_buffer_cache = new PtrHashtable ();
1580 public enum Result {
1587 /// Returns true if parameters of two compared methods are CLS-Compliant.
1588 /// It tests differing only in ref or out, or in array rank.
1590 public static Result AreOverloadedMethodParamsClsCompliant (AParametersCollection pa, AParametersCollection pb)
1592 Type [] types_a = pa.Types;
1593 Type [] types_b = pb.Types;
1594 if (types_a == null || types_b == null)
1597 if (types_a.Length != types_b.Length)
1600 Result result = Result.Ok;
1601 for (int i = 0; i < types_b.Length; ++i) {
1602 Type aType = types_a [i];
1603 Type bType = types_b [i];
1605 if (aType.IsArray && bType.IsArray) {
1606 Type a_el_type = TypeManager.GetElementType (aType);
1607 Type b_el_type = TypeManager.GetElementType (bType);
1608 if (aType.GetArrayRank () != bType.GetArrayRank () && a_el_type == b_el_type) {
1609 result = Result.RefOutArrayError;
1613 if (a_el_type.IsArray || b_el_type.IsArray) {
1614 result = Result.ArrayArrayError;
1622 const Parameter.Modifier out_ref_mod = (Parameter.Modifier.OUTMASK | Parameter.Modifier.REFMASK);
1623 if ((pa.FixedParameters[i].ModFlags & out_ref_mod) != (pb.FixedParameters[i].ModFlags & out_ref_mod))
1624 result = Result.RefOutArrayError;
1630 /// This method tests the CLS compliance of external types. It doesn't test type visibility.
1632 public static bool IsClsCompliant (Type type)
1637 object type_compliance = analyzed_types[type];
1638 if (type_compliance != null)
1639 return type_compliance == TRUE;
1641 if (type.IsPointer) {
1642 analyzed_types.Add (type, FALSE);
1648 result = IsClsCompliant (TypeManager.GetElementType (type));
1649 } else if (TypeManager.IsNullableType (type)) {
1650 result = IsClsCompliant (TypeManager.GetTypeArguments (type) [0]);
1652 result = AnalyzeTypeCompliance (type);
1654 analyzed_types.Add (type, result ? TRUE : FALSE);
1659 /// Returns IFixedBuffer implementation if field is fixed buffer else null.
1661 public static IFixedBuffer GetFixedBuffer (FieldInfo fi)
1663 // Fixed buffer helper type is generated as value type
1664 if (TypeManager.IsReferenceType (fi.FieldType))
1667 FieldBase fb = TypeManager.GetField (fi);
1669 return fb as IFixedBuffer;
1672 if (TypeManager.GetConstant (fi) != null)
1675 object o = fixed_buffer_cache [fi];
1677 PredefinedAttribute pa = PredefinedAttributes.Get.FixedBuffer;
1681 if (!fi.IsDefined (pa.Type, false)) {
1682 fixed_buffer_cache.Add (fi, FALSE);
1686 IFixedBuffer iff = new FixedFieldExternal (fi);
1687 fixed_buffer_cache.Add (fi, iff);
1694 return (IFixedBuffer)o;
1697 public static void VerifyModulesClsCompliance ()
1699 Module[] modules = GlobalRootNamespace.Instance.Modules;
1700 if (modules == null)
1703 // The first module is generated assembly
1704 for (int i = 1; i < modules.Length; ++i) {
1705 Module module = modules [i];
1706 if (!GetClsCompliantAttributeValue (module, null)) {
1707 Report.Error (3013, "Added modules must be marked with the CLSCompliant attribute " +
1708 "to match the assembly", module.Name);
1714 public static Type GetImportedIgnoreCaseClsType (string name)
1716 foreach (Assembly a in GlobalRootNamespace.Instance.Assemblies) {
1717 Type t = a.GetType (name, false, true);
1721 if (IsClsCompliant (t))
1727 static bool GetClsCompliantAttributeValue (ICustomAttributeProvider attribute_provider, Assembly a)
1729 PredefinedAttribute pa = PredefinedAttributes.Get.CLSCompliant;
1733 object[] cls_attr = attribute_provider.GetCustomAttributes (pa.Type, false);
1734 if (cls_attr.Length == 0) {
1738 return GetClsCompliantAttributeValue (a, null);
1741 return ((CLSCompliantAttribute)cls_attr [0]).IsCompliant;
1744 static bool AnalyzeTypeCompliance (Type type)
1746 type = TypeManager.DropGenericTypeArguments (type);
1747 DeclSpace ds = TypeManager.LookupDeclSpace (type);
1749 return ds.IsClsComplianceRequired ();
1752 if (TypeManager.IsGenericParameter (type))
1755 return GetClsCompliantAttributeValue (type, type.Assembly);
1759 /// Returns instance of ObsoleteAttribute when type is obsolete
1761 public static ObsoleteAttribute GetObsoleteAttribute (Type type)
1763 object type_obsolete = analyzed_types_obsolete [type];
1764 if (type_obsolete == FALSE)
1767 if (type_obsolete != null)
1768 return (ObsoleteAttribute)type_obsolete;
1770 ObsoleteAttribute result = null;
1771 if (TypeManager.HasElementType (type)) {
1772 result = GetObsoleteAttribute (TypeManager.GetElementType (type));
1773 } else if (TypeManager.IsGenericParameter (type))
1774 result = null; // TODO: throw new NotSupportedException ()
1775 else if (TypeManager.IsGenericType (type) && !TypeManager.IsGenericTypeDefinition (type)) {
1776 return GetObsoleteAttribute (TypeManager.DropGenericTypeArguments (type));
1778 DeclSpace type_ds = TypeManager.LookupDeclSpace (type);
1780 // Type is external, we can get attribute directly
1781 if (type_ds == null) {
1782 PredefinedAttribute pa = PredefinedAttributes.Get.Obsolete;
1784 object[] attribute = type.GetCustomAttributes (pa.Type, false);
1785 if (attribute.Length == 1)
1786 result = (ObsoleteAttribute) attribute[0];
1789 result = type_ds.GetObsoleteAttribute ();
1793 // Cannot use .Add because of corlib bootstrap
1794 analyzed_types_obsolete [type] = result == null ? FALSE : result;
1799 /// Returns instance of ObsoleteAttribute when method is obsolete
1801 public static ObsoleteAttribute GetMethodObsoleteAttribute (MethodBase mb)
1803 IMethodData mc = TypeManager.GetMethod (mb);
1805 return mc.GetObsoleteAttribute ();
1807 // compiler generated methods are not registered by AddMethod
1808 if (mb.DeclaringType is TypeBuilder)
1811 MemberInfo mi = TypeManager.GetPropertyFromAccessor (mb);
1813 return GetMemberObsoleteAttribute (mi);
1815 mi = TypeManager.GetEventFromAccessor (mb);
1817 return GetMemberObsoleteAttribute (mi);
1819 return GetMemberObsoleteAttribute (mb);
1823 /// Returns instance of ObsoleteAttribute when member is obsolete
1825 public static ObsoleteAttribute GetMemberObsoleteAttribute (MemberInfo mi)
1827 object type_obsolete = analyzed_member_obsolete [mi];
1828 if (type_obsolete == FALSE)
1831 if (type_obsolete != null)
1832 return (ObsoleteAttribute)type_obsolete;
1834 if ((mi.DeclaringType is TypeBuilder) || TypeManager.IsGenericType (mi.DeclaringType))
1837 PredefinedAttribute pa = PredefinedAttributes.Get.Obsolete;
1841 ObsoleteAttribute oa = System.Attribute.GetCustomAttribute (mi, pa.Type, false)
1842 as ObsoleteAttribute;
1843 analyzed_member_obsolete.Add (mi, oa == null ? FALSE : oa);
1848 /// Common method for Obsolete error/warning reporting.
1850 public static void Report_ObsoleteMessage (ObsoleteAttribute oa, string member, Location loc)
1853 Report.Error (619, loc, "`{0}' is obsolete: `{1}'", member, oa.Message);
1857 if (oa.Message == null || oa.Message.Length == 0) {
1858 Report.Warning (612, 1, loc, "`{0}' is obsolete", member);
1861 Report.Warning (618, 2, loc, "`{0}' is obsolete: `{1}'", member, oa.Message);
1864 public static bool IsConditionalMethodExcluded (MethodBase mb, Location loc)
1866 object excluded = analyzed_method_excluded [mb];
1867 if (excluded != null)
1868 return excluded == TRUE ? true : false;
1870 PredefinedAttribute pa = PredefinedAttributes.Get.Conditional;
1874 ConditionalAttribute[] attrs = mb.GetCustomAttributes (pa.Type, true)
1875 as ConditionalAttribute[];
1876 if (attrs.Length == 0) {
1877 analyzed_method_excluded.Add (mb, FALSE);
1881 foreach (ConditionalAttribute a in attrs) {
1882 if (loc.CompilationUnit.IsConditionalDefined (a.ConditionString)) {
1883 analyzed_method_excluded.Add (mb, FALSE);
1888 analyzed_method_excluded.Add (mb, TRUE);
1893 /// Analyzes class whether it has attribute which has ConditionalAttribute
1894 /// and its condition is not defined.
1896 public static bool IsAttributeExcluded (Type type, Location loc)
1901 Class class_decl = TypeManager.LookupDeclSpace (type) as Class;
1903 // TODO: add caching
1904 // TODO: merge all Type bases attribute caching to one cache to save memory
1905 PredefinedAttribute pa = PredefinedAttributes.Get.Conditional;
1906 if (class_decl == null && pa.IsDefined) {
1907 object[] attributes = type.GetCustomAttributes (pa.Type, false);
1908 foreach (ConditionalAttribute ca in attributes) {
1909 if (loc.CompilationUnit.IsConditionalDefined (ca.ConditionString))
1912 return attributes.Length > 0;
1915 return class_decl.IsExcluded ();
1918 public static Type GetCoClassAttribute (Type type)
1920 TypeContainer tc = TypeManager.LookupInterface (type);
1921 PredefinedAttribute pa = PredefinedAttributes.Get.CoClass;
1926 object[] o = type.GetCustomAttributes (pa.Type, false);
1929 return ((System.Runtime.InteropServices.CoClassAttribute)o[0]).CoClass;
1932 if (tc.OptAttributes == null)
1935 Attribute a = tc.OptAttributes.Search (pa);
1939 return a.GetCoClassAttributeValue ();
1943 public class PredefinedAttributes
1946 public readonly PredefinedAttribute ParamArray;
1947 public readonly PredefinedAttribute Out;
1950 public readonly PredefinedAttribute Obsolete;
1951 public readonly PredefinedAttribute DllImport;
1952 public readonly PredefinedAttribute MethodImpl;
1953 public readonly PredefinedAttribute MarshalAs;
1954 public readonly PredefinedAttribute In;
1955 public readonly PredefinedAttribute IndexerName;
1956 public readonly PredefinedAttribute Conditional;
1957 public readonly PredefinedAttribute CLSCompliant;
1958 public readonly PredefinedAttribute Security;
1959 public readonly PredefinedAttribute Required;
1960 public readonly PredefinedAttribute Guid;
1961 public readonly PredefinedAttribute AssemblyCulture;
1962 public readonly PredefinedAttribute AssemblyVersion;
1963 public readonly PredefinedAttribute ComImport;
1964 public readonly PredefinedAttribute CoClass;
1965 public readonly PredefinedAttribute AttributeUsage;
1966 public readonly PredefinedAttribute DefaultParameterValue;
1969 public readonly PredefinedAttribute DefaultCharset;
1970 public readonly PredefinedAttribute TypeForwarder;
1971 public readonly PredefinedAttribute FixedBuffer;
1972 public readonly PredefinedAttribute CompilerGenerated;
1973 public readonly PredefinedAttribute InternalsVisibleTo;
1974 public readonly PredefinedAttribute RuntimeCompatibility;
1975 public readonly PredefinedAttribute DebuggerHidden;
1976 public readonly PredefinedAttribute UnsafeValueType;
1979 public readonly PredefinedAttribute Extension;
1982 // Optional types which are used as types and for member lookup
1984 public readonly PredefinedAttribute DefaultMember;
1985 public readonly PredefinedAttribute DecimalConstant;
1986 public readonly PredefinedAttribute StructLayout;
1987 public readonly PredefinedAttribute FieldOffset;
1989 public static PredefinedAttributes Get = new PredefinedAttributes ();
1991 private PredefinedAttributes ()
1993 ParamArray = new PredefinedAttribute ("System", "ParamArrayAttribute");
1994 Out = new PredefinedAttribute ("System.Runtime.InteropServices", "OutAttribute");
1996 Obsolete = new PredefinedAttribute ("System", "ObsoleteAttribute");
1997 DllImport = new PredefinedAttribute ("System.Runtime.InteropServices", "DllImportAttribute");
1998 MethodImpl = new PredefinedAttribute ("System.Runtime.CompilerServices", "MethodImplAttribute");
1999 MarshalAs = new PredefinedAttribute ("System.Runtime.InteropServices", "MarshalAsAttribute");
2000 In = new PredefinedAttribute ("System.Runtime.InteropServices", "InAttribute");
2001 IndexerName = new PredefinedAttribute ("System.Runtime.CompilerServices", "IndexerNameAttribute");
2002 Conditional = new PredefinedAttribute ("System.Diagnostics", "ConditionalAttribute");
2003 CLSCompliant = new PredefinedAttribute ("System", "CLSCompliantAttribute");
2004 Security = new PredefinedAttribute ("System.Security.Permissions", "SecurityAttribute");
2005 Required = new PredefinedAttribute ("System.Runtime.CompilerServices", "RequiredAttributeAttribute");
2006 Guid = new PredefinedAttribute ("System.Runtime.InteropServices", "GuidAttribute");
2007 AssemblyCulture = new PredefinedAttribute ("System.Reflection", "AssemblyCultureAttribute");
2008 AssemblyVersion = new PredefinedAttribute ("System.Reflection", "AssemblyVersionAttribute");
2009 ComImport = new PredefinedAttribute ("System.Runtime.InteropServices", "ComImportAttribute");
2010 CoClass = new PredefinedAttribute ("System.Runtime.InteropServices", "CoClassAttribute");
2011 AttributeUsage = new PredefinedAttribute ("System", "AttributeUsageAttribute");
2012 DefaultParameterValue = new PredefinedAttribute ("System.Runtime.InteropServices", "DefaultParameterValueAttribute");
2014 DefaultCharset = new PredefinedAttribute ("System.Runtime.InteropServices", "DefaultCharSetAttribute");
2015 TypeForwarder = new PredefinedAttribute ("System.Runtime.CompilerServices", "TypeForwardedToAttribute");
2016 FixedBuffer = new PredefinedAttribute ("System.Runtime.CompilerServices", "FixedBufferAttribute");
2017 CompilerGenerated = new PredefinedAttribute ("System.Runtime.CompilerServices", "CompilerGeneratedAttribute");
2018 InternalsVisibleTo = new PredefinedAttribute ("System.Runtime.CompilerServices", "InternalsVisibleToAttribute");
2019 RuntimeCompatibility = new PredefinedAttribute ("System.Runtime.CompilerServices", "RuntimeCompatibilityAttribute");
2020 DebuggerHidden = new PredefinedAttribute ("System.Diagnostics", "DebuggerHiddenAttribute");
2021 UnsafeValueType = new PredefinedAttribute ("System.Runtime.CompilerServices", "UnsafeValueTypeAttribute");
2023 Extension = new PredefinedAttribute ("System.Runtime.CompilerServices", "ExtensionAttribute");
2025 DefaultMember = new PredefinedAttribute ("System.Reflection", "DefaultMemberAttribute");
2026 DecimalConstant = new PredefinedAttribute ("System.Runtime.CompilerServices", "DecimalConstantAttribute");
2027 StructLayout = new PredefinedAttribute ("System.Runtime.InteropServices", "StructLayoutAttribute");
2028 FieldOffset = new PredefinedAttribute ("System.Runtime.InteropServices", "FieldOffsetAttribute");
2031 public void Initialize ()
2033 foreach (FieldInfo fi in GetType ().GetFields (BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly)) {
2034 ((PredefinedAttribute) fi.GetValue (this)).Resolve (true);
2038 public static void Reset ()
2040 Get = new PredefinedAttributes ();
2044 public class PredefinedAttribute
2047 CustomAttributeBuilder cab;
2048 ConstructorInfo ctor;
2049 readonly string ns, name;
2051 public PredefinedAttribute (string ns, string name)
2057 public static bool operator == (Type type, PredefinedAttribute pa)
2059 return type == pa.type;
2062 public static bool operator != (Type type, PredefinedAttribute pa)
2064 return type != pa.type;
2067 public ConstructorInfo Constructor {
2068 get { return ctor; }
2071 public override int GetHashCode ()
2073 return base.GetHashCode ();
2076 public override bool Equals (object obj)
2078 throw new NotSupportedException ();
2081 public void EmitAttribute (ConstructorBuilder builder)
2083 if (ResolveBuilder ())
2084 builder.SetCustomAttribute (cab);
2087 public void EmitAttribute (MethodBuilder builder)
2089 if (ResolveBuilder ())
2090 builder.SetCustomAttribute (cab);
2093 public void EmitAttribute (FieldBuilder builder)
2095 if (ResolveBuilder ())
2096 builder.SetCustomAttribute (cab);
2099 public void EmitAttribute (TypeBuilder builder)
2101 if (ResolveBuilder ())
2102 builder.SetCustomAttribute (cab);
2105 public void EmitAttribute (AssemblyBuilder builder)
2107 if (ResolveBuilder ())
2108 builder.SetCustomAttribute (cab);
2111 public void EmitAttribute (ParameterBuilder builder, Location loc)
2113 if (ResolveBuilder ())
2114 builder.SetCustomAttribute (cab);
2117 public bool IsDefined {
2118 get { return type != null && type != typeof (PredefinedAttribute); }
2121 public bool Resolve (bool canFail)
2130 type = TypeManager.CoreLookupType (ns, name, Kind.Class, !canFail);
2132 type = typeof (PredefinedAttribute);
2139 bool ResolveBuilder ()
2145 // Handle all parameter-less attributes as optional
2147 if (!Resolve (true))
2150 ConstructorInfo ci = TypeManager.GetPredefinedConstructor (type, Location.Null, Type.EmptyTypes);
2154 cab = new CustomAttributeBuilder (ci, new object[0]);
2158 public bool ResolveConstructor (Location loc, params Type[] argType)
2161 throw new InternalErrorException ("Predefined ctor redefined");
2163 if (!Resolve (false))
2166 ctor = TypeManager.GetPredefinedConstructor (type, loc, argType);
2167 return ctor != null;
2171 get { return type; }