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 void ApplyModuleCharSet ()
370 if (Type != PredefinedAttributes.Get.DllImport)
373 if (!RootContext.ToplevelTypes.HasDefaultCharSet)
376 const string CharSetEnumMember = "CharSet";
377 if (NamedArguments == null) {
378 NamedArguments = new ArrayList (1);
380 foreach (DictionaryEntry de in NamedArguments) {
381 if ((string)de.Key == CharSetEnumMember)
386 NamedArguments.Add (new DictionaryEntry (CharSetEnumMember,
387 new Argument (Constant.CreateConstant (typeof (CharSet), RootContext.ToplevelTypes.DefaultCharSet, Location))));
390 public CustomAttributeBuilder Resolve ()
395 resolve_error = true;
398 ResolveAttributeType ();
403 if (Type.IsAbstract) {
404 Report.Error (653, Location, "Cannot apply attribute class `{0}' because it is abstract", GetSignatureForError ());
408 ObsoleteAttribute obsolete_attr = AttributeTester.GetObsoleteAttribute (Type);
409 if (obsolete_attr != null) {
410 AttributeTester.Report_ObsoleteMessage (obsolete_attr, TypeManager.CSharpName (Type), Location);
413 if (PosArguments == null && NamedArguments == null) {
414 object o = att_cache [Type];
416 resolve_error = false;
417 return (CustomAttributeBuilder)o;
421 Attributable owner = Owner;
422 DeclSpace ds = owner.ResolveContext as DeclSpace;
424 ds = owner.ResolveContext.DeclContainer;
426 EmitContext ec = new EmitContext (owner.ResolveContext, ds, ds,
427 Location, null, typeof (Attribute), ds.ModFlags, false);
428 ec.IsAnonymousMethodAllowed = false;
430 ConstructorInfo ctor = ResolveConstructor (ec);
432 if (Type is TypeBuilder &&
433 TypeManager.LookupDeclSpace (Type).MemberCache == null)
434 // The attribute type has been DefineType'd, but not Defined. Let's not treat it as an error.
435 // It'll be resolved again when the attached-to entity is emitted.
436 resolve_error = false;
440 ApplyModuleCharSet ();
442 CustomAttributeBuilder cb;
444 // SRE does not allow private ctor but we want to report all source code errors
448 if (NamedArguments == null) {
449 cb = new CustomAttributeBuilder (ctor, pos_values);
451 if (pos_values.Length == 0)
452 att_cache.Add (Type, cb);
454 resolve_error = false;
458 if (!ResolveNamedArguments (ec)) {
462 cb = new CustomAttributeBuilder (ctor, pos_values,
463 prop_info_arr, prop_values_arr,
464 field_info_arr, field_values_arr);
466 resolve_error = false;
470 Error_AttributeArgumentNotValid (Location);
475 protected virtual ConstructorInfo ResolveConstructor (EmitContext ec)
477 if (PosArguments != null) {
478 for (int i = 0; i < PosArguments.Count; i++) {
479 Argument a = (Argument) PosArguments [i];
481 if (!a.Resolve (ec, Location))
486 MethodGroupExpr mg = MemberLookupFinal (ec, ec.ContainerType,
487 Type, ConstructorInfo.ConstructorName, MemberTypes.Constructor,
488 BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly,
489 Location) as MethodGroupExpr;
492 throw new NotImplementedException ();
494 mg = mg.OverloadResolve (ec, ref PosArguments, false, Location);
498 ConstructorInfo constructor = (ConstructorInfo)mg;
499 if (PosArguments == null) {
500 pos_values = EmptyObject;
504 AParametersCollection pd = TypeManager.GetParameterData (constructor);
506 int pos_arg_count = PosArguments.Count;
507 pos_values = new object [pos_arg_count];
508 for (int j = 0; j < pos_arg_count; ++j) {
509 Argument a = (Argument) PosArguments [j];
511 if (!a.Expr.GetAttributableValue (ec, a.Type, out pos_values [j]))
515 // Here we do the checks which should be done by corlib or by runtime.
516 // However Zoltan doesn't like it and every Mono compiler has to do it again.
517 PredefinedAttributes pa = PredefinedAttributes.Get;
518 if (Type == pa.Guid) {
520 new Guid ((string)pos_values [0]);
522 catch (Exception e) {
523 Error_AttributeEmitError (e.Message);
528 if (Type == pa.AttributeUsage && (int)pos_values [0] == 0) {
529 Report.Error (591, Location, "Invalid value for argument to `System.AttributeUsage' attribute");
533 if (Type == pa.IndexerName || Type == pa.Conditional) {
534 string v = pos_values [0] as string;
535 if (!Tokenizer.IsValidIdentifier (v) || Tokenizer.IsKeyword (v)) {
536 Report.Error (633, ((Argument)PosArguments[0]).Expr.Location,
537 "The argument to the `{0}' attribute must be a valid identifier", GetSignatureForError ());
542 if (Type == pa.MethodImpl && pos_values.Length == 1 &&
543 pd.Types [0] == TypeManager.short_type &&
544 !System.Enum.IsDefined (typeof (MethodImplOptions), pos_values [0].ToString ())) {
545 Error_AttributeEmitError ("Incorrect argument value.");
552 protected virtual bool ResolveNamedArguments (EmitContext ec)
554 int named_arg_count = NamedArguments.Count;
556 ArrayList field_infos = new ArrayList (named_arg_count);
557 ArrayList prop_infos = new ArrayList (named_arg_count);
558 ArrayList field_values = new ArrayList (named_arg_count);
559 ArrayList prop_values = new ArrayList (named_arg_count);
561 ArrayList seen_names = new ArrayList(named_arg_count);
563 foreach (DictionaryEntry de in NamedArguments) {
564 string member_name = (string) de.Key;
566 if (seen_names.Contains(member_name)) {
567 Report.Error(643, Location, "'{0}' duplicate named attribute argument", member_name);
570 seen_names.Add(member_name);
572 Argument a = (Argument) de.Value;
573 if (!a.Resolve (ec, Location))
576 Expression member = Expression.MemberLookup (
577 ec.ContainerType, Type, member_name,
579 BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static,
582 if (member == null) {
583 member = Expression.MemberLookup (ec.ContainerType, Type, member_name,
584 MemberTypes.All, BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static,
587 if (member != null) {
588 Report.SymbolRelatedToPreviousError (member.Type);
589 Expression.ErrorIsInaccesible (Location, member.GetSignatureForError ());
595 Expression.Error_TypeDoesNotContainDefinition (Location, Type, member_name);
599 if (!(member is PropertyExpr || member is FieldExpr)) {
600 Error_InvalidNamedArgument (member_name);
604 if (a.Expr is TypeParameterExpr){
605 Error_TypeParameterInAttribute (Location);
609 ObsoleteAttribute obsolete_attr;
611 if (member is PropertyExpr) {
612 PropertyInfo pi = ((PropertyExpr) member).PropertyInfo;
614 if (!pi.CanWrite || !pi.CanRead || pi.GetGetMethod ().IsStatic) {
615 Report.SymbolRelatedToPreviousError (pi);
616 Error_InvalidNamedArgument (member_name);
620 if (!IsValidArgumentType (member.Type)) {
621 Report.SymbolRelatedToPreviousError (pi);
622 Error_InvalidNamedAgrumentType (member_name);
627 if (!a.Expr.GetAttributableValue (ec, member.Type, out value))
630 PropertyBase pb = TypeManager.GetProperty (pi);
632 obsolete_attr = pb.GetObsoleteAttribute ();
634 obsolete_attr = AttributeTester.GetMemberObsoleteAttribute (pi);
636 prop_values.Add (value);
640 FieldInfo fi = ((FieldExpr) member).FieldInfo;
642 if (fi.IsInitOnly || fi.IsStatic) {
643 Error_InvalidNamedArgument (member_name);
647 if (!IsValidArgumentType (member.Type)) {
648 Report.SymbolRelatedToPreviousError (fi);
649 Error_InvalidNamedAgrumentType (member_name);
654 if (!a.Expr.GetAttributableValue (ec, member.Type, out value))
657 FieldBase fb = TypeManager.GetField (fi);
659 obsolete_attr = fb.GetObsoleteAttribute ();
661 obsolete_attr = AttributeTester.GetMemberObsoleteAttribute (fi);
663 field_values.Add (value);
664 field_infos.Add (fi);
667 if (obsolete_attr != null && !Owner.ResolveContext.IsInObsoleteScope)
668 AttributeTester.Report_ObsoleteMessage (obsolete_attr, member.GetSignatureForError (), member.Location);
671 prop_info_arr = new PropertyInfo [prop_infos.Count];
672 field_info_arr = new FieldInfo [field_infos.Count];
673 field_values_arr = new object [field_values.Count];
674 prop_values_arr = new object [prop_values.Count];
676 field_infos.CopyTo (field_info_arr, 0);
677 field_values.CopyTo (field_values_arr, 0);
679 prop_values.CopyTo (prop_values_arr, 0);
680 prop_infos.CopyTo (prop_info_arr, 0);
686 /// Get a string containing a list of valid targets for the attribute 'attr'
688 public string GetValidTargets ()
690 StringBuilder sb = new StringBuilder ();
691 AttributeTargets targets = GetAttributeUsage (Type).ValidOn;
693 if ((targets & AttributeTargets.Assembly) != 0)
694 sb.Append ("assembly, ");
696 if ((targets & AttributeTargets.Module) != 0)
697 sb.Append ("module, ");
699 if ((targets & AttributeTargets.Class) != 0)
700 sb.Append ("class, ");
702 if ((targets & AttributeTargets.Struct) != 0)
703 sb.Append ("struct, ");
705 if ((targets & AttributeTargets.Enum) != 0)
706 sb.Append ("enum, ");
708 if ((targets & AttributeTargets.Constructor) != 0)
709 sb.Append ("constructor, ");
711 if ((targets & AttributeTargets.Method) != 0)
712 sb.Append ("method, ");
714 if ((targets & AttributeTargets.Property) != 0)
715 sb.Append ("property, indexer, ");
717 if ((targets & AttributeTargets.Field) != 0)
718 sb.Append ("field, ");
720 if ((targets & AttributeTargets.Event) != 0)
721 sb.Append ("event, ");
723 if ((targets & AttributeTargets.Interface) != 0)
724 sb.Append ("interface, ");
726 if ((targets & AttributeTargets.Parameter) != 0)
727 sb.Append ("parameter, ");
729 if ((targets & AttributeTargets.Delegate) != 0)
730 sb.Append ("delegate, ");
732 if ((targets & AttributeTargets.ReturnValue) != 0)
733 sb.Append ("return, ");
736 if ((targets & AttributeTargets.GenericParameter) != 0)
737 sb.Append ("type parameter, ");
739 return sb.Remove (sb.Length - 2, 2).ToString ();
743 /// Returns AttributeUsage attribute based on types hierarchy
745 static AttributeUsageAttribute GetAttributeUsage (Type type)
747 AttributeUsageAttribute ua = usage_attr_cache [type] as AttributeUsageAttribute;
751 Class attr_class = TypeManager.LookupClass (type);
752 PredefinedAttribute pa = PredefinedAttributes.Get.AttributeUsage;
754 if (attr_class == null) {
756 return new AttributeUsageAttribute (0);
758 object[] usage_attr = type.GetCustomAttributes (pa.Type, true);
759 ua = (AttributeUsageAttribute)usage_attr [0];
760 usage_attr_cache.Add (type, ua);
765 if (attr_class.OptAttributes != null)
766 a = attr_class.OptAttributes.Search (pa);
769 if (attr_class.TypeBuilder.BaseType != TypeManager.attribute_type)
770 ua = GetAttributeUsage (attr_class.TypeBuilder.BaseType);
772 ua = DefaultUsageAttribute;
774 ua = a.GetAttributeUsageAttribute ();
777 usage_attr_cache.Add (type, ua);
781 AttributeUsageAttribute GetAttributeUsageAttribute ()
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...
789 return DefaultUsageAttribute;
791 AttributeUsageAttribute usage_attribute = new AttributeUsageAttribute ((AttributeTargets)pos_values [0]);
793 object field = GetPropertyValue ("AllowMultiple");
795 usage_attribute.AllowMultiple = (bool)field;
797 field = GetPropertyValue ("Inherited");
799 usage_attribute.Inherited = (bool)field;
801 return usage_attribute;
805 /// Returns custom name of indexer
807 public string GetIndexerAttributeValue ()
809 if (pos_values == null)
810 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
811 // But because a lot of attribute class code must be rewritten will be better to wait...
817 return pos_values [0] as string;
821 /// Returns condition of ConditionalAttribute
823 public string GetConditionalAttributeValue ()
825 if (pos_values == null)
826 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
827 // But because a lot of attribute class code must be rewritten will be better to wait...
833 return (string)pos_values [0];
837 /// Creates the instance of ObsoleteAttribute from this attribute instance
839 public ObsoleteAttribute GetObsoleteAttribute ()
841 if (pos_values == null)
842 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
843 // But because a lot of attribute class code must be rewritten will be better to wait...
849 if (pos_values == null || pos_values.Length == 0)
850 return new ObsoleteAttribute ();
852 if (pos_values.Length == 1)
853 return new ObsoleteAttribute ((string)pos_values [0]);
855 return new ObsoleteAttribute ((string)pos_values [0], (bool)pos_values [1]);
859 /// Returns value of CLSCompliantAttribute contructor parameter but because the method can be called
860 /// before ApplyAttribute. We need to resolve the arguments.
861 /// This situation occurs when class deps is differs from Emit order.
863 public bool GetClsCompliantAttributeValue ()
865 if (pos_values == null)
866 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
867 // But because a lot of attribute class code must be rewritten will be better to wait...
873 return (bool)pos_values [0];
876 public Type GetCoClassAttributeValue ()
878 if (pos_values == null)
884 return (Type)pos_values [0];
887 public bool CheckTarget ()
889 string[] valid_targets = Owner.ValidAttributeTargets;
890 if (ExplicitTarget == null || ExplicitTarget == valid_targets [0]) {
891 Target = Owner.AttributeTargets;
895 // TODO: we can skip the first item
896 if (((IList) valid_targets).Contains (ExplicitTarget)) {
897 switch (ExplicitTarget) {
898 case "return": Target = AttributeTargets.ReturnValue; return true;
899 case "param": Target = AttributeTargets.Parameter; return true;
900 case "field": Target = AttributeTargets.Field; return true;
901 case "method": Target = AttributeTargets.Method; return true;
902 case "property": Target = AttributeTargets.Property; return true;
904 throw new InternalErrorException ("Unknown explicit target: " + ExplicitTarget);
907 StringBuilder sb = new StringBuilder ();
908 foreach (string s in valid_targets) {
912 sb.Remove (sb.Length - 2, 2);
913 Report.Error (657, Location, "`{0}' is not a valid attribute location for this declaration. " +
914 "Valid attribute locations for this declaration are `{1}'", ExplicitTarget, sb.ToString ());
919 /// Tests permitted SecurityAction for assembly or other types
921 protected virtual bool IsSecurityActionValid (bool for_assembly)
923 SecurityAction action = GetSecurityActionValue ();
926 case SecurityAction.Demand:
927 case SecurityAction.Assert:
928 case SecurityAction.Deny:
929 case SecurityAction.PermitOnly:
930 case SecurityAction.LinkDemand:
931 case SecurityAction.InheritanceDemand:
936 case SecurityAction.RequestMinimum:
937 case SecurityAction.RequestOptional:
938 case SecurityAction.RequestRefuse:
944 Error_AttributeEmitError ("SecurityAction is out of range");
948 Error_AttributeEmitError (String.Concat ("SecurityAction `", action, "' is not valid for this declaration"));
952 System.Security.Permissions.SecurityAction GetSecurityActionValue ()
954 return (SecurityAction)pos_values [0];
958 /// Creates instance of SecurityAttribute class and add result of CreatePermission method to permission table.
960 /// <returns></returns>
961 public void ExtractSecurityPermissionSet (ListDictionary permissions)
963 Type orig_assembly_type = null;
965 if (TypeManager.LookupDeclSpace (Type) != null) {
966 if (!RootContext.StdLib) {
967 orig_assembly_type = Type.GetType (Type.FullName);
969 string orig_version_path = Environment.GetEnvironmentVariable ("__SECURITY_BOOTSTRAP_DB");
970 if (orig_version_path == null) {
971 Error_AttributeEmitError ("security custom attributes can not be referenced from defining assembly");
975 if (orig_sec_assembly == null) {
976 string file = Path.Combine (orig_version_path, Driver.OutputFile);
977 orig_sec_assembly = Assembly.LoadFile (file);
980 orig_assembly_type = orig_sec_assembly.GetType (Type.FullName, true);
981 if (orig_assembly_type == null) {
982 Report.Warning (-112, 1, Location, "Self-referenced security attribute `{0}' " +
983 "was not found in previous version of assembly");
989 SecurityAttribute sa;
990 // For all non-selfreferencing security attributes we can avoid all hacks
991 if (orig_assembly_type == null) {
992 sa = (SecurityAttribute) Activator.CreateInstance (Type, pos_values);
994 if (prop_info_arr != null) {
995 for (int i = 0; i < prop_info_arr.Length; ++i) {
996 PropertyInfo pi = prop_info_arr [i];
997 pi.SetValue (sa, prop_values_arr [i], null);
1001 // HACK: All security attributes have same ctor syntax
1002 sa = (SecurityAttribute) Activator.CreateInstance (orig_assembly_type, new object[] { GetSecurityActionValue () } );
1004 // All types are from newly created assembly but for invocation with old one we need to convert them
1005 if (prop_info_arr != null) {
1006 for (int i = 0; i < prop_info_arr.Length; ++i) {
1007 PropertyInfo emited_pi = prop_info_arr [i];
1008 // FIXME: We are missing return type filter
1009 // TODO: pi can be null
1010 PropertyInfo pi = orig_assembly_type.GetProperty (emited_pi.Name);
1012 object old_instance = TypeManager.IsEnumType (pi.PropertyType) ?
1013 System.Enum.ToObject (pi.PropertyType, prop_values_arr [i]) :
1014 prop_values_arr [i];
1016 pi.SetValue (sa, old_instance, null);
1022 perm = sa.CreatePermission ();
1023 SecurityAction action = GetSecurityActionValue ();
1025 // IS is correct because for corlib we are using an instance from old corlib
1026 if (!(perm is System.Security.CodeAccessPermission)) {
1028 case SecurityAction.Demand:
1029 action = (SecurityAction)13;
1031 case SecurityAction.LinkDemand:
1032 action = (SecurityAction)14;
1034 case SecurityAction.InheritanceDemand:
1035 action = (SecurityAction)15;
1040 PermissionSet ps = (PermissionSet)permissions [action];
1042 if (sa is PermissionSetAttribute)
1043 ps = new PermissionSet (sa.Unrestricted ? PermissionState.Unrestricted : PermissionState.None);
1045 ps = new PermissionSet (PermissionState.None);
1047 permissions.Add (action, ps);
1048 } else if (!ps.IsUnrestricted () && (sa is PermissionSetAttribute) && sa.Unrestricted) {
1049 ps = ps.Union (new PermissionSet (PermissionState.Unrestricted));
1050 permissions [action] = ps;
1052 ps.AddPermission (perm);
1055 public object GetPropertyValue (string name)
1057 if (prop_info_arr == null)
1060 for (int i = 0; i < prop_info_arr.Length; ++i) {
1061 if (prop_info_arr [i].Name == name)
1062 return prop_values_arr [i];
1069 // Theoretically, we can get rid of this, since FieldBuilder.SetCustomAttribute()
1070 // and ParameterBuilder.SetCustomAttribute() are supposed to handle this attribute.
1071 // However, we can't, since it appears that the .NET 1.1 SRE hangs when given a MarshalAsAttribute.
1074 public UnmanagedMarshal GetMarshal (Attributable attr)
1076 UnmanagedType UnmanagedType;
1077 if (!RootContext.StdLib || pos_values [0].GetType () != typeof (UnmanagedType))
1078 UnmanagedType = (UnmanagedType) System.Enum.ToObject (typeof (UnmanagedType), pos_values [0]);
1080 UnmanagedType = (UnmanagedType) pos_values [0];
1082 object value = GetFieldValue ("SizeParamIndex");
1083 if (value != null && UnmanagedType != UnmanagedType.LPArray) {
1084 Error_AttributeEmitError ("SizeParamIndex field is not valid for the specified unmanaged type");
1088 object o = GetFieldValue ("ArraySubType");
1089 UnmanagedType array_sub_type = o == null ? (UnmanagedType) 0x50 /* NATIVE_MAX */ : (UnmanagedType) o;
1091 switch (UnmanagedType) {
1092 case UnmanagedType.CustomMarshaler: {
1093 MethodInfo define_custom = typeof (UnmanagedMarshal).GetMethod ("DefineCustom",
1094 BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
1095 if (define_custom == null) {
1096 Report.RuntimeMissingSupport (Location, "set marshal info");
1100 object [] args = new object [4];
1101 args [0] = GetFieldValue ("MarshalTypeRef");
1102 args [1] = GetFieldValue ("MarshalCookie");
1103 args [2] = GetFieldValue ("MarshalType");
1104 args [3] = Guid.Empty;
1105 return (UnmanagedMarshal) define_custom.Invoke (null, args);
1107 case UnmanagedType.LPArray: {
1108 object size_const = GetFieldValue ("SizeConst");
1109 object size_param_index = GetFieldValue ("SizeParamIndex");
1111 if ((size_const != null) || (size_param_index != null)) {
1112 MethodInfo define_array = typeof (UnmanagedMarshal).GetMethod ("DefineLPArrayInternal",
1113 BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
1114 if (define_array == null) {
1115 Report.RuntimeMissingSupport (Location, "set marshal info");
1119 object [] args = new object [3];
1120 args [0] = array_sub_type;
1121 args [1] = size_const == null ? -1 : size_const;
1122 args [2] = size_param_index == null ? -1 : size_param_index;
1123 return (UnmanagedMarshal) define_array.Invoke (null, args);
1126 return UnmanagedMarshal.DefineLPArray (array_sub_type);
1128 case UnmanagedType.SafeArray:
1129 return UnmanagedMarshal.DefineSafeArray (array_sub_type);
1131 case UnmanagedType.ByValArray:
1132 FieldBase fm = attr as FieldBase;
1134 Error_AttributeEmitError ("Specified unmanaged type is only valid on fields");
1137 return UnmanagedMarshal.DefineByValArray ((int) GetFieldValue ("SizeConst"));
1139 case UnmanagedType.ByValTStr:
1140 return UnmanagedMarshal.DefineByValTStr ((int) GetFieldValue ("SizeConst"));
1143 return UnmanagedMarshal.DefineUnmanagedMarshal (UnmanagedType);
1147 object GetFieldValue (string name)
1150 if (field_info_arr == null)
1153 foreach (FieldInfo fi in field_info_arr) {
1154 if (fi.Name == name)
1155 return GetValue (field_values_arr [i]);
1161 static object GetValue (object value)
1163 if (value is EnumConstant)
1164 return ((EnumConstant) value).GetValue ();
1171 public CharSet GetCharSetValue ()
1173 return (CharSet)System.Enum.Parse (typeof (CharSet), pos_values [0].ToString ());
1176 public bool HasField (string fieldName)
1178 if (field_info_arr == null)
1181 foreach (FieldInfo fi in field_info_arr) {
1182 if (fi.Name == fieldName)
1189 public bool IsInternalMethodImplAttribute {
1191 if (Type != PredefinedAttributes.Get.MethodImpl)
1194 MethodImplOptions options;
1195 if (pos_values[0].GetType () != typeof (MethodImplOptions))
1196 options = (MethodImplOptions)System.Enum.ToObject (typeof (MethodImplOptions), pos_values[0]);
1198 options = (MethodImplOptions)pos_values[0];
1200 return (options & MethodImplOptions.InternalCall) != 0;
1204 public LayoutKind GetLayoutKindValue ()
1206 if (!RootContext.StdLib || pos_values [0].GetType () != typeof (LayoutKind))
1207 return (LayoutKind)System.Enum.ToObject (typeof (LayoutKind), pos_values [0]);
1209 return (LayoutKind)pos_values [0];
1212 public object GetParameterDefaultValue ()
1214 return pos_values [0];
1217 public override bool Equals (object obj)
1219 Attribute a = obj as Attribute;
1223 return Type == a.Type && Target == a.Target;
1226 public override int GetHashCode ()
1228 return base.GetHashCode ();
1232 /// Emit attribute for Attributable symbol
1234 public void Emit (ListDictionary allEmitted)
1236 CustomAttributeBuilder cb = Resolve ();
1240 AttributeUsageAttribute usage_attr = GetAttributeUsage (Type);
1241 if ((usage_attr.ValidOn & Target) == 0) {
1242 Report.Error (592, Location, "The attribute `{0}' is not valid on this declaration type. " +
1243 "It is valid on `{1}' declarations only",
1244 GetSignatureForError (), GetValidTargets ());
1249 foreach (Attributable owner in owners)
1250 owner.ApplyAttributeBuilder (this, cb, PredefinedAttributes.Get);
1252 catch (Exception e) {
1253 Error_AttributeEmitError (e.Message);
1257 if (!usage_attr.AllowMultiple && allEmitted != null) {
1258 if (allEmitted.Contains (this)) {
1259 ArrayList a = allEmitted [this] as ArrayList;
1261 a = new ArrayList (2);
1262 allEmitted [this] = a;
1266 allEmitted.Add (this, null);
1270 if (!RootContext.VerifyClsCompliance)
1273 // Here we are testing attribute arguments for array usage (error 3016)
1274 if (Owner.IsClsComplianceRequired ()) {
1275 if (PosArguments != null) {
1276 foreach (Argument arg in PosArguments) {
1277 // Type is undefined (was error 246)
1278 if (arg.Type == null)
1281 if (arg.Type.IsArray) {
1282 Report.Warning (3016, 1, Location, "Arrays as attribute arguments are not CLS-compliant");
1288 if (NamedArguments == null)
1291 foreach (DictionaryEntry de in NamedArguments) {
1292 Argument arg = (Argument) de.Value;
1294 // Type is undefined (was error 246)
1295 if (arg.Type == null)
1298 if (arg.Type.IsArray) {
1299 Report.Warning (3016, 1, Location, "Arrays as attribute arguments are not CLS-compliant");
1306 private Expression GetValue ()
1308 if (PosArguments == null || PosArguments.Count < 1)
1311 return ((Argument) PosArguments [0]).Expr;
1314 public string GetString ()
1316 Expression e = GetValue ();
1317 if (e is StringConstant)
1318 return ((StringConstant)e).Value;
1322 public bool GetBoolean ()
1324 Expression e = GetValue ();
1325 if (e is BoolConstant)
1326 return ((BoolConstant)e).Value;
1330 public Type GetArgumentType ()
1332 TypeOf e = GetValue () as TypeOf;
1335 return e.TypeArgument;
1338 public override Expression CreateExpressionTree (EmitContext ec)
1340 throw new NotSupportedException ("ET");
1343 public override Expression DoResolve (EmitContext ec)
1345 throw new NotImplementedException ();
1348 public override void Emit (EmitContext ec)
1350 throw new NotImplementedException ();
1356 /// For global attributes (assembly, module) we need special handling.
1357 /// Attributes can be located in the several files
1359 public class GlobalAttribute : Attribute
1361 public readonly NamespaceEntry ns;
1363 public GlobalAttribute (NamespaceEntry ns, string target,
1364 Expression left_expr, string identifier, object[] args, Location loc, bool nameEscaped):
1365 base (target, left_expr, identifier, args, loc, nameEscaped)
1368 this.owners = new Attributable[1];
1371 public override void AttachTo (Attributable owner)
1373 if (ExplicitTarget == "assembly") {
1374 owners [0] = CodeGen.Assembly;
1377 if (ExplicitTarget == "module") {
1378 owners [0] = RootContext.ToplevelTypes;
1381 throw new NotImplementedException ("Unknown global explicit target " + ExplicitTarget);
1386 // RootContext.ToplevelTypes has a single NamespaceEntry which gets overwritten
1387 // each time a new file is parsed. However, we need to use the NamespaceEntry
1388 // in effect where the attribute was used. Since code elsewhere cannot assume
1389 // that the NamespaceEntry is right, just overwrite it.
1391 // Precondition: RootContext.ToplevelTypes == null
1393 if (RootContext.ToplevelTypes.NamespaceEntry != null)
1394 throw new InternalErrorException (Location + " non-null NamespaceEntry");
1396 RootContext.ToplevelTypes.NamespaceEntry = ns;
1399 protected override bool IsSecurityActionValid (bool for_assembly)
1401 return base.IsSecurityActionValid (true);
1406 RootContext.ToplevelTypes.NamespaceEntry = null;
1409 protected override TypeExpr ResolveAsTypeTerminal (Expression expr, IResolveContext ec, bool silent)
1413 return base.ResolveAsTypeTerminal (expr, ec, silent);
1420 protected override ConstructorInfo ResolveConstructor (EmitContext ec)
1424 return base.ResolveConstructor (ec);
1431 protected override bool ResolveNamedArguments (EmitContext ec)
1435 return base.ResolveNamedArguments (ec);
1443 public class Attributes {
1444 public readonly ArrayList Attrs;
1446 public Attributes (Attribute a)
1448 Attrs = new ArrayList ();
1452 public Attributes (ArrayList attrs)
1457 public void AddAttributes (ArrayList attrs)
1459 Attrs.AddRange (attrs);
1462 public void AttachTo (Attributable attributable)
1464 foreach (Attribute a in Attrs)
1465 a.AttachTo (attributable);
1468 public Attributes Clone ()
1470 ArrayList al = new ArrayList (Attrs.Count);
1471 foreach (Attribute a in Attrs)
1472 al.Add (a.Clone ());
1474 return new Attributes (al);
1478 /// Checks whether attribute target is valid for the current element
1480 public bool CheckTargets ()
1482 foreach (Attribute a in Attrs) {
1483 if (!a.CheckTarget ())
1489 public Attribute Search (PredefinedAttribute t)
1491 foreach (Attribute a in Attrs) {
1492 if (a.ResolveType () == t)
1499 /// Returns all attributes of type 't'. Use it when attribute is AllowMultiple = true
1501 public Attribute[] SearchMulti (PredefinedAttribute t)
1503 ArrayList ar = null;
1505 foreach (Attribute a in Attrs) {
1506 if (a.ResolveType () == t) {
1508 ar = new ArrayList ();
1513 return ar == null ? null : ar.ToArray (typeof (Attribute)) as Attribute[];
1520 ListDictionary ld = Attrs.Count > 1 ? new ListDictionary () : null;
1522 foreach (Attribute a in Attrs)
1525 if (ld == null || ld.Count == 0)
1528 foreach (DictionaryEntry d in ld) {
1529 if (d.Value == null)
1532 foreach (Attribute collision in (ArrayList)d.Value)
1533 Report.SymbolRelatedToPreviousError (collision.Location, "");
1535 Attribute a = (Attribute)d.Key;
1536 Report.Error (579, a.Location, "The attribute `{0}' cannot be applied multiple times",
1537 a.GetSignatureForError ());
1541 public bool Contains (PredefinedAttribute t)
1543 return Search (t) != null;
1548 /// Helper class for attribute verification routine.
1550 sealed class AttributeTester
1552 static PtrHashtable analyzed_types;
1553 static PtrHashtable analyzed_types_obsolete;
1554 static PtrHashtable analyzed_member_obsolete;
1555 static PtrHashtable analyzed_method_excluded;
1556 static PtrHashtable fixed_buffer_cache;
1558 static object TRUE = new object ();
1559 static object FALSE = new object ();
1561 static AttributeTester ()
1566 private AttributeTester ()
1570 public static void Reset ()
1572 analyzed_types = new PtrHashtable ();
1573 analyzed_types_obsolete = new PtrHashtable ();
1574 analyzed_member_obsolete = new PtrHashtable ();
1575 analyzed_method_excluded = new PtrHashtable ();
1576 fixed_buffer_cache = new PtrHashtable ();
1579 public enum Result {
1586 /// Returns true if parameters of two compared methods are CLS-Compliant.
1587 /// It tests differing only in ref or out, or in array rank.
1589 public static Result AreOverloadedMethodParamsClsCompliant (AParametersCollection pa, AParametersCollection pb)
1591 Type [] types_a = pa.Types;
1592 Type [] types_b = pb.Types;
1593 if (types_a == null || types_b == null)
1596 if (types_a.Length != types_b.Length)
1599 Result result = Result.Ok;
1600 for (int i = 0; i < types_b.Length; ++i) {
1601 Type aType = types_a [i];
1602 Type bType = types_b [i];
1604 if (aType.IsArray && bType.IsArray) {
1605 Type a_el_type = TypeManager.GetElementType (aType);
1606 Type b_el_type = TypeManager.GetElementType (bType);
1607 if (aType.GetArrayRank () != bType.GetArrayRank () && a_el_type == b_el_type) {
1608 result = Result.RefOutArrayError;
1612 if (a_el_type.IsArray || b_el_type.IsArray) {
1613 result = Result.ArrayArrayError;
1621 const Parameter.Modifier out_ref_mod = (Parameter.Modifier.OUTMASK | Parameter.Modifier.REFMASK);
1622 if ((pa.FixedParameters[i].ModFlags & out_ref_mod) != (pb.FixedParameters[i].ModFlags & out_ref_mod))
1623 result = Result.RefOutArrayError;
1629 /// This method tests the CLS compliance of external types. It doesn't test type visibility.
1631 public static bool IsClsCompliant (Type type)
1636 object type_compliance = analyzed_types[type];
1637 if (type_compliance != null)
1638 return type_compliance == TRUE;
1640 if (type.IsPointer) {
1641 analyzed_types.Add (type, FALSE);
1647 result = IsClsCompliant (TypeManager.GetElementType (type));
1648 } else if (TypeManager.IsNullableType (type)) {
1649 result = IsClsCompliant (TypeManager.GetTypeArguments (type) [0]);
1651 result = AnalyzeTypeCompliance (type);
1653 analyzed_types.Add (type, result ? TRUE : FALSE);
1658 /// Returns IFixedBuffer implementation if field is fixed buffer else null.
1660 public static IFixedBuffer GetFixedBuffer (FieldInfo fi)
1662 // Fixed buffer helper type is generated as value type
1663 if (TypeManager.IsReferenceType (fi.FieldType))
1666 FieldBase fb = TypeManager.GetField (fi);
1668 return fb as IFixedBuffer;
1671 if (TypeManager.GetConstant (fi) != null)
1674 object o = fixed_buffer_cache [fi];
1676 PredefinedAttribute pa = PredefinedAttributes.Get.FixedBuffer;
1680 if (!fi.IsDefined (pa.Type, false)) {
1681 fixed_buffer_cache.Add (fi, FALSE);
1685 IFixedBuffer iff = new FixedFieldExternal (fi);
1686 fixed_buffer_cache.Add (fi, iff);
1693 return (IFixedBuffer)o;
1696 public static void VerifyModulesClsCompliance ()
1698 Module[] modules = GlobalRootNamespace.Instance.Modules;
1699 if (modules == null)
1702 // The first module is generated assembly
1703 for (int i = 1; i < modules.Length; ++i) {
1704 Module module = modules [i];
1705 if (!GetClsCompliantAttributeValue (module, null)) {
1706 Report.Error (3013, "Added modules must be marked with the CLSCompliant attribute " +
1707 "to match the assembly", module.Name);
1713 public static Type GetImportedIgnoreCaseClsType (string name)
1715 foreach (Assembly a in GlobalRootNamespace.Instance.Assemblies) {
1716 Type t = a.GetType (name, false, true);
1720 if (IsClsCompliant (t))
1726 static bool GetClsCompliantAttributeValue (ICustomAttributeProvider attribute_provider, Assembly a)
1728 PredefinedAttribute pa = PredefinedAttributes.Get.CLSCompliant;
1732 object[] cls_attr = attribute_provider.GetCustomAttributes (pa.Type, false);
1733 if (cls_attr.Length == 0) {
1737 return GetClsCompliantAttributeValue (a, null);
1740 return ((CLSCompliantAttribute)cls_attr [0]).IsCompliant;
1743 static bool AnalyzeTypeCompliance (Type type)
1745 type = TypeManager.DropGenericTypeArguments (type);
1746 DeclSpace ds = TypeManager.LookupDeclSpace (type);
1748 return ds.IsClsComplianceRequired ();
1751 if (TypeManager.IsGenericParameter (type))
1754 return GetClsCompliantAttributeValue (type, type.Assembly);
1758 /// Returns instance of ObsoleteAttribute when type is obsolete
1760 public static ObsoleteAttribute GetObsoleteAttribute (Type type)
1762 object type_obsolete = analyzed_types_obsolete [type];
1763 if (type_obsolete == FALSE)
1766 if (type_obsolete != null)
1767 return (ObsoleteAttribute)type_obsolete;
1769 ObsoleteAttribute result = null;
1770 if (TypeManager.HasElementType (type)) {
1771 result = GetObsoleteAttribute (TypeManager.GetElementType (type));
1772 } else if (TypeManager.IsGenericParameter (type))
1773 result = null; // TODO: throw new NotSupportedException ()
1774 else if (TypeManager.IsGenericType (type) && !TypeManager.IsGenericTypeDefinition (type)) {
1775 return GetObsoleteAttribute (TypeManager.DropGenericTypeArguments (type));
1777 DeclSpace type_ds = TypeManager.LookupDeclSpace (type);
1779 // Type is external, we can get attribute directly
1780 if (type_ds == null) {
1781 PredefinedAttribute pa = PredefinedAttributes.Get.Obsolete;
1783 object[] attribute = type.GetCustomAttributes (pa.Type, false);
1784 if (attribute.Length == 1)
1785 result = (ObsoleteAttribute) attribute[0];
1788 result = type_ds.GetObsoleteAttribute ();
1792 // Cannot use .Add because of corlib bootstrap
1793 analyzed_types_obsolete [type] = result == null ? FALSE : result;
1798 /// Returns instance of ObsoleteAttribute when method is obsolete
1800 public static ObsoleteAttribute GetMethodObsoleteAttribute (MethodBase mb)
1802 IMethodData mc = TypeManager.GetMethod (mb);
1804 return mc.GetObsoleteAttribute ();
1806 // compiler generated methods are not registered by AddMethod
1807 if (mb.DeclaringType is TypeBuilder)
1810 MemberInfo mi = TypeManager.GetPropertyFromAccessor (mb);
1812 return GetMemberObsoleteAttribute (mi);
1814 mi = TypeManager.GetEventFromAccessor (mb);
1816 return GetMemberObsoleteAttribute (mi);
1818 return GetMemberObsoleteAttribute (mb);
1822 /// Returns instance of ObsoleteAttribute when member is obsolete
1824 public static ObsoleteAttribute GetMemberObsoleteAttribute (MemberInfo mi)
1826 object type_obsolete = analyzed_member_obsolete [mi];
1827 if (type_obsolete == FALSE)
1830 if (type_obsolete != null)
1831 return (ObsoleteAttribute)type_obsolete;
1833 if ((mi.DeclaringType is TypeBuilder) || TypeManager.IsGenericType (mi.DeclaringType))
1836 PredefinedAttribute pa = PredefinedAttributes.Get.Obsolete;
1840 ObsoleteAttribute oa = System.Attribute.GetCustomAttribute (mi, pa.Type, false)
1841 as ObsoleteAttribute;
1842 analyzed_member_obsolete.Add (mi, oa == null ? FALSE : oa);
1847 /// Common method for Obsolete error/warning reporting.
1849 public static void Report_ObsoleteMessage (ObsoleteAttribute oa, string member, Location loc)
1852 Report.Error (619, loc, "`{0}' is obsolete: `{1}'", member, oa.Message);
1856 if (oa.Message == null || oa.Message.Length == 0) {
1857 Report.Warning (612, 1, loc, "`{0}' is obsolete", member);
1860 Report.Warning (618, 2, loc, "`{0}' is obsolete: `{1}'", member, oa.Message);
1863 public static bool IsConditionalMethodExcluded (MethodBase mb, Location loc)
1865 object excluded = analyzed_method_excluded [mb];
1866 if (excluded != null)
1867 return excluded == TRUE ? true : false;
1869 PredefinedAttribute pa = PredefinedAttributes.Get.Conditional;
1873 ConditionalAttribute[] attrs = mb.GetCustomAttributes (pa.Type, true)
1874 as ConditionalAttribute[];
1875 if (attrs.Length == 0) {
1876 analyzed_method_excluded.Add (mb, FALSE);
1880 foreach (ConditionalAttribute a in attrs) {
1881 if (loc.CompilationUnit.IsConditionalDefined (a.ConditionString)) {
1882 analyzed_method_excluded.Add (mb, FALSE);
1887 analyzed_method_excluded.Add (mb, TRUE);
1892 /// Analyzes class whether it has attribute which has ConditionalAttribute
1893 /// and its condition is not defined.
1895 public static bool IsAttributeExcluded (Type type, Location loc)
1900 Class class_decl = TypeManager.LookupDeclSpace (type) as Class;
1902 // TODO: add caching
1903 // TODO: merge all Type bases attribute caching to one cache to save memory
1904 PredefinedAttribute pa = PredefinedAttributes.Get.Conditional;
1905 if (class_decl == null && pa.IsDefined) {
1906 object[] attributes = type.GetCustomAttributes (pa.Type, false);
1907 foreach (ConditionalAttribute ca in attributes) {
1908 if (loc.CompilationUnit.IsConditionalDefined (ca.ConditionString))
1911 return attributes.Length > 0;
1914 return class_decl.IsExcluded ();
1917 public static Type GetCoClassAttribute (Type type)
1919 TypeContainer tc = TypeManager.LookupInterface (type);
1920 PredefinedAttribute pa = PredefinedAttributes.Get.CoClass;
1925 object[] o = type.GetCustomAttributes (pa.Type, false);
1928 return ((System.Runtime.InteropServices.CoClassAttribute)o[0]).CoClass;
1931 if (tc.OptAttributes == null)
1934 Attribute a = tc.OptAttributes.Search (pa);
1938 return a.GetCoClassAttributeValue ();
1942 public class PredefinedAttributes
1945 public readonly PredefinedAttribute ParamArray;
1946 public readonly PredefinedAttribute Out;
1949 public readonly PredefinedAttribute Obsolete;
1950 public readonly PredefinedAttribute DllImport;
1951 public readonly PredefinedAttribute MethodImpl;
1952 public readonly PredefinedAttribute MarshalAs;
1953 public readonly PredefinedAttribute In;
1954 public readonly PredefinedAttribute IndexerName;
1955 public readonly PredefinedAttribute Conditional;
1956 public readonly PredefinedAttribute CLSCompliant;
1957 public readonly PredefinedAttribute Security;
1958 public readonly PredefinedAttribute Required;
1959 public readonly PredefinedAttribute Guid;
1960 public readonly PredefinedAttribute AssemblyCulture;
1961 public readonly PredefinedAttribute AssemblyVersion;
1962 public readonly PredefinedAttribute ComImport;
1963 public readonly PredefinedAttribute CoClass;
1964 public readonly PredefinedAttribute AttributeUsage;
1965 public readonly PredefinedAttribute DefaultParameterValue;
1968 public readonly PredefinedAttribute DefaultCharset;
1969 public readonly PredefinedAttribute TypeForwarder;
1970 public readonly PredefinedAttribute FixedBuffer;
1971 public readonly PredefinedAttribute CompilerGenerated;
1972 public readonly PredefinedAttribute InternalsVisibleTo;
1973 public readonly PredefinedAttribute RuntimeCompatibility;
1974 public readonly PredefinedAttribute DebuggerHidden;
1975 public readonly PredefinedAttribute UnsafeValueType;
1978 public readonly PredefinedAttribute Extension;
1981 // Optional types which are used as types and for member lookup
1983 public readonly PredefinedAttribute DefaultMember;
1984 public readonly PredefinedAttribute DecimalConstant;
1985 public readonly PredefinedAttribute StructLayout;
1986 public readonly PredefinedAttribute FieldOffset;
1988 public static PredefinedAttributes Get = new PredefinedAttributes ();
1990 private PredefinedAttributes ()
1992 ParamArray = new PredefinedAttribute ("System", "ParamArrayAttribute");
1993 Out = new PredefinedAttribute ("System.Runtime.InteropServices", "OutAttribute");
1995 Obsolete = new PredefinedAttribute ("System", "ObsoleteAttribute");
1996 DllImport = new PredefinedAttribute ("System.Runtime.InteropServices", "DllImportAttribute");
1997 MethodImpl = new PredefinedAttribute ("System.Runtime.CompilerServices", "MethodImplAttribute");
1998 MarshalAs = new PredefinedAttribute ("System.Runtime.InteropServices", "MarshalAsAttribute");
1999 In = new PredefinedAttribute ("System.Runtime.InteropServices", "InAttribute");
2000 IndexerName = new PredefinedAttribute ("System.Runtime.CompilerServices", "IndexerNameAttribute");
2001 Conditional = new PredefinedAttribute ("System.Diagnostics", "ConditionalAttribute");
2002 CLSCompliant = new PredefinedAttribute ("System", "CLSCompliantAttribute");
2003 Security = new PredefinedAttribute ("System.Security.Permissions", "SecurityAttribute");
2004 Required = new PredefinedAttribute ("System.Runtime.CompilerServices", "RequiredAttributeAttribute");
2005 Guid = new PredefinedAttribute ("System.Runtime.InteropServices", "GuidAttribute");
2006 AssemblyCulture = new PredefinedAttribute ("System.Reflection", "AssemblyCultureAttribute");
2007 AssemblyVersion = new PredefinedAttribute ("System.Reflection", "AssemblyVersionAttribute");
2008 ComImport = new PredefinedAttribute ("System.Runtime.InteropServices", "ComImportAttribute");
2009 CoClass = new PredefinedAttribute ("System.Runtime.InteropServices", "CoClassAttribute");
2010 AttributeUsage = new PredefinedAttribute ("System", "AttributeUsageAttribute");
2011 DefaultParameterValue = new PredefinedAttribute ("System.Runtime.InteropServices", "DefaultParameterValueAttribute");
2013 DefaultCharset = new PredefinedAttribute ("System.Runtime.InteropServices", "DefaultCharSetAttribute");
2014 TypeForwarder = new PredefinedAttribute ("System.Runtime.CompilerServices", "TypeForwardedToAttribute");
2015 FixedBuffer = new PredefinedAttribute ("System.Runtime.CompilerServices", "FixedBufferAttribute");
2016 CompilerGenerated = new PredefinedAttribute ("System.Runtime.CompilerServices", "CompilerGeneratedAttribute");
2017 InternalsVisibleTo = new PredefinedAttribute ("System.Runtime.CompilerServices", "InternalsVisibleToAttribute");
2018 RuntimeCompatibility = new PredefinedAttribute ("System.Runtime.CompilerServices", "RuntimeCompatibilityAttribute");
2019 DebuggerHidden = new PredefinedAttribute ("System.Diagnostics", "DebuggerHiddenAttribute");
2020 UnsafeValueType = new PredefinedAttribute ("System.Runtime.CompilerServices", "UnsafeValueTypeAttribute");
2022 Extension = new PredefinedAttribute ("System.Runtime.CompilerServices", "ExtensionAttribute");
2024 DefaultMember = new PredefinedAttribute ("System.Reflection", "DefaultMemberAttribute");
2025 DecimalConstant = new PredefinedAttribute ("System.Runtime.CompilerServices", "DecimalConstantAttribute");
2026 StructLayout = new PredefinedAttribute ("System.Runtime.InteropServices", "StructLayoutAttribute");
2027 FieldOffset = new PredefinedAttribute ("System.Runtime.InteropServices", "FieldOffsetAttribute");
2030 public void Initialize ()
2032 foreach (FieldInfo fi in GetType ().GetFields (BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly)) {
2033 ((PredefinedAttribute) fi.GetValue (this)).Resolve (true);
2037 public static void Reset ()
2039 Get = new PredefinedAttributes ();
2043 public class PredefinedAttribute
2046 CustomAttributeBuilder cab;
2047 ConstructorInfo ctor;
2048 readonly string ns, name;
2050 public PredefinedAttribute (string ns, string name)
2056 public static bool operator == (Type type, PredefinedAttribute pa)
2058 return type == pa.type;
2061 public static bool operator != (Type type, PredefinedAttribute pa)
2063 return type != pa.type;
2066 public ConstructorInfo Constructor {
2067 get { return ctor; }
2070 public override int GetHashCode ()
2072 return base.GetHashCode ();
2075 public override bool Equals (object obj)
2077 throw new NotSupportedException ();
2080 public void EmitAttribute (ConstructorBuilder builder)
2082 if (ResolveBuilder ())
2083 builder.SetCustomAttribute (cab);
2086 public void EmitAttribute (MethodBuilder builder)
2088 if (ResolveBuilder ())
2089 builder.SetCustomAttribute (cab);
2092 public void EmitAttribute (FieldBuilder builder)
2094 if (ResolveBuilder ())
2095 builder.SetCustomAttribute (cab);
2098 public void EmitAttribute (TypeBuilder builder)
2100 if (ResolveBuilder ())
2101 builder.SetCustomAttribute (cab);
2104 public void EmitAttribute (AssemblyBuilder builder)
2106 if (ResolveBuilder ())
2107 builder.SetCustomAttribute (cab);
2110 public void EmitAttribute (ParameterBuilder builder, Location loc)
2112 if (ResolveBuilder ())
2113 builder.SetCustomAttribute (cab);
2116 public bool IsDefined {
2117 get { return type != null && type != typeof (PredefinedAttribute); }
2120 public bool Resolve (bool canFail)
2129 type = TypeManager.CoreLookupType (ns, name, Kind.Class, !canFail);
2131 type = typeof (PredefinedAttribute);
2138 bool ResolveBuilder ()
2144 // Handle all parameter-less attributes as optional
2146 if (!Resolve (true))
2149 ConstructorInfo ci = TypeManager.GetPredefinedConstructor (type, Location.Null, Type.EmptyTypes);
2153 cab = new CustomAttributeBuilder (ci, new object[0]);
2157 public bool ResolveConstructor (Location loc, params Type[] argType)
2160 throw new InternalErrorException ("Predefined ctor redefined");
2162 if (!Resolve (false))
2165 ctor = TypeManager.GetPredefinedConstructor (type, loc, argType);
2166 return ctor != null;
2170 get { return type; }