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 Arguments PosArguments;
129 Arguments 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, Arguments[] args, Location loc, bool nameEscaped)
154 LeftExpr = left_expr;
155 Identifier = identifier;
156 Name = LeftExpr == null ? identifier : LeftExpr + "." + identifier;
158 PosArguments = args [0];
159 NamedArguments = 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 (NamedArgument name)
205 Report.Error (617, name.Name.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_InvalidNamedArgumentType (NamedArgument name)
213 Report.Error (655, name.Name.Location,
214 "`{0}' is not a valid named attribute argument because it is not a valid attribute parameter type",
218 public static void Error_AttributeArgumentNotValid (Location loc)
220 Report.Error (182, loc,
221 "An attribute argument must be a constant expression, typeof " +
222 "expression or array creation expression");
225 static void Error_TypeParameterInAttribute (Location loc)
228 -202, loc, "Can not use a type parameter in an attribute");
231 public void Error_MissingGuidAttribute ()
233 Report.Error (596, Location, "The Guid attribute must be specified with the ComImport attribute");
236 public void Error_MisusedExtensionAttribute ()
238 Report.Error (1112, Location, "Do not use `{0}' directly. Use parameter modifier `this' instead", GetSignatureForError ());
242 /// This is rather hack. We report many emit attribute error with same error to be compatible with
243 /// csc. But because csc has to report them this way because error came from ilasm we needn't.
245 public void Error_AttributeEmitError (string inner)
247 Report.Error (647, Location, "Error during emitting `{0}' attribute. The reason is `{1}'",
248 TypeManager.CSharpName (Type), inner);
251 public void Error_InvalidSecurityParent ()
253 Error_AttributeEmitError ("it is attached to invalid parent");
262 protected virtual TypeExpr ResolveAsTypeTerminal (Expression expr, IResolveContext ec, bool silent)
264 return expr.ResolveAsTypeTerminal (ec, silent);
267 Type ResolvePossibleAttributeType (string name, bool silent, ref bool is_attr)
269 IResolveContext rc = new AttributeResolveContext (Owner.ResolveContext);
272 if (LeftExpr == null) {
273 te = ResolveAsTypeTerminal (new SimpleName (name, Location), rc, silent);
275 te = ResolveAsTypeTerminal (new MemberAccess (LeftExpr, name), rc, silent);
282 if (TypeManager.IsSubclassOf (t, TypeManager.attribute_type)) {
284 } else if (!silent) {
285 Report.SymbolRelatedToPreviousError (t);
286 Report.Error (616, Location, "`{0}': is not an attribute class", TypeManager.CSharpName (t));
292 /// Tries to resolve the type of the attribute. Flags an error if it can't, and complain is true.
294 void ResolveAttributeType ()
296 bool t1_is_attr = false;
297 Type t1 = ResolvePossibleAttributeType (Identifier, true, ref t1_is_attr);
299 bool t2_is_attr = false;
300 Type t2 = nameEscaped ? null :
301 ResolvePossibleAttributeType (Identifier + "Attribute", true, ref t2_is_attr);
303 if (t1_is_attr && t2_is_attr) {
304 Report.Error (1614, Location, "`{0}' is ambiguous between `{0}' and `{0}Attribute'. " +
305 "Use either `@{0}' or `{0}Attribute'", GetSignatureForError ());
306 resolve_error = true;
320 if (t1 == null && t2 == null)
321 ResolvePossibleAttributeType (Identifier, false, ref t1_is_attr);
323 ResolvePossibleAttributeType (Identifier, false, ref t1_is_attr);
325 ResolvePossibleAttributeType (Identifier + "Attribute", false, ref t2_is_attr);
327 resolve_error = true;
330 public virtual Type ResolveType ()
332 if (Type == null && !resolve_error)
333 ResolveAttributeType ();
337 public override string GetSignatureForError ()
340 return TypeManager.CSharpName (Type);
342 return LeftExpr == null ? Identifier : LeftExpr.GetSignatureForError () + "." + Identifier;
345 public bool HasSecurityAttribute {
347 PredefinedAttribute pa = PredefinedAttributes.Get.Security;
348 return pa.IsDefined && TypeManager.IsSubclassOf (type, pa.Type);
352 public bool IsValidSecurityAttribute ()
354 return HasSecurityAttribute && IsSecurityActionValid (false);
357 static bool IsValidArgumentType (Type t)
360 t = TypeManager.GetElementType (t);
362 return t == TypeManager.string_type ||
363 TypeManager.IsPrimitiveType (t) ||
364 TypeManager.IsEnumType (t) ||
365 t == TypeManager.object_type ||
366 t == TypeManager.type_type;
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 Arguments (1);
381 foreach (NamedArgument a in NamedArguments) {
382 if (a.Name.Value == CharSetEnumMember)
387 NamedArguments.Add (new NamedArgument (new LocatedToken (loc, CharSetEnumMember),
388 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) {
480 PosArguments.Resolve (ec, out dynamic);
482 throw new NotImplementedException ("dynamic");
485 MethodGroupExpr mg = MemberLookupFinal (ec, ec.ContainerType,
486 Type, ConstructorInfo.ConstructorName, MemberTypes.Constructor,
487 BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly,
488 Location) as MethodGroupExpr;
491 throw new NotImplementedException ();
493 mg = mg.OverloadResolve (ec, ref PosArguments, false, Location);
497 ConstructorInfo constructor = (ConstructorInfo)mg;
498 if (PosArguments == null) {
499 pos_values = EmptyObject;
503 AParametersCollection pd = TypeManager.GetParameterData (constructor);
505 if (!PosArguments.GetAttributableValue (ec, out pos_values))
508 // Here we do the checks which should be done by corlib or by runtime.
509 // However Zoltan doesn't like it and every Mono compiler has to do it again.
510 PredefinedAttributes pa = PredefinedAttributes.Get;
511 if (Type == pa.Guid) {
513 new Guid ((string)pos_values [0]);
515 catch (Exception e) {
516 Error_AttributeEmitError (e.Message);
521 if (Type == pa.AttributeUsage && (int)pos_values [0] == 0) {
522 Report.Error (591, Location, "Invalid value for argument to `System.AttributeUsage' attribute");
526 if (Type == pa.IndexerName || Type == pa.Conditional) {
527 string v = pos_values [0] as string;
528 if (!Tokenizer.IsValidIdentifier (v) || Tokenizer.IsKeyword (v)) {
529 Report.Error (633, PosArguments [0].Expr.Location,
530 "The argument to the `{0}' attribute must be a valid identifier", GetSignatureForError ());
535 if (Type == pa.MethodImpl && pos_values.Length == 1 &&
536 pd.Types [0] == TypeManager.short_type &&
537 !System.Enum.IsDefined (typeof (MethodImplOptions), pos_values [0].ToString ())) {
538 Error_AttributeEmitError ("Incorrect argument value.");
545 protected virtual bool ResolveNamedArguments (EmitContext ec)
547 int named_arg_count = NamedArguments.Count;
549 ArrayList field_infos = new ArrayList (named_arg_count);
550 ArrayList prop_infos = new ArrayList (named_arg_count);
551 ArrayList field_values = new ArrayList (named_arg_count);
552 ArrayList prop_values = new ArrayList (named_arg_count);
554 ArrayList seen_names = new ArrayList (named_arg_count);
556 foreach (NamedArgument a in NamedArguments) {
557 string name = a.Name.Value;
558 if (seen_names.Contains (name)) {
559 Report.Error (643, a.Name.Location, "Duplicate named attribute `{0}' argument", name);
563 seen_names.Add (name);
567 Expression member = Expression.MemberLookup (
568 ec.ContainerType, Type, name,
570 BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static,
573 if (member == null) {
574 member = Expression.MemberLookup (ec.ContainerType, Type, name,
575 MemberTypes.All, BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static,
578 if (member != null) {
579 Report.SymbolRelatedToPreviousError (member.Type);
580 Expression.ErrorIsInaccesible (Location, member.GetSignatureForError ());
586 Expression.Error_TypeDoesNotContainDefinition (Location, Type, name);
590 if (!(member is PropertyExpr || member is FieldExpr)) {
591 Error_InvalidNamedArgument (a);
595 if (a.Expr is TypeParameterExpr){
596 Error_TypeParameterInAttribute (Location);
600 ObsoleteAttribute obsolete_attr;
602 if (member is PropertyExpr) {
603 PropertyInfo pi = ((PropertyExpr) member).PropertyInfo;
605 if (!pi.CanWrite || !pi.CanRead || pi.GetGetMethod ().IsStatic) {
606 Report.SymbolRelatedToPreviousError (pi);
607 Error_InvalidNamedArgument (a);
611 if (!IsValidArgumentType (member.Type)) {
612 Report.SymbolRelatedToPreviousError (pi);
613 Error_InvalidNamedArgumentType (a);
618 if (!a.Expr.GetAttributableValue (ec, member.Type, out value))
621 PropertyBase pb = TypeManager.GetProperty (pi);
623 obsolete_attr = pb.GetObsoleteAttribute ();
625 obsolete_attr = AttributeTester.GetMemberObsoleteAttribute (pi);
627 prop_values.Add (value);
631 FieldInfo fi = ((FieldExpr) member).FieldInfo;
633 if (fi.IsInitOnly || fi.IsStatic) {
634 Error_InvalidNamedArgument (a);
638 if (!IsValidArgumentType (member.Type)) {
639 Report.SymbolRelatedToPreviousError (fi);
640 Error_InvalidNamedArgumentType (a);
645 if (!a.Expr.GetAttributableValue (ec, member.Type, out value))
648 FieldBase fb = TypeManager.GetField (fi);
650 obsolete_attr = fb.GetObsoleteAttribute ();
652 obsolete_attr = AttributeTester.GetMemberObsoleteAttribute (fi);
654 field_values.Add (value);
655 field_infos.Add (fi);
658 if (obsolete_attr != null && !Owner.ResolveContext.IsInObsoleteScope)
659 AttributeTester.Report_ObsoleteMessage (obsolete_attr, member.GetSignatureForError (), member.Location);
662 prop_info_arr = new PropertyInfo [prop_infos.Count];
663 field_info_arr = new FieldInfo [field_infos.Count];
664 field_values_arr = new object [field_values.Count];
665 prop_values_arr = new object [prop_values.Count];
667 field_infos.CopyTo (field_info_arr, 0);
668 field_values.CopyTo (field_values_arr, 0);
670 prop_values.CopyTo (prop_values_arr, 0);
671 prop_infos.CopyTo (prop_info_arr, 0);
677 /// Get a string containing a list of valid targets for the attribute 'attr'
679 public string GetValidTargets ()
681 StringBuilder sb = new StringBuilder ();
682 AttributeTargets targets = GetAttributeUsage (Type).ValidOn;
684 if ((targets & AttributeTargets.Assembly) != 0)
685 sb.Append ("assembly, ");
687 if ((targets & AttributeTargets.Module) != 0)
688 sb.Append ("module, ");
690 if ((targets & AttributeTargets.Class) != 0)
691 sb.Append ("class, ");
693 if ((targets & AttributeTargets.Struct) != 0)
694 sb.Append ("struct, ");
696 if ((targets & AttributeTargets.Enum) != 0)
697 sb.Append ("enum, ");
699 if ((targets & AttributeTargets.Constructor) != 0)
700 sb.Append ("constructor, ");
702 if ((targets & AttributeTargets.Method) != 0)
703 sb.Append ("method, ");
705 if ((targets & AttributeTargets.Property) != 0)
706 sb.Append ("property, indexer, ");
708 if ((targets & AttributeTargets.Field) != 0)
709 sb.Append ("field, ");
711 if ((targets & AttributeTargets.Event) != 0)
712 sb.Append ("event, ");
714 if ((targets & AttributeTargets.Interface) != 0)
715 sb.Append ("interface, ");
717 if ((targets & AttributeTargets.Parameter) != 0)
718 sb.Append ("parameter, ");
720 if ((targets & AttributeTargets.Delegate) != 0)
721 sb.Append ("delegate, ");
723 if ((targets & AttributeTargets.ReturnValue) != 0)
724 sb.Append ("return, ");
727 if ((targets & AttributeTargets.GenericParameter) != 0)
728 sb.Append ("type parameter, ");
730 return sb.Remove (sb.Length - 2, 2).ToString ();
734 /// Returns AttributeUsage attribute based on types hierarchy
736 static AttributeUsageAttribute GetAttributeUsage (Type type)
738 AttributeUsageAttribute ua = usage_attr_cache [type] as AttributeUsageAttribute;
742 Class attr_class = TypeManager.LookupClass (type);
743 PredefinedAttribute pa = PredefinedAttributes.Get.AttributeUsage;
745 if (attr_class == null) {
747 return new AttributeUsageAttribute (0);
749 object[] usage_attr = type.GetCustomAttributes (pa.Type, true);
750 ua = (AttributeUsageAttribute)usage_attr [0];
751 usage_attr_cache.Add (type, ua);
756 if (attr_class.OptAttributes != null)
757 a = attr_class.OptAttributes.Search (pa);
760 if (attr_class.TypeBuilder.BaseType != TypeManager.attribute_type)
761 ua = GetAttributeUsage (attr_class.TypeBuilder.BaseType);
763 ua = DefaultUsageAttribute;
765 ua = a.GetAttributeUsageAttribute ();
768 usage_attr_cache.Add (type, ua);
772 AttributeUsageAttribute GetAttributeUsageAttribute ()
774 if (pos_values == null)
775 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
776 // But because a lot of attribute class code must be rewritten will be better to wait...
780 return DefaultUsageAttribute;
782 AttributeUsageAttribute usage_attribute = new AttributeUsageAttribute ((AttributeTargets)pos_values [0]);
784 object field = GetPropertyValue ("AllowMultiple");
786 usage_attribute.AllowMultiple = (bool)field;
788 field = GetPropertyValue ("Inherited");
790 usage_attribute.Inherited = (bool)field;
792 return usage_attribute;
796 /// Returns custom name of indexer
798 public string GetIndexerAttributeValue ()
800 if (pos_values == null)
801 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
802 // But because a lot of attribute class code must be rewritten will be better to wait...
808 return pos_values [0] as string;
812 /// Returns condition of ConditionalAttribute
814 public string GetConditionalAttributeValue ()
816 if (pos_values == null)
817 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
818 // But because a lot of attribute class code must be rewritten will be better to wait...
824 return (string)pos_values [0];
828 /// Creates the instance of ObsoleteAttribute from this attribute instance
830 public ObsoleteAttribute GetObsoleteAttribute ()
832 if (pos_values == null)
833 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
834 // But because a lot of attribute class code must be rewritten will be better to wait...
840 if (pos_values == null || pos_values.Length == 0)
841 return new ObsoleteAttribute ();
843 if (pos_values.Length == 1)
844 return new ObsoleteAttribute ((string)pos_values [0]);
846 return new ObsoleteAttribute ((string)pos_values [0], (bool)pos_values [1]);
850 /// Returns value of CLSCompliantAttribute contructor parameter but because the method can be called
851 /// before ApplyAttribute. We need to resolve the arguments.
852 /// This situation occurs when class deps is differs from Emit order.
854 public bool GetClsCompliantAttributeValue ()
856 if (pos_values == null)
857 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
858 // But because a lot of attribute class code must be rewritten will be better to wait...
864 return (bool)pos_values [0];
867 public Type GetCoClassAttributeValue ()
869 if (pos_values == null)
875 return (Type)pos_values [0];
878 public bool CheckTarget ()
880 string[] valid_targets = Owner.ValidAttributeTargets;
881 if (ExplicitTarget == null || ExplicitTarget == valid_targets [0]) {
882 Target = Owner.AttributeTargets;
886 // TODO: we can skip the first item
887 if (((IList) valid_targets).Contains (ExplicitTarget)) {
888 switch (ExplicitTarget) {
889 case "return": Target = AttributeTargets.ReturnValue; return true;
890 case "param": Target = AttributeTargets.Parameter; return true;
891 case "field": Target = AttributeTargets.Field; return true;
892 case "method": Target = AttributeTargets.Method; return true;
893 case "property": Target = AttributeTargets.Property; return true;
895 throw new InternalErrorException ("Unknown explicit target: " + ExplicitTarget);
898 StringBuilder sb = new StringBuilder ();
899 foreach (string s in valid_targets) {
903 sb.Remove (sb.Length - 2, 2);
904 Report.Error (657, Location, "`{0}' is not a valid attribute location for this declaration. " +
905 "Valid attribute locations for this declaration are `{1}'", ExplicitTarget, sb.ToString ());
910 /// Tests permitted SecurityAction for assembly or other types
912 protected virtual bool IsSecurityActionValid (bool for_assembly)
914 SecurityAction action = GetSecurityActionValue ();
917 case SecurityAction.Demand:
918 case SecurityAction.Assert:
919 case SecurityAction.Deny:
920 case SecurityAction.PermitOnly:
921 case SecurityAction.LinkDemand:
922 case SecurityAction.InheritanceDemand:
927 case SecurityAction.RequestMinimum:
928 case SecurityAction.RequestOptional:
929 case SecurityAction.RequestRefuse:
935 Error_AttributeEmitError ("SecurityAction is out of range");
939 Error_AttributeEmitError (String.Concat ("SecurityAction `", action, "' is not valid for this declaration"));
943 System.Security.Permissions.SecurityAction GetSecurityActionValue ()
945 return (SecurityAction)pos_values [0];
949 /// Creates instance of SecurityAttribute class and add result of CreatePermission method to permission table.
951 /// <returns></returns>
952 public void ExtractSecurityPermissionSet (ListDictionary permissions)
954 Type orig_assembly_type = null;
956 if (TypeManager.LookupDeclSpace (Type) != null) {
957 if (!RootContext.StdLib) {
958 orig_assembly_type = Type.GetType (Type.FullName);
960 string orig_version_path = Environment.GetEnvironmentVariable ("__SECURITY_BOOTSTRAP_DB");
961 if (orig_version_path == null) {
962 Error_AttributeEmitError ("security custom attributes can not be referenced from defining assembly");
966 if (orig_sec_assembly == null) {
967 string file = Path.Combine (orig_version_path, Driver.OutputFile);
968 orig_sec_assembly = Assembly.LoadFile (file);
971 orig_assembly_type = orig_sec_assembly.GetType (Type.FullName, true);
972 if (orig_assembly_type == null) {
973 Report.Warning (-112, 1, Location, "Self-referenced security attribute `{0}' " +
974 "was not found in previous version of assembly");
980 SecurityAttribute sa;
981 // For all non-selfreferencing security attributes we can avoid all hacks
982 if (orig_assembly_type == null) {
983 sa = (SecurityAttribute) Activator.CreateInstance (Type, pos_values);
985 if (prop_info_arr != null) {
986 for (int i = 0; i < prop_info_arr.Length; ++i) {
987 PropertyInfo pi = prop_info_arr [i];
988 pi.SetValue (sa, prop_values_arr [i], null);
992 // HACK: All security attributes have same ctor syntax
993 sa = (SecurityAttribute) Activator.CreateInstance (orig_assembly_type, new object[] { GetSecurityActionValue () } );
995 // All types are from newly created assembly but for invocation with old one we need to convert them
996 if (prop_info_arr != null) {
997 for (int i = 0; i < prop_info_arr.Length; ++i) {
998 PropertyInfo emited_pi = prop_info_arr [i];
999 // FIXME: We are missing return type filter
1000 // TODO: pi can be null
1001 PropertyInfo pi = orig_assembly_type.GetProperty (emited_pi.Name);
1003 object old_instance = TypeManager.IsEnumType (pi.PropertyType) ?
1004 System.Enum.ToObject (pi.PropertyType, prop_values_arr [i]) :
1005 prop_values_arr [i];
1007 pi.SetValue (sa, old_instance, null);
1013 perm = sa.CreatePermission ();
1014 SecurityAction action = GetSecurityActionValue ();
1016 // IS is correct because for corlib we are using an instance from old corlib
1017 if (!(perm is System.Security.CodeAccessPermission)) {
1019 case SecurityAction.Demand:
1020 action = (SecurityAction)13;
1022 case SecurityAction.LinkDemand:
1023 action = (SecurityAction)14;
1025 case SecurityAction.InheritanceDemand:
1026 action = (SecurityAction)15;
1031 PermissionSet ps = (PermissionSet)permissions [action];
1033 if (sa is PermissionSetAttribute)
1034 ps = new PermissionSet (sa.Unrestricted ? PermissionState.Unrestricted : PermissionState.None);
1036 ps = new PermissionSet (PermissionState.None);
1038 permissions.Add (action, ps);
1039 } else if (!ps.IsUnrestricted () && (sa is PermissionSetAttribute) && sa.Unrestricted) {
1040 ps = ps.Union (new PermissionSet (PermissionState.Unrestricted));
1041 permissions [action] = ps;
1043 ps.AddPermission (perm);
1046 public object GetPropertyValue (string name)
1048 if (prop_info_arr == null)
1051 for (int i = 0; i < prop_info_arr.Length; ++i) {
1052 if (prop_info_arr [i].Name == name)
1053 return prop_values_arr [i];
1060 // Theoretically, we can get rid of this, since FieldBuilder.SetCustomAttribute()
1061 // and ParameterBuilder.SetCustomAttribute() are supposed to handle this attribute.
1062 // However, we can't, since it appears that the .NET 1.1 SRE hangs when given a MarshalAsAttribute.
1065 public UnmanagedMarshal GetMarshal (Attributable attr)
1067 UnmanagedType UnmanagedType;
1068 if (!RootContext.StdLib || pos_values [0].GetType () != typeof (UnmanagedType))
1069 UnmanagedType = (UnmanagedType) System.Enum.ToObject (typeof (UnmanagedType), pos_values [0]);
1071 UnmanagedType = (UnmanagedType) pos_values [0];
1073 object value = GetFieldValue ("SizeParamIndex");
1074 if (value != null && UnmanagedType != UnmanagedType.LPArray) {
1075 Error_AttributeEmitError ("SizeParamIndex field is not valid for the specified unmanaged type");
1079 object o = GetFieldValue ("ArraySubType");
1080 UnmanagedType array_sub_type = o == null ? (UnmanagedType) 0x50 /* NATIVE_MAX */ : (UnmanagedType) o;
1082 switch (UnmanagedType) {
1083 case UnmanagedType.CustomMarshaler: {
1084 MethodInfo define_custom = typeof (UnmanagedMarshal).GetMethod ("DefineCustom",
1085 BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
1086 if (define_custom == null) {
1087 Report.RuntimeMissingSupport (Location, "set marshal info");
1091 object [] args = new object [4];
1092 args [0] = GetFieldValue ("MarshalTypeRef");
1093 args [1] = GetFieldValue ("MarshalCookie");
1094 args [2] = GetFieldValue ("MarshalType");
1095 args [3] = Guid.Empty;
1096 return (UnmanagedMarshal) define_custom.Invoke (null, args);
1098 case UnmanagedType.LPArray: {
1099 object size_const = GetFieldValue ("SizeConst");
1100 object size_param_index = GetFieldValue ("SizeParamIndex");
1102 if ((size_const != null) || (size_param_index != null)) {
1103 MethodInfo define_array = typeof (UnmanagedMarshal).GetMethod ("DefineLPArrayInternal",
1104 BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
1105 if (define_array == null) {
1106 Report.RuntimeMissingSupport (Location, "set marshal info");
1110 object [] args = new object [3];
1111 args [0] = array_sub_type;
1112 args [1] = size_const == null ? -1 : size_const;
1113 args [2] = size_param_index == null ? -1 : size_param_index;
1114 return (UnmanagedMarshal) define_array.Invoke (null, args);
1117 return UnmanagedMarshal.DefineLPArray (array_sub_type);
1119 case UnmanagedType.SafeArray:
1120 return UnmanagedMarshal.DefineSafeArray (array_sub_type);
1122 case UnmanagedType.ByValArray:
1123 FieldBase fm = attr as FieldBase;
1125 Error_AttributeEmitError ("Specified unmanaged type is only valid on fields");
1128 return UnmanagedMarshal.DefineByValArray ((int) GetFieldValue ("SizeConst"));
1130 case UnmanagedType.ByValTStr:
1131 return UnmanagedMarshal.DefineByValTStr ((int) GetFieldValue ("SizeConst"));
1134 return UnmanagedMarshal.DefineUnmanagedMarshal (UnmanagedType);
1138 object GetFieldValue (string name)
1141 if (field_info_arr == null)
1144 foreach (FieldInfo fi in field_info_arr) {
1145 if (fi.Name == name)
1146 return GetValue (field_values_arr [i]);
1152 static object GetValue (object value)
1154 if (value is EnumConstant)
1155 return ((EnumConstant) value).GetValue ();
1162 public CharSet GetCharSetValue ()
1164 return (CharSet)System.Enum.Parse (typeof (CharSet), pos_values [0].ToString ());
1167 public bool HasField (string fieldName)
1169 if (field_info_arr == null)
1172 foreach (FieldInfo fi in field_info_arr) {
1173 if (fi.Name == fieldName)
1180 public bool IsInternalMethodImplAttribute {
1182 if (Type != PredefinedAttributes.Get.MethodImpl)
1185 MethodImplOptions options;
1186 if (pos_values[0].GetType () != typeof (MethodImplOptions))
1187 options = (MethodImplOptions)System.Enum.ToObject (typeof (MethodImplOptions), pos_values[0]);
1189 options = (MethodImplOptions)pos_values[0];
1191 return (options & MethodImplOptions.InternalCall) != 0;
1195 public LayoutKind GetLayoutKindValue ()
1197 if (!RootContext.StdLib || pos_values [0].GetType () != typeof (LayoutKind))
1198 return (LayoutKind)System.Enum.ToObject (typeof (LayoutKind), pos_values [0]);
1200 return (LayoutKind)pos_values [0];
1203 public object GetParameterDefaultValue ()
1205 return pos_values [0];
1208 public override bool Equals (object obj)
1210 Attribute a = obj as Attribute;
1214 return Type == a.Type && Target == a.Target;
1217 public override int GetHashCode ()
1219 return base.GetHashCode ();
1223 /// Emit attribute for Attributable symbol
1225 public void Emit (ListDictionary allEmitted)
1227 CustomAttributeBuilder cb = Resolve ();
1231 AttributeUsageAttribute usage_attr = GetAttributeUsage (Type);
1232 if ((usage_attr.ValidOn & Target) == 0) {
1233 Report.Error (592, Location, "The attribute `{0}' is not valid on this declaration type. " +
1234 "It is valid on `{1}' declarations only",
1235 GetSignatureForError (), GetValidTargets ());
1240 foreach (Attributable owner in owners)
1241 owner.ApplyAttributeBuilder (this, cb, PredefinedAttributes.Get);
1243 catch (Exception e) {
1244 Error_AttributeEmitError (e.Message);
1248 if (!usage_attr.AllowMultiple && allEmitted != null) {
1249 if (allEmitted.Contains (this)) {
1250 ArrayList a = allEmitted [this] as ArrayList;
1252 a = new ArrayList (2);
1253 allEmitted [this] = a;
1257 allEmitted.Add (this, null);
1261 if (!RootContext.VerifyClsCompliance)
1264 // Here we are testing attribute arguments for array usage (error 3016)
1265 if (Owner.IsClsComplianceRequired ()) {
1266 if (PosArguments != null)
1267 PosArguments.CheckArrayAsAttribute ();
1269 if (NamedArguments == null)
1272 NamedArguments.CheckArrayAsAttribute ();
1276 private Expression GetValue ()
1278 if (PosArguments == null || PosArguments.Count < 1)
1281 return PosArguments [0].Expr;
1284 public string GetString ()
1286 Expression e = GetValue ();
1287 if (e is StringConstant)
1288 return ((StringConstant)e).Value;
1292 public bool GetBoolean ()
1294 Expression e = GetValue ();
1295 if (e is BoolConstant)
1296 return ((BoolConstant)e).Value;
1300 public Type GetArgumentType ()
1302 TypeOf e = GetValue () as TypeOf;
1305 return e.TypeArgument;
1308 public override Expression CreateExpressionTree (EmitContext ec)
1310 throw new NotSupportedException ("ET");
1313 public override Expression DoResolve (EmitContext ec)
1315 throw new NotImplementedException ();
1318 public override void Emit (EmitContext ec)
1320 throw new NotImplementedException ();
1326 /// For global attributes (assembly, module) we need special handling.
1327 /// Attributes can be located in the several files
1329 public class GlobalAttribute : Attribute
1331 public readonly NamespaceEntry ns;
1333 public GlobalAttribute (NamespaceEntry ns, string target,
1334 Expression left_expr, string identifier, Arguments[] args, Location loc, bool nameEscaped):
1335 base (target, left_expr, identifier, args, loc, nameEscaped)
1338 this.owners = new Attributable[1];
1341 public override void AttachTo (Attributable owner)
1343 if (ExplicitTarget == "assembly") {
1344 owners [0] = CodeGen.Assembly;
1347 if (ExplicitTarget == "module") {
1348 owners [0] = RootContext.ToplevelTypes;
1351 throw new NotImplementedException ("Unknown global explicit target " + ExplicitTarget);
1356 // RootContext.ToplevelTypes has a single NamespaceEntry which gets overwritten
1357 // each time a new file is parsed. However, we need to use the NamespaceEntry
1358 // in effect where the attribute was used. Since code elsewhere cannot assume
1359 // that the NamespaceEntry is right, just overwrite it.
1361 // Precondition: RootContext.ToplevelTypes == null
1363 if (RootContext.ToplevelTypes.NamespaceEntry != null)
1364 throw new InternalErrorException (Location + " non-null NamespaceEntry");
1366 RootContext.ToplevelTypes.NamespaceEntry = ns;
1369 protected override bool IsSecurityActionValid (bool for_assembly)
1371 return base.IsSecurityActionValid (true);
1376 RootContext.ToplevelTypes.NamespaceEntry = null;
1379 protected override TypeExpr ResolveAsTypeTerminal (Expression expr, IResolveContext ec, bool silent)
1383 return base.ResolveAsTypeTerminal (expr, ec, silent);
1390 protected override ConstructorInfo ResolveConstructor (EmitContext ec)
1394 return base.ResolveConstructor (ec);
1401 protected override bool ResolveNamedArguments (EmitContext ec)
1405 return base.ResolveNamedArguments (ec);
1413 public class Attributes {
1414 public readonly ArrayList Attrs;
1416 public Attributes (Attribute a)
1418 Attrs = new ArrayList ();
1422 public Attributes (ArrayList attrs)
1427 public void AddAttributes (ArrayList attrs)
1429 Attrs.AddRange (attrs);
1432 public void AttachTo (Attributable attributable)
1434 foreach (Attribute a in Attrs)
1435 a.AttachTo (attributable);
1438 public Attributes Clone ()
1440 ArrayList al = new ArrayList (Attrs.Count);
1441 foreach (Attribute a in Attrs)
1442 al.Add (a.Clone ());
1444 return new Attributes (al);
1448 /// Checks whether attribute target is valid for the current element
1450 public bool CheckTargets ()
1452 foreach (Attribute a in Attrs) {
1453 if (!a.CheckTarget ())
1459 public Attribute Search (PredefinedAttribute t)
1461 foreach (Attribute a in Attrs) {
1462 if (a.ResolveType () == t)
1469 /// Returns all attributes of type 't'. Use it when attribute is AllowMultiple = true
1471 public Attribute[] SearchMulti (PredefinedAttribute t)
1473 ArrayList ar = null;
1475 foreach (Attribute a in Attrs) {
1476 if (a.ResolveType () == t) {
1478 ar = new ArrayList ();
1483 return ar == null ? null : ar.ToArray (typeof (Attribute)) as Attribute[];
1490 ListDictionary ld = Attrs.Count > 1 ? new ListDictionary () : null;
1492 foreach (Attribute a in Attrs)
1495 if (ld == null || ld.Count == 0)
1498 foreach (DictionaryEntry d in ld) {
1499 if (d.Value == null)
1502 foreach (Attribute collision in (ArrayList)d.Value)
1503 Report.SymbolRelatedToPreviousError (collision.Location, "");
1505 Attribute a = (Attribute)d.Key;
1506 Report.Error (579, a.Location, "The attribute `{0}' cannot be applied multiple times",
1507 a.GetSignatureForError ());
1511 public bool Contains (PredefinedAttribute t)
1513 return Search (t) != null;
1518 /// Helper class for attribute verification routine.
1520 sealed class AttributeTester
1522 static PtrHashtable analyzed_types;
1523 static PtrHashtable analyzed_types_obsolete;
1524 static PtrHashtable analyzed_member_obsolete;
1525 static PtrHashtable analyzed_method_excluded;
1526 static PtrHashtable fixed_buffer_cache;
1528 static object TRUE = new object ();
1529 static object FALSE = new object ();
1531 static AttributeTester ()
1536 private AttributeTester ()
1540 public static void Reset ()
1542 analyzed_types = new PtrHashtable ();
1543 analyzed_types_obsolete = new PtrHashtable ();
1544 analyzed_member_obsolete = new PtrHashtable ();
1545 analyzed_method_excluded = new PtrHashtable ();
1546 fixed_buffer_cache = new PtrHashtable ();
1549 public enum Result {
1556 /// Returns true if parameters of two compared methods are CLS-Compliant.
1557 /// It tests differing only in ref or out, or in array rank.
1559 public static Result AreOverloadedMethodParamsClsCompliant (AParametersCollection pa, AParametersCollection pb)
1561 Type [] types_a = pa.Types;
1562 Type [] types_b = pb.Types;
1563 if (types_a == null || types_b == null)
1566 if (types_a.Length != types_b.Length)
1569 Result result = Result.Ok;
1570 for (int i = 0; i < types_b.Length; ++i) {
1571 Type aType = types_a [i];
1572 Type bType = types_b [i];
1574 if (aType.IsArray && bType.IsArray) {
1575 Type a_el_type = TypeManager.GetElementType (aType);
1576 Type b_el_type = TypeManager.GetElementType (bType);
1577 if (aType.GetArrayRank () != bType.GetArrayRank () && a_el_type == b_el_type) {
1578 result = Result.RefOutArrayError;
1582 if (a_el_type.IsArray || b_el_type.IsArray) {
1583 result = Result.ArrayArrayError;
1591 const Parameter.Modifier out_ref_mod = (Parameter.Modifier.OUTMASK | Parameter.Modifier.REFMASK);
1592 if ((pa.FixedParameters[i].ModFlags & out_ref_mod) != (pb.FixedParameters[i].ModFlags & out_ref_mod))
1593 result = Result.RefOutArrayError;
1599 /// This method tests the CLS compliance of external types. It doesn't test type visibility.
1601 public static bool IsClsCompliant (Type type)
1606 object type_compliance = analyzed_types[type];
1607 if (type_compliance != null)
1608 return type_compliance == TRUE;
1610 if (type.IsPointer) {
1611 analyzed_types.Add (type, FALSE);
1617 result = IsClsCompliant (TypeManager.GetElementType (type));
1618 } else if (TypeManager.IsNullableType (type)) {
1619 result = IsClsCompliant (TypeManager.TypeToCoreType (TypeManager.GetTypeArguments (type) [0]));
1621 result = AnalyzeTypeCompliance (type);
1623 analyzed_types.Add (type, result ? TRUE : FALSE);
1628 /// Returns IFixedBuffer implementation if field is fixed buffer else null.
1630 public static IFixedBuffer GetFixedBuffer (FieldInfo fi)
1632 // Fixed buffer helper type is generated as value type
1633 if (TypeManager.IsReferenceType (fi.FieldType))
1636 FieldBase fb = TypeManager.GetField (fi);
1638 return fb as IFixedBuffer;
1641 if (TypeManager.GetConstant (fi) != null)
1644 object o = fixed_buffer_cache [fi];
1646 PredefinedAttribute pa = PredefinedAttributes.Get.FixedBuffer;
1650 if (!fi.IsDefined (pa.Type, false)) {
1651 fixed_buffer_cache.Add (fi, FALSE);
1655 IFixedBuffer iff = new FixedFieldExternal (fi);
1656 fixed_buffer_cache.Add (fi, iff);
1663 return (IFixedBuffer)o;
1666 public static void VerifyModulesClsCompliance ()
1668 Module[] modules = GlobalRootNamespace.Instance.Modules;
1669 if (modules == null)
1672 // The first module is generated assembly
1673 for (int i = 1; i < modules.Length; ++i) {
1674 Module module = modules [i];
1675 if (!GetClsCompliantAttributeValue (module, null)) {
1676 Report.Error (3013, "Added modules must be marked with the CLSCompliant attribute " +
1677 "to match the assembly", module.Name);
1683 public static Type GetImportedIgnoreCaseClsType (string name)
1685 foreach (Assembly a in GlobalRootNamespace.Instance.Assemblies) {
1686 Type t = a.GetType (name, false, true);
1690 if (IsClsCompliant (t))
1696 static bool GetClsCompliantAttributeValue (ICustomAttributeProvider attribute_provider, Assembly a)
1698 PredefinedAttribute pa = PredefinedAttributes.Get.CLSCompliant;
1702 object[] cls_attr = attribute_provider.GetCustomAttributes (pa.Type, false);
1703 if (cls_attr.Length == 0) {
1707 return GetClsCompliantAttributeValue (a, null);
1710 return ((CLSCompliantAttribute)cls_attr [0]).IsCompliant;
1713 static bool AnalyzeTypeCompliance (Type type)
1715 type = TypeManager.DropGenericTypeArguments (type);
1716 DeclSpace ds = TypeManager.LookupDeclSpace (type);
1718 return ds.IsClsComplianceRequired ();
1721 if (TypeManager.IsGenericParameter (type))
1724 return GetClsCompliantAttributeValue (type, type.Assembly);
1728 /// Returns instance of ObsoleteAttribute when type is obsolete
1730 public static ObsoleteAttribute GetObsoleteAttribute (Type type)
1732 object type_obsolete = analyzed_types_obsolete [type];
1733 if (type_obsolete == FALSE)
1736 if (type_obsolete != null)
1737 return (ObsoleteAttribute)type_obsolete;
1739 ObsoleteAttribute result = null;
1740 if (TypeManager.HasElementType (type)) {
1741 result = GetObsoleteAttribute (TypeManager.GetElementType (type));
1742 } else if (TypeManager.IsGenericParameter (type))
1743 result = null; // TODO: throw new NotSupportedException ()
1744 else if (TypeManager.IsGenericType (type) && !TypeManager.IsGenericTypeDefinition (type)) {
1745 return GetObsoleteAttribute (TypeManager.DropGenericTypeArguments (type));
1747 DeclSpace type_ds = TypeManager.LookupDeclSpace (type);
1749 // Type is external, we can get attribute directly
1750 if (type_ds == null) {
1751 PredefinedAttribute pa = PredefinedAttributes.Get.Obsolete;
1753 object[] attribute = type.GetCustomAttributes (pa.Type, false);
1754 if (attribute.Length == 1)
1755 result = (ObsoleteAttribute) attribute[0];
1758 result = type_ds.GetObsoleteAttribute ();
1762 // Cannot use .Add because of corlib bootstrap
1763 analyzed_types_obsolete [type] = result == null ? FALSE : result;
1768 /// Returns instance of ObsoleteAttribute when method is obsolete
1770 public static ObsoleteAttribute GetMethodObsoleteAttribute (MethodBase mb)
1772 IMethodData mc = TypeManager.GetMethod (mb);
1774 return mc.GetObsoleteAttribute ();
1776 // compiler generated methods are not registered by AddMethod
1777 if (mb.DeclaringType is TypeBuilder)
1780 MemberInfo mi = TypeManager.GetPropertyFromAccessor (mb);
1782 return GetMemberObsoleteAttribute (mi);
1784 mi = TypeManager.GetEventFromAccessor (mb);
1786 return GetMemberObsoleteAttribute (mi);
1788 return GetMemberObsoleteAttribute (mb);
1792 /// Returns instance of ObsoleteAttribute when member is obsolete
1794 public static ObsoleteAttribute GetMemberObsoleteAttribute (MemberInfo mi)
1796 object type_obsolete = analyzed_member_obsolete [mi];
1797 if (type_obsolete == FALSE)
1800 if (type_obsolete != null)
1801 return (ObsoleteAttribute)type_obsolete;
1803 if ((mi.DeclaringType is TypeBuilder) || TypeManager.IsGenericType (mi.DeclaringType))
1806 PredefinedAttribute pa = PredefinedAttributes.Get.Obsolete;
1810 ObsoleteAttribute oa = System.Attribute.GetCustomAttribute (mi, pa.Type, false)
1811 as ObsoleteAttribute;
1812 analyzed_member_obsolete.Add (mi, oa == null ? FALSE : oa);
1817 /// Common method for Obsolete error/warning reporting.
1819 public static void Report_ObsoleteMessage (ObsoleteAttribute oa, string member, Location loc)
1822 Report.Error (619, loc, "`{0}' is obsolete: `{1}'", member, oa.Message);
1826 if (oa.Message == null || oa.Message.Length == 0) {
1827 Report.Warning (612, 1, loc, "`{0}' is obsolete", member);
1830 Report.Warning (618, 2, loc, "`{0}' is obsolete: `{1}'", member, oa.Message);
1833 public static bool IsConditionalMethodExcluded (MethodBase mb, Location loc)
1835 object excluded = analyzed_method_excluded [mb];
1836 if (excluded != null)
1837 return excluded == TRUE ? true : false;
1839 PredefinedAttribute pa = PredefinedAttributes.Get.Conditional;
1843 ConditionalAttribute[] attrs = mb.GetCustomAttributes (pa.Type, true)
1844 as ConditionalAttribute[];
1845 if (attrs.Length == 0) {
1846 analyzed_method_excluded.Add (mb, FALSE);
1850 foreach (ConditionalAttribute a in attrs) {
1851 if (loc.CompilationUnit.IsConditionalDefined (a.ConditionString)) {
1852 analyzed_method_excluded.Add (mb, FALSE);
1857 analyzed_method_excluded.Add (mb, TRUE);
1862 /// Analyzes class whether it has attribute which has ConditionalAttribute
1863 /// and its condition is not defined.
1865 public static bool IsAttributeExcluded (Type type, Location loc)
1870 Class class_decl = TypeManager.LookupDeclSpace (type) as Class;
1872 // TODO: add caching
1873 // TODO: merge all Type bases attribute caching to one cache to save memory
1874 PredefinedAttribute pa = PredefinedAttributes.Get.Conditional;
1875 if (class_decl == null && pa.IsDefined) {
1876 object[] attributes = type.GetCustomAttributes (pa.Type, false);
1877 foreach (ConditionalAttribute ca in attributes) {
1878 if (loc.CompilationUnit.IsConditionalDefined (ca.ConditionString))
1881 return attributes.Length > 0;
1884 return class_decl.IsExcluded ();
1887 public static Type GetCoClassAttribute (Type type)
1889 TypeContainer tc = TypeManager.LookupInterface (type);
1890 PredefinedAttribute pa = PredefinedAttributes.Get.CoClass;
1895 object[] o = type.GetCustomAttributes (pa.Type, false);
1898 return ((System.Runtime.InteropServices.CoClassAttribute)o[0]).CoClass;
1901 if (tc.OptAttributes == null)
1904 Attribute a = tc.OptAttributes.Search (pa);
1908 return a.GetCoClassAttributeValue ();
1912 public class PredefinedAttributes
1915 public readonly PredefinedAttribute ParamArray;
1916 public readonly PredefinedAttribute Out;
1919 public readonly PredefinedAttribute Obsolete;
1920 public readonly PredefinedAttribute DllImport;
1921 public readonly PredefinedAttribute MethodImpl;
1922 public readonly PredefinedAttribute MarshalAs;
1923 public readonly PredefinedAttribute In;
1924 public readonly PredefinedAttribute IndexerName;
1925 public readonly PredefinedAttribute Conditional;
1926 public readonly PredefinedAttribute CLSCompliant;
1927 public readonly PredefinedAttribute Security;
1928 public readonly PredefinedAttribute Required;
1929 public readonly PredefinedAttribute Guid;
1930 public readonly PredefinedAttribute AssemblyCulture;
1931 public readonly PredefinedAttribute AssemblyVersion;
1932 public readonly PredefinedAttribute ComImport;
1933 public readonly PredefinedAttribute CoClass;
1934 public readonly PredefinedAttribute AttributeUsage;
1935 public readonly PredefinedAttribute DefaultParameterValue;
1936 public readonly PredefinedAttribute OptionalParameter;
1939 public readonly PredefinedAttribute DefaultCharset;
1940 public readonly PredefinedAttribute TypeForwarder;
1941 public readonly PredefinedAttribute FixedBuffer;
1942 public readonly PredefinedAttribute CompilerGenerated;
1943 public readonly PredefinedAttribute InternalsVisibleTo;
1944 public readonly PredefinedAttribute RuntimeCompatibility;
1945 public readonly PredefinedAttribute DebuggerHidden;
1946 public readonly PredefinedAttribute UnsafeValueType;
1949 public readonly PredefinedAttribute Extension;
1952 public readonly PredefinedAttribute Dynamic;
1955 // Optional types which are used as types and for member lookup
1957 public readonly PredefinedAttribute DefaultMember;
1958 public readonly PredefinedAttribute DecimalConstant;
1959 public readonly PredefinedAttribute StructLayout;
1960 public readonly PredefinedAttribute FieldOffset;
1962 public static PredefinedAttributes Get = new PredefinedAttributes ();
1964 private PredefinedAttributes ()
1966 ParamArray = new PredefinedAttribute ("System", "ParamArrayAttribute");
1967 Out = new PredefinedAttribute ("System.Runtime.InteropServices", "OutAttribute");
1969 Obsolete = new PredefinedAttribute ("System", "ObsoleteAttribute");
1970 DllImport = new PredefinedAttribute ("System.Runtime.InteropServices", "DllImportAttribute");
1971 MethodImpl = new PredefinedAttribute ("System.Runtime.CompilerServices", "MethodImplAttribute");
1972 MarshalAs = new PredefinedAttribute ("System.Runtime.InteropServices", "MarshalAsAttribute");
1973 In = new PredefinedAttribute ("System.Runtime.InteropServices", "InAttribute");
1974 IndexerName = new PredefinedAttribute ("System.Runtime.CompilerServices", "IndexerNameAttribute");
1975 Conditional = new PredefinedAttribute ("System.Diagnostics", "ConditionalAttribute");
1976 CLSCompliant = new PredefinedAttribute ("System", "CLSCompliantAttribute");
1977 Security = new PredefinedAttribute ("System.Security.Permissions", "SecurityAttribute");
1978 Required = new PredefinedAttribute ("System.Runtime.CompilerServices", "RequiredAttributeAttribute");
1979 Guid = new PredefinedAttribute ("System.Runtime.InteropServices", "GuidAttribute");
1980 AssemblyCulture = new PredefinedAttribute ("System.Reflection", "AssemblyCultureAttribute");
1981 AssemblyVersion = new PredefinedAttribute ("System.Reflection", "AssemblyVersionAttribute");
1982 ComImport = new PredefinedAttribute ("System.Runtime.InteropServices", "ComImportAttribute");
1983 CoClass = new PredefinedAttribute ("System.Runtime.InteropServices", "CoClassAttribute");
1984 AttributeUsage = new PredefinedAttribute ("System", "AttributeUsageAttribute");
1985 DefaultParameterValue = new PredefinedAttribute ("System.Runtime.InteropServices", "DefaultParameterValueAttribute");
1986 OptionalParameter = new PredefinedAttribute ("System.Runtime.InteropServices", "OptionalAttribute");
1988 DefaultCharset = new PredefinedAttribute ("System.Runtime.InteropServices", "DefaultCharSetAttribute");
1989 TypeForwarder = new PredefinedAttribute ("System.Runtime.CompilerServices", "TypeForwardedToAttribute");
1990 FixedBuffer = new PredefinedAttribute ("System.Runtime.CompilerServices", "FixedBufferAttribute");
1991 CompilerGenerated = new PredefinedAttribute ("System.Runtime.CompilerServices", "CompilerGeneratedAttribute");
1992 InternalsVisibleTo = new PredefinedAttribute ("System.Runtime.CompilerServices", "InternalsVisibleToAttribute");
1993 RuntimeCompatibility = new PredefinedAttribute ("System.Runtime.CompilerServices", "RuntimeCompatibilityAttribute");
1994 DebuggerHidden = new PredefinedAttribute ("System.Diagnostics", "DebuggerHiddenAttribute");
1995 UnsafeValueType = new PredefinedAttribute ("System.Runtime.CompilerServices", "UnsafeValueTypeAttribute");
1997 Extension = new PredefinedAttribute ("System.Runtime.CompilerServices", "ExtensionAttribute");
1999 Dynamic = new PredefinedAttribute ("System.Runtime.CompilerServices", "DynamicAttribute");
2001 DefaultMember = new PredefinedAttribute ("System.Reflection", "DefaultMemberAttribute");
2002 DecimalConstant = new PredefinedAttribute ("System.Runtime.CompilerServices", "DecimalConstantAttribute");
2003 StructLayout = new PredefinedAttribute ("System.Runtime.InteropServices", "StructLayoutAttribute");
2004 FieldOffset = new PredefinedAttribute ("System.Runtime.InteropServices", "FieldOffsetAttribute");
2007 public void Initialize ()
2009 foreach (FieldInfo fi in GetType ().GetFields (BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly)) {
2010 ((PredefinedAttribute) fi.GetValue (this)).Resolve (true);
2014 public static void Reset ()
2016 Get = new PredefinedAttributes ();
2020 public class PredefinedAttribute
2023 CustomAttributeBuilder cab;
2024 ConstructorInfo ctor;
2025 readonly string ns, name;
2027 public PredefinedAttribute (string ns, string name)
2033 public static bool operator == (Type type, PredefinedAttribute pa)
2035 return type == pa.type;
2038 public static bool operator != (Type type, PredefinedAttribute pa)
2040 return type != pa.type;
2043 public ConstructorInfo Constructor {
2044 get { return ctor; }
2047 public override int GetHashCode ()
2049 return base.GetHashCode ();
2052 public override bool Equals (object obj)
2054 throw new NotSupportedException ();
2057 public void EmitAttribute (ConstructorBuilder builder)
2059 if (ResolveBuilder ())
2060 builder.SetCustomAttribute (cab);
2063 public void EmitAttribute (MethodBuilder builder)
2065 if (ResolveBuilder ())
2066 builder.SetCustomAttribute (cab);
2069 public void EmitAttribute (PropertyBuilder builder)
2071 if (ResolveBuilder ())
2072 builder.SetCustomAttribute (cab);
2075 public void EmitAttribute (FieldBuilder builder)
2077 if (ResolveBuilder ())
2078 builder.SetCustomAttribute (cab);
2081 public void EmitAttribute (TypeBuilder builder)
2083 if (ResolveBuilder ())
2084 builder.SetCustomAttribute (cab);
2087 public void EmitAttribute (AssemblyBuilder builder)
2089 if (ResolveBuilder ())
2090 builder.SetCustomAttribute (cab);
2093 public void EmitAttribute (ParameterBuilder builder, Location loc)
2095 if (ResolveBuilder ())
2096 builder.SetCustomAttribute (cab);
2099 public bool IsDefined {
2100 get { return type != null && type != typeof (PredefinedAttribute); }
2103 public bool Resolve (bool canFail)
2112 type = TypeManager.CoreLookupType (ns, name, Kind.Class, !canFail);
2114 type = typeof (PredefinedAttribute);
2121 bool ResolveBuilder ()
2127 // Handle all parameter-less attributes as optional
2129 if (!Resolve (true))
2132 ConstructorInfo ci = TypeManager.GetPredefinedConstructor (type, Location.Null, Type.EmptyTypes);
2136 cab = new CustomAttributeBuilder (ci, new object[0]);
2140 public bool ResolveConstructor (Location loc, params Type[] argType)
2143 throw new InternalErrorException ("Predefined ctor redefined");
2145 if (!Resolve (false))
2148 ctor = TypeManager.GetPredefinedConstructor (type, loc, argType);
2149 return ctor != null;
2153 get { return type; }