2 // attribute.cs: Attributes handling
4 // Author: Ravi Pratap (ravi@ximian.com)
5 // Marek Safar (marek.safar@gmail.com)
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.
11 // Copyright 2011-2013 Xamarin Inc
15 using System.Collections.Generic;
16 using System.Runtime.InteropServices;
17 using System.Runtime.CompilerServices;
18 using System.Security;
19 using System.Security.Permissions;
24 using SecurityType = System.Collections.Generic.List<IKVM.Reflection.Emit.CustomAttributeBuilder>;
25 using BadImageFormat = IKVM.Reflection.BadImageFormatException;
26 using IKVM.Reflection;
27 using IKVM.Reflection.Emit;
29 using SecurityType = System.Collections.Generic.Dictionary<System.Security.Permissions.SecurityAction, System.Security.PermissionSet>;
30 using BadImageFormat = System.BadImageFormatException;
31 using System.Reflection;
32 using System.Reflection.Emit;
35 namespace Mono.CSharp {
38 /// Base class for objects that can have Attributes applied to them.
40 public abstract class Attributable {
42 // Holds all attributes attached to this element
44 protected Attributes attributes;
46 public void AddAttributes (Attributes attrs, IMemberContext context)
51 if (attributes == null)
54 attributes.AddAttributes (attrs.Attrs);
56 attrs.AttachTo (this, context);
59 public Attributes OptAttributes {
69 /// Use member-specific procedure to apply attribute @a in @cb to the entity being built in @builder
71 public abstract void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa);
74 /// Returns one AttributeTarget for this element.
76 public abstract AttributeTargets AttributeTargets { get; }
78 public abstract bool IsClsComplianceRequired ();
81 /// Gets list of valid attribute targets for explicit target declaration.
82 /// The first array item is default target. Don't break this rule.
84 public abstract string[] ValidAttributeTargets { get; }
87 public class Attribute
89 public readonly string ExplicitTarget;
90 public AttributeTargets Target;
91 readonly ATypeNameExpression expression;
93 Arguments pos_args, named_args;
97 readonly bool nameEscaped;
98 readonly Location loc;
102 // An attribute can be attached to multiple targets (e.g. multiple fields)
104 Attributable[] targets;
107 // A member context for the attribute, it's much easier to hold it here
108 // than trying to pull it during resolve
110 IMemberContext context;
112 public static readonly AttributeUsageAttribute DefaultUsageAttribute = new AttributeUsageAttribute (AttributeTargets.All);
113 public static readonly object[] EmptyObject = new object [0];
115 List<KeyValuePair<MemberExpr, NamedArgument>> named_values;
117 public Attribute (string target, ATypeNameExpression expr, Arguments[] args, Location loc, bool nameEscaped)
119 this.expression = expr;
122 named_args = args[1];
125 ExplicitTarget = target;
126 this.nameEscaped = nameEscaped;
129 public Location Location {
135 public Arguments NamedArguments {
141 public Arguments PositionalArguments {
147 public bool ResolveError {
149 return resolve_error;
153 public ATypeNameExpression TypeExpression {
159 void AddModuleCharSet (ResolveContext rc)
161 const string dll_import_char_set = "CharSet";
164 // Only when not customized by user
166 if (HasField (dll_import_char_set))
169 if (!rc.Module.PredefinedTypes.CharSet.Define ()) {
173 if (NamedArguments == null)
174 named_args = new Arguments (1);
176 var value = Constant.CreateConstantFromValue (rc.Module.PredefinedTypes.CharSet.TypeSpec, rc.Module.DefaultCharSet, Location);
177 NamedArguments.Add (new NamedArgument (dll_import_char_set, loc, value));
180 public Attribute Clone ()
182 Attribute a = new Attribute (ExplicitTarget, expression, null, loc, nameEscaped);
183 a.pos_args = pos_args;
184 a.named_args = NamedArguments;
189 // When the same attribute is attached to multiple fiels
190 // we use @target field as a list of targets. The attribute
191 // has to be resolved only once but emitted for each target.
193 public void AttachTo (Attributable target, IMemberContext context)
195 if (this.targets == null) {
196 this.targets = new Attributable[] { target };
197 this.context = context;
201 // When re-attaching global attributes
202 if (context is NamespaceContainer) {
203 this.targets[0] = target;
204 this.context = context;
208 // Resize target array
209 Attributable[] new_array = new Attributable [this.targets.Length + 1];
210 targets.CopyTo (new_array, 0);
211 new_array [targets.Length] = target;
212 this.targets = new_array;
214 // No need to update context, different targets cannot have
215 // different contexts, it's enough to remove same attributes
216 // from secondary members.
218 target.OptAttributes = null;
221 public ResolveContext CreateResolveContext ()
223 return new ResolveContext (context, ResolveContext.Options.ConstantScope);
226 static void Error_InvalidNamedArgument (ResolveContext rc, NamedArgument name)
228 rc.Report.Error (617, name.Location, "`{0}' is not a valid named attribute argument. Named attribute arguments " +
229 "must be fields which are not readonly, static, const or read-write properties which are " +
230 "public and not static",
234 static void Error_InvalidNamedArgumentType (ResolveContext rc, NamedArgument name)
236 rc.Report.Error (655, name.Location,
237 "`{0}' is not a valid named attribute argument because it is not a valid attribute parameter type",
241 public static void Error_AttributeArgumentIsDynamic (IMemberContext context, Location loc)
243 context.Module.Compiler.Report.Error (1982, loc, "An attribute argument cannot be dynamic expression");
246 public void Error_MissingGuidAttribute ()
248 Report.Error (596, Location, "The Guid attribute must be specified with the ComImport attribute");
251 public void Error_MisusedExtensionAttribute ()
253 Report.Error (1112, Location, "Do not use `{0}' directly. Use parameter modifier `this' instead", GetSignatureForError ());
256 public void Error_MisusedDynamicAttribute ()
258 Report.Error (1970, loc, "Do not use `{0}' directly. Use `dynamic' keyword instead", GetSignatureForError ());
261 void Error_AttributeEmitError (string inner)
263 Report.Error (647, Location, "Error during emitting `{0}' attribute. The reason is `{1}'",
264 Type.GetSignatureForError (), inner);
267 public void Error_InvalidArgumentValue (TypeSpec attributeType)
269 Report.Error (591, Location, "Invalid value for argument to `{0}' attribute", attributeType.GetSignatureForError ());
272 public void Error_InvalidSecurityParent ()
274 Report.Error (7070, Location,
275 "Security attribute `{0}' is not valid on this declaration type. Security attributes are only valid on assembly, type and method declarations",
276 Type.GetSignatureForError ());
285 public void SetOwner (Attributable owner)
291 /// Tries to resolve the type of the attribute. Flags an error if it can't, and complain is true.
293 void ResolveAttributeType (bool comparisonOnly)
295 var resolve_printer = new SessionReportPrinter ();
296 SessionReportPrinter secondary_printer = null;
297 ReportPrinter prev_recorder = Report.SetPrinter (resolve_printer);
299 bool t1_is_attr = false;
300 bool t2_is_attr = false;
302 ATypeNameExpression expanded = null;
304 // TODO: Additional warnings such as CS0436 are swallowed because we don't
308 t1 = expression.ResolveAsType (context);
309 resolve_printer.EndSession ();
311 if (t1 != null && resolve_printer.ErrorsCount == 0)
312 t1_is_attr = t1.IsAttribute;
317 expanded = (ATypeNameExpression) expression.Clone (null);
318 expanded.Name += "Attribute";
320 secondary_printer = new SessionReportPrinter ();
321 Report.SetPrinter (secondary_printer);
322 t2 = expanded.ResolveAsType (context);
323 secondary_printer.EndSession ();
324 if (t2 != null && secondary_printer.ErrorsCount == 0)
325 t2_is_attr = t2.IsAttribute;
327 secondary_printer.EndSession ();
330 context.Module.Compiler.Report.SetPrinter (prev_recorder);
333 if (t1_is_attr && t2_is_attr && t1 != t2) {
334 if (!comparisonOnly) {
335 Report.Error (1614, Location, "`{0}' is ambiguous between `{1}' and `{2}'. Use either `@{0}' or `{0}Attribute'",
336 GetSignatureForError (), expression.GetSignatureForError (), expanded.GetSignatureForError ());
337 resolve_error = true;
356 resolve_error = true;
359 if (resolve_printer.IsEmpty) {
360 Report.SymbolRelatedToPreviousError (t1);
361 Report.Error (616, Location, "`{0}': is not an attribute class", t1.GetSignatureForError ());
363 resolve_printer.Merge (prev_recorder);
370 if (secondary_printer.IsEmpty) {
371 Report.SymbolRelatedToPreviousError (t2);
372 Report.Error (616, Location, "`{0}': is not an attribute class", t2.GetSignatureForError ());
374 secondary_printer.Merge (prev_recorder);
380 resolve_printer.Merge (prev_recorder);
383 public TypeSpec ResolveTypeForComparison ()
385 if (Type == null && !resolve_error)
386 ResolveAttributeType (true);
390 public string GetSignatureForError ()
393 return Type.GetSignatureForError ();
395 return expression.GetSignatureForError ();
398 public bool HasSecurityAttribute {
400 PredefinedAttribute pa = context.Module.PredefinedAttributes.Security;
401 return pa.IsDefined && TypeSpec.IsBaseClass (Type, pa.TypeSpec, false);
405 public bool IsValidSecurityAttribute ()
407 return HasSecurityAttribute && IsSecurityActionValid ();
410 static bool IsValidMethodImplOption (int value)
413 // Allow to use AggressiveInlining on any runtime/corlib
415 MethodImplOptions all = (MethodImplOptions) 256;
416 foreach (MethodImplOptions v in System.Enum.GetValues (typeof (MethodImplOptions))) {
420 return ((MethodImplOptions) value | all) == all;
423 public static bool IsValidArgumentType (TypeSpec t)
426 var ac = (ArrayContainer) t;
433 switch (t.BuiltinType) {
434 case BuiltinTypeSpec.Type.Int:
435 case BuiltinTypeSpec.Type.UInt:
436 case BuiltinTypeSpec.Type.Long:
437 case BuiltinTypeSpec.Type.ULong:
438 case BuiltinTypeSpec.Type.Float:
439 case BuiltinTypeSpec.Type.Double:
440 case BuiltinTypeSpec.Type.Char:
441 case BuiltinTypeSpec.Type.Short:
442 case BuiltinTypeSpec.Type.Bool:
443 case BuiltinTypeSpec.Type.SByte:
444 case BuiltinTypeSpec.Type.Byte:
445 case BuiltinTypeSpec.Type.UShort:
447 case BuiltinTypeSpec.Type.String:
448 case BuiltinTypeSpec.Type.Object:
449 case BuiltinTypeSpec.Type.Dynamic:
450 case BuiltinTypeSpec.Type.Type:
457 // TODO: Don't use this ambiguous value
459 get { return expression.Name; }
462 public Report Report {
463 get { return context.Module.Compiler.Report; }
466 public MethodSpec Resolve ()
471 resolve_error = true;
475 ResolveAttributeType (false);
480 if (Type.IsAbstract) {
481 Report.Error (653, Location, "Cannot apply attribute class `{0}' because it is abstract", GetSignatureForError ());
485 Type.CheckObsoleteness (context, expression.StartLocation);
487 ResolveContext rc = null;
490 // Try if the attribute is simple and has been resolved before
491 if (pos_args != null || !context.Module.AttributeConstructorCache.TryGetValue (Type, out ctor)) {
492 rc = CreateResolveContext ();
493 ctor = ResolveConstructor (rc);
498 if (pos_args == null && ctor.Parameters.IsEmpty)
499 context.Module.AttributeConstructorCache.Add (Type, ctor);
503 // Add [module: DefaultCharSet] to all DllImport import attributes
505 var module = context.Module;
506 if ((Type == module.PredefinedAttributes.DllImport || Type == module.PredefinedAttributes.UnmanagedFunctionPointer) && module.HasDefaultCharSet) {
508 rc = CreateResolveContext ();
510 AddModuleCharSet (rc);
513 if (NamedArguments != null) {
515 rc = CreateResolveContext ();
517 if (!ResolveNamedArguments (rc))
521 resolve_error = false;
525 MethodSpec ResolveConstructor (ResolveContext ec)
527 if (pos_args != null) {
529 pos_args.Resolve (ec, out dynamic);
531 Error_AttributeArgumentIsDynamic (ec.MemberContext, loc);
536 return Expression.ConstructorLookup (ec, Type, ref pos_args, loc);
539 bool ResolveNamedArguments (ResolveContext ec)
541 int named_arg_count = NamedArguments.Count;
542 var seen_names = new List<string> (named_arg_count);
544 named_values = new List<KeyValuePair<MemberExpr, NamedArgument>> (named_arg_count);
546 foreach (NamedArgument a in NamedArguments) {
547 string name = a.Name;
548 if (seen_names.Contains (name)) {
549 ec.Report.Error (643, a.Location, "Duplicate named attribute `{0}' argument", name);
553 seen_names.Add (name);
557 Expression member = Expression.MemberLookup (ec, false, Type, name, 0, Expression.MemberLookupRestrictions.ExactArity, loc);
559 if (member == null) {
560 member = Expression.MemberLookup (ec, true, Type, name, 0, Expression.MemberLookupRestrictions.ExactArity, loc);
562 if (member != null) {
563 // TODO: ec.Report.SymbolRelatedToPreviousError (member);
564 Expression.ErrorIsInaccesible (ec, member.GetSignatureForError (), loc);
570 Expression.Error_TypeDoesNotContainDefinition (ec, Location, Type, name);
574 if (!(member is PropertyExpr || member is FieldExpr)) {
575 Error_InvalidNamedArgument (ec, a);
579 if (member is PropertyExpr) {
580 var pi = ((PropertyExpr) member).PropertyInfo;
582 if (!pi.HasSet || !pi.HasGet || pi.IsStatic || !pi.Get.IsPublic || !pi.Set.IsPublic) {
583 ec.Report.SymbolRelatedToPreviousError (pi);
584 Error_InvalidNamedArgument (ec, a);
588 if (!IsValidArgumentType (member.Type)) {
589 ec.Report.SymbolRelatedToPreviousError (pi);
590 Error_InvalidNamedArgumentType (ec, a);
594 // if (!context.IsObsolete)
595 pi.CheckObsoleteness (ec, member.StartLocation);
597 pi.MemberDefinition.SetIsAssigned ();
599 var fi = ((FieldExpr) member).Spec;
601 if (fi.IsReadOnly || fi.IsStatic || !fi.IsPublic) {
602 Error_InvalidNamedArgument (ec, a);
606 if (!IsValidArgumentType (member.Type)) {
607 ec.Report.SymbolRelatedToPreviousError (fi);
608 Error_InvalidNamedArgumentType (ec, a);
612 // if (!context.IsObsolete)
613 fi.CheckObsoleteness (ec, member.StartLocation);
615 fi.MemberDefinition.SetIsAssigned ();
618 if (a.Type != member.Type) {
619 a.Expr = Convert.ImplicitConversionRequired (ec, a.Expr, member.Type, a.Expr.Location);
623 named_values.Add (new KeyValuePair<MemberExpr, NamedArgument> ((MemberExpr) member, a));
630 /// Get a string containing a list of valid targets for the attribute 'attr'
632 public string GetValidTargets ()
634 StringBuilder sb = new StringBuilder ();
635 AttributeTargets targets = Type.GetAttributeUsage (context.Module.PredefinedAttributes.AttributeUsage).ValidOn;
637 if ((targets & AttributeTargets.Assembly) != 0)
638 sb.Append ("assembly, ");
640 if ((targets & AttributeTargets.Module) != 0)
641 sb.Append ("module, ");
643 if ((targets & AttributeTargets.Class) != 0)
644 sb.Append ("class, ");
646 if ((targets & AttributeTargets.Struct) != 0)
647 sb.Append ("struct, ");
649 if ((targets & AttributeTargets.Enum) != 0)
650 sb.Append ("enum, ");
652 if ((targets & AttributeTargets.Constructor) != 0)
653 sb.Append ("constructor, ");
655 if ((targets & AttributeTargets.Method) != 0)
656 sb.Append ("method, ");
658 if ((targets & AttributeTargets.Property) != 0)
659 sb.Append ("property, indexer, ");
661 if ((targets & AttributeTargets.Field) != 0)
662 sb.Append ("field, ");
664 if ((targets & AttributeTargets.Event) != 0)
665 sb.Append ("event, ");
667 if ((targets & AttributeTargets.Interface) != 0)
668 sb.Append ("interface, ");
670 if ((targets & AttributeTargets.Parameter) != 0)
671 sb.Append ("parameter, ");
673 if ((targets & AttributeTargets.Delegate) != 0)
674 sb.Append ("delegate, ");
676 if ((targets & AttributeTargets.ReturnValue) != 0)
677 sb.Append ("return, ");
679 if ((targets & AttributeTargets.GenericParameter) != 0)
680 sb.Append ("type parameter, ");
682 return sb.Remove (sb.Length - 2, 2).ToString ();
685 public AttributeUsageAttribute GetAttributeUsageAttribute ()
688 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
689 // But because a lot of attribute class code must be rewritten will be better to wait...
693 return DefaultUsageAttribute;
695 AttributeUsageAttribute usage_attribute = new AttributeUsageAttribute ((AttributeTargets) ((Constant) pos_args[0].Expr).GetValue ());
697 var field = GetNamedValue ("AllowMultiple") as BoolConstant;
699 usage_attribute.AllowMultiple = field.Value;
701 field = GetNamedValue ("Inherited") as BoolConstant;
703 usage_attribute.Inherited = field.Value;
705 return usage_attribute;
709 /// Returns custom name of indexer
711 public string GetIndexerAttributeValue ()
714 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
715 // But because a lot of attribute class code must be rewritten will be better to wait...
718 if (resolve_error || pos_args.Count != 1 || !(pos_args[0].Expr is Constant))
721 return ((Constant) pos_args[0].Expr).GetValue () as string;
725 /// Returns condition of ConditionalAttribute
727 public string GetConditionalAttributeValue ()
730 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
731 // But because a lot of attribute class code must be rewritten will be better to wait...
737 return ((Constant) pos_args[0].Expr).GetValue () as string;
741 /// Creates the instance of ObsoleteAttribute from this attribute instance
743 public ObsoleteAttribute GetObsoleteAttribute ()
746 // corlib only case when obsolete is used before is resolved
747 var c = Type.MemberDefinition as Class;
748 if (c != null && !c.HasMembersDefined)
751 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
752 // But because a lot of attribute class code must be rewritten will be better to wait...
759 if (pos_args == null)
760 return new ObsoleteAttribute ();
762 string msg = ((Constant) pos_args[0].Expr).GetValue () as string;
763 if (pos_args.Count == 1)
764 return new ObsoleteAttribute (msg);
766 return new ObsoleteAttribute (msg, ((BoolConstant) pos_args[1].Expr).Value);
770 /// Returns value of CLSCompliantAttribute contructor parameter but because the method can be called
771 /// before ApplyAttribute. We need to resolve the arguments.
772 /// This situation occurs when class deps is differs from Emit order.
774 public bool GetClsCompliantAttributeValue ()
777 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
778 // But because a lot of attribute class code must be rewritten will be better to wait...
784 return ((BoolConstant) pos_args[0].Expr).Value;
787 public TypeSpec GetCoClassAttributeValue ()
795 return GetArgumentType ();
798 public bool CheckTarget ()
800 string[] valid_targets = Owner.ValidAttributeTargets;
801 if (ExplicitTarget == null || ExplicitTarget == valid_targets [0]) {
802 Target = Owner.AttributeTargets;
806 // TODO: we can skip the first item
807 if (Array.Exists (valid_targets, i => i == ExplicitTarget)) {
808 switch (ExplicitTarget) {
809 case "return": Target = AttributeTargets.ReturnValue; return true;
810 case "param": Target = AttributeTargets.Parameter; return true;
811 case "field": Target = AttributeTargets.Field; return true;
812 case "method": Target = AttributeTargets.Method; return true;
813 case "property": Target = AttributeTargets.Property; return true;
814 case "module": Target = AttributeTargets.Module; return true;
816 throw new InternalErrorException ("Unknown explicit target: " + ExplicitTarget);
819 StringBuilder sb = new StringBuilder ();
820 foreach (string s in valid_targets) {
824 sb.Remove (sb.Length - 2, 2);
825 Report.Warning (657, 1, Location,
826 "`{0}' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are `{1}'. All attributes in this section will be ignored",
827 ExplicitTarget, sb.ToString ());
832 /// Tests permitted SecurityAction for assembly or other types
834 bool IsSecurityActionValid ()
837 var action = GetSecurityActionValue (ref c);
838 bool for_assembly = Target == AttributeTargets.Assembly || Target == AttributeTargets.Module;
841 #pragma warning disable 618
842 case SecurityAction.Demand:
843 case SecurityAction.Assert:
844 case SecurityAction.Deny:
845 case SecurityAction.PermitOnly:
846 case SecurityAction.LinkDemand:
847 case SecurityAction.InheritanceDemand:
852 case SecurityAction.RequestMinimum:
853 case SecurityAction.RequestOptional:
854 case SecurityAction.RequestRefuse:
858 #pragma warning restore 618
860 Report.Error (7048, loc, "First argument of a security attribute `{0}' must be a valid SecurityAction",
861 Type.GetSignatureForError ());
865 Report.Error (7049, c.Location, "Security attribute `{0}' has an invalid SecurityAction value `{1}'",
866 Type.GetSignatureForError (), c.GetValueAsLiteral());
871 case AttributeTargets.Assembly:
872 Report.Error (7050, c.Location, "SecurityAction value `{0}' is invalid for security attributes applied to an assembly",
873 c.GetSignatureForError ());
876 Report.Error (7051, c.Location, "SecurityAction value `{0}' is invalid for security attributes applied to a type or a method",
877 c.GetSignatureForError ());
884 SecurityAction? GetSecurityActionValue (ref Constant value)
886 if (pos_args == null) {
887 var predefined = context.Module.PredefinedAttributes;
890 // BCL defines System.Security.Permissions.HostProtectionAttribute with parameterless
891 // contructor which should not be valid but it's already part of the framework
893 if (Type == predefined.HostProtection.TypeSpec) {
894 value = new IntConstant (context.Module.Compiler.BuiltinTypes, (int)SecurityAction.LinkDemand, loc);
895 return SecurityAction.LinkDemand;
901 value = (Constant) pos_args [0].Expr;
902 return (SecurityAction) value.GetValue ();
906 /// Creates instance of SecurityAttribute class and add result of CreatePermission method to permission table.
908 /// <returns></returns>
909 public void ExtractSecurityPermissionSet (MethodSpec ctor, ref SecurityType permissions)
913 if (pos_args != null) {
914 values = new object[pos_args.Count];
915 for (int i = 0; i < values.Length; ++i)
916 values[i] = ((Constant) pos_args[i].Expr).GetValue ();
922 object[] prop_values;
923 if (named_values == null) {
927 prop = new PropertyInfo[named_values.Count];
928 prop_values = new object [named_values.Count];
929 for (int i = 0; i < prop.Length; ++i) {
930 prop [i] = ((PropertyExpr) named_values [i].Key).PropertyInfo.MetaInfo;
931 prop_values [i] = ((Constant) named_values [i].Value.Expr).GetValue ();
935 if (permissions == null)
936 permissions = new SecurityType ();
938 var cab = new CustomAttributeBuilder ((ConstructorInfo) ctor.GetMetaInfo (), values, prop, prop_values);
939 permissions.Add (cab);
941 throw new NotSupportedException ();
945 public Constant GetNamedValue (string name)
947 if (named_values == null)
950 for (int i = 0; i < named_values.Count; ++i) {
951 if (named_values [i].Value.Name == name)
952 return named_values [i].Value.Expr as Constant;
958 public CharSet GetCharSetValue ()
960 return (CharSet) System.Enum.Parse (typeof (CharSet), ((Constant) pos_args[0].Expr).GetValue ().ToString ());
963 public bool HasField (string fieldName)
965 if (named_values == null)
968 foreach (var na in named_values) {
969 if (na.Value.Name == fieldName)
977 // Returns true for MethodImplAttribute with MethodImplOptions.InternalCall value
979 public bool IsInternalCall ()
981 return (GetMethodImplOptions () & MethodImplOptions.InternalCall) != 0;
984 public MethodImplOptions GetMethodImplOptions ()
986 MethodImplOptions options = 0;
987 if (pos_args.Count == 1) {
988 options = (MethodImplOptions) System.Enum.Parse (typeof (MethodImplOptions), ((Constant) pos_args[0].Expr).GetValue ().ToString ());
989 } else if (HasField ("Value")) {
990 var named = GetNamedValue ("Value");
991 options = (MethodImplOptions) System.Enum.Parse (typeof (MethodImplOptions), named.GetValue ().ToString ());
998 // Returns true for StructLayoutAttribute with LayoutKind.Explicit value
1000 public bool IsExplicitLayoutKind ()
1002 if (pos_args == null || pos_args.Count != 1)
1005 var value = (LayoutKind) System.Enum.Parse (typeof (LayoutKind), ((Constant) pos_args[0].Expr).GetValue ().ToString ());
1006 return value == LayoutKind.Explicit;
1009 public Expression GetParameterDefaultValue ()
1011 if (pos_args == null)
1014 return pos_args[0].Expr;
1017 public override bool Equals (object obj)
1019 Attribute a = obj as Attribute;
1023 return Type == a.Type && Target == a.Target;
1026 public override int GetHashCode ()
1028 return Type.GetHashCode () ^ Target.GetHashCode ();
1032 /// Emit attribute for Attributable symbol
1034 public void Emit (Dictionary<Attribute, List<Attribute>> allEmitted)
1036 var ctor = Resolve ();
1040 var predefined = context.Module.PredefinedAttributes;
1042 AttributeUsageAttribute usage_attr = Type.GetAttributeUsage (predefined.AttributeUsage);
1043 if ((usage_attr.ValidOn & Target) == 0) {
1044 Report.Error (592, Location, "The attribute `{0}' is not valid on this declaration type. " +
1045 "It is valid on `{1}' declarations only",
1046 GetSignatureForError (), GetValidTargets ());
1051 if (pos_args == null && named_values == null) {
1052 cdata = AttributeEncoder.Empty;
1054 AttributeEncoder encoder = new AttributeEncoder ();
1056 if (pos_args != null) {
1057 var param_types = ctor.Parameters.Types;
1058 for (int j = 0; j < pos_args.Count; ++j) {
1059 var pt = param_types[j];
1060 var arg_expr = pos_args[j].Expr;
1062 if ((Type == predefined.IndexerName || Type == predefined.Conditional) && arg_expr is Constant) {
1063 string v = ((Constant) arg_expr).GetValue () as string;
1064 if (!Tokenizer.IsValidIdentifier (v) || (Type == predefined.IndexerName && Tokenizer.IsKeyword (v))) {
1065 context.Module.Compiler.Report.Error (633, arg_expr.Location,
1066 "The argument to the `{0}' attribute must be a valid identifier", GetSignatureForError ());
1069 } else if (Type == predefined.Guid) {
1070 string v = ((StringConstant) arg_expr).Value;
1074 Error_InvalidArgumentValue (Type);
1077 } else if (Type == predefined.AttributeUsage) {
1078 int v = ((IntConstant) ((EnumConstant) arg_expr).Child).Value;
1080 Error_InvalidArgumentValue (Type);
1081 } else if (Type == predefined.MarshalAs) {
1082 if (pos_args.Count == 1) {
1083 var u_type = (UnmanagedType) System.Enum.Parse (typeof (UnmanagedType), ((Constant) pos_args[0].Expr).GetValue ().ToString ());
1084 if (u_type == UnmanagedType.ByValArray && !(Owner is FieldBase)) {
1085 Report.Error (7055, pos_args [0].Expr.Location, "Unmanaged type `ByValArray' is only valid for fields");
1088 } else if (Type == predefined.DllImport) {
1089 if (pos_args.Count == 1 && pos_args[0].Expr is Constant) {
1090 var value = ((Constant) pos_args[0].Expr).GetValue () as string;
1091 if (string.IsNullOrEmpty (value))
1092 Error_InvalidArgumentValue (Type);
1094 } else if (Type == predefined.MethodImpl) {
1095 if (pos_args.Count == 1) {
1096 var value = (int) ((Constant) arg_expr).GetValueAsLong ();
1098 if (!IsValidMethodImplOption (value)) {
1099 Error_InvalidArgumentValue (Type);
1105 arg_expr.EncodeAttributeValue (context, encoder, pt, pt);
1109 if (named_values != null) {
1110 encoder.Encode ((ushort) named_values.Count);
1111 foreach (var na in named_values) {
1112 if (na.Key is FieldExpr)
1113 encoder.Encode ((byte) 0x53);
1115 encoder.Encode ((byte) 0x54);
1117 encoder.Encode (na.Key.Type);
1118 encoder.Encode (na.Value.Name);
1119 na.Value.Expr.EncodeAttributeValue (context, encoder, na.Key.Type, na.Key.Type);
1122 encoder.EncodeEmptyNamedArguments ();
1125 cdata = encoder.ToArray ();
1128 if (!IsConditionallyExcluded (ctor.DeclaringType)) {
1130 foreach (Attributable target in targets)
1131 target.ApplyAttributeBuilder (this, ctor, cdata, predefined);
1132 } catch (Exception e) {
1133 if (e is BadImageFormat && Report.Errors > 0)
1136 Error_AttributeEmitError (e.Message);
1141 if (!usage_attr.AllowMultiple && allEmitted != null) {
1142 if (allEmitted.ContainsKey (this)) {
1143 var a = allEmitted [this];
1145 a = new List<Attribute> (2);
1146 allEmitted [this] = a;
1150 allEmitted.Add (this, null);
1154 if (!context.Module.Compiler.Settings.VerifyClsCompliance)
1157 // Here we are testing attribute arguments for array usage (error 3016)
1158 if (Owner.IsClsComplianceRequired ()) {
1159 if (pos_args != null)
1160 pos_args.CheckArrayAsAttribute (context.Module.Compiler);
1162 if (NamedArguments == null)
1165 NamedArguments.CheckArrayAsAttribute (context.Module.Compiler);
1169 bool IsConditionallyExcluded (TypeSpec type)
1172 if (type.IsConditionallyExcluded (context))
1175 type = type.BaseType;
1176 } while (type != null);
1181 private Expression GetValue ()
1183 if (pos_args == null || pos_args.Count < 1)
1186 return pos_args[0].Expr;
1189 public string GetString ()
1191 Expression e = GetValue ();
1192 if (e is StringConstant)
1193 return ((StringConstant)e).Value;
1197 public bool GetBoolean ()
1199 Expression e = GetValue ();
1200 if (e is BoolConstant)
1201 return ((BoolConstant)e).Value;
1205 public TypeSpec GetArgumentType ()
1207 TypeOf e = GetValue () as TypeOf;
1210 return e.TypeArgument;
1214 public class Attributes
1216 public readonly List<Attribute> Attrs;
1218 public Attributes (Attribute a)
1220 Attrs = new List<Attribute> ();
1224 public Attributes (List<Attribute> attrs)
1226 Attrs = attrs ?? new List<Attribute> ();
1229 public void AddAttribute (Attribute attr)
1234 public void AddAttributes (List<Attribute> attrs)
1236 Attrs.AddRange (attrs);
1239 public static void AttachFromPartial (Attributable target, Attributable partialSrc)
1241 if (target.OptAttributes == null) {
1242 target.OptAttributes = partialSrc.OptAttributes;
1244 target.OptAttributes.Attrs.AddRange (partialSrc.OptAttributes.Attrs);
1247 foreach (var attr in partialSrc.OptAttributes.Attrs) {
1248 attr.SetOwner (target);
1252 public void AttachTo (Attributable attributable, IMemberContext context)
1254 foreach (Attribute a in Attrs)
1255 a.AttachTo (attributable, context);
1258 public Attributes Clone ()
1260 var al = new List<Attribute> (Attrs.Count);
1261 foreach (Attribute a in Attrs)
1262 al.Add (a.Clone ());
1264 return new Attributes (al);
1268 /// Checks whether attribute target is valid for the current element
1270 public bool CheckTargets ()
1272 for (int i = 0; i < Attrs.Count; ++i) {
1273 if (!Attrs [i].CheckTarget ())
1274 Attrs.RemoveAt (i--);
1280 public void ConvertGlobalAttributes (TypeContainer member, NamespaceContainer currentNamespace, bool isGlobal)
1282 var member_explicit_targets = member.ValidAttributeTargets;
1283 for (int i = 0; i < Attrs.Count; ++i) {
1284 var attr = Attrs[0];
1285 if (attr.ExplicitTarget == null)
1289 for (ii = 0; ii < member_explicit_targets.Length; ++ii) {
1290 if (attr.ExplicitTarget == member_explicit_targets[ii]) {
1296 if (ii < 0 || !isGlobal)
1299 member.Module.AddAttribute (attr, currentNamespace);
1305 public bool HasResolveError()
1307 foreach (var a in Attrs) {
1315 public Attribute Search (PredefinedAttribute t)
1317 return Search (null, t);
1320 public Attribute Search (string explicitTarget, PredefinedAttribute t)
1322 foreach (Attribute a in Attrs) {
1323 if (explicitTarget != null && a.ExplicitTarget != explicitTarget)
1326 if (a.ResolveTypeForComparison () == t)
1333 /// Returns all attributes of type 't'. Use it when attribute is AllowMultiple = true
1335 public Attribute[] SearchMulti (PredefinedAttribute t)
1337 List<Attribute> ar = null;
1339 foreach (Attribute a in Attrs) {
1340 if (a.ResolveTypeForComparison () == t) {
1342 ar = new List<Attribute> (Attrs.Count);
1347 return ar == null ? null : ar.ToArray ();
1354 Dictionary<Attribute, List<Attribute>> ld = Attrs.Count > 1 ? new Dictionary<Attribute, List<Attribute>> () : null;
1356 foreach (Attribute a in Attrs)
1359 if (ld == null || ld.Count == 0)
1362 foreach (var d in ld) {
1363 if (d.Value == null)
1366 Attribute a = d.Key;
1368 foreach (Attribute collision in d.Value)
1369 a.Report.SymbolRelatedToPreviousError (collision.Location, "");
1371 a.Report.Error (579, a.Location, "The attribute `{0}' cannot be applied multiple times",
1372 a.GetSignatureForError ());
1376 public bool Contains (PredefinedAttribute t)
1378 return Search (t) != null;
1382 public sealed class AttributeEncoder
1385 public enum EncodedTypeProperties
1389 TypeParameter = 1 << 1
1392 public static readonly byte[] Empty;
1396 const ushort Version = 1;
1398 static AttributeEncoder ()
1400 Empty = new byte[4];
1401 Empty[0] = (byte) Version;
1404 public AttributeEncoder ()
1406 buffer = new byte[32];
1410 public void Encode (bool value)
1412 Encode (value ? (byte) 1 : (byte) 0);
1415 public void Encode (byte value)
1417 if (pos == buffer.Length)
1420 buffer [pos++] = value;
1423 public void Encode (sbyte value)
1425 Encode ((byte) value);
1428 public void Encode (short value)
1430 if (pos + 2 > buffer.Length)
1433 buffer[pos++] = (byte) value;
1434 buffer[pos++] = (byte) (value >> 8);
1437 public void Encode (ushort value)
1439 Encode ((short) value);
1442 public void Encode (int value)
1444 if (pos + 4 > buffer.Length)
1447 buffer[pos++] = (byte) value;
1448 buffer[pos++] = (byte) (value >> 8);
1449 buffer[pos++] = (byte) (value >> 16);
1450 buffer[pos++] = (byte) (value >> 24);
1453 public void Encode (uint value)
1455 Encode ((int) value);
1458 public void Encode (long value)
1460 if (pos + 8 > buffer.Length)
1463 buffer[pos++] = (byte) value;
1464 buffer[pos++] = (byte) (value >> 8);
1465 buffer[pos++] = (byte) (value >> 16);
1466 buffer[pos++] = (byte) (value >> 24);
1467 buffer[pos++] = (byte) (value >> 32);
1468 buffer[pos++] = (byte) (value >> 40);
1469 buffer[pos++] = (byte) (value >> 48);
1470 buffer[pos++] = (byte) (value >> 56);
1473 public void Encode (ulong value)
1475 Encode ((long) value);
1478 public void Encode (float value)
1480 Encode (SingleConverter.SingleToInt32Bits (value));
1483 public void Encode (double value)
1485 Encode (BitConverter.DoubleToInt64Bits (value));
1488 public void Encode (string value)
1490 if (value == null) {
1491 Encode ((byte) 0xFF);
1495 var buf = Encoding.UTF8.GetBytes(value);
1496 WriteCompressedValue (buf.Length);
1498 if (pos + buf.Length > buffer.Length)
1501 Buffer.BlockCopy (buf, 0, buffer, pos, buf.Length);
1505 public EncodedTypeProperties Encode (TypeSpec type)
1507 switch (type.BuiltinType) {
1508 case BuiltinTypeSpec.Type.Bool:
1509 Encode ((byte) 0x02);
1511 case BuiltinTypeSpec.Type.Char:
1512 Encode ((byte) 0x03);
1514 case BuiltinTypeSpec.Type.SByte:
1515 Encode ((byte) 0x04);
1517 case BuiltinTypeSpec.Type.Byte:
1518 Encode ((byte) 0x05);
1520 case BuiltinTypeSpec.Type.Short:
1521 Encode ((byte) 0x06);
1523 case BuiltinTypeSpec.Type.UShort:
1524 Encode ((byte) 0x07);
1526 case BuiltinTypeSpec.Type.Int:
1527 Encode ((byte) 0x08);
1529 case BuiltinTypeSpec.Type.UInt:
1530 Encode ((byte) 0x09);
1532 case BuiltinTypeSpec.Type.Long:
1533 Encode ((byte) 0x0A);
1535 case BuiltinTypeSpec.Type.ULong:
1536 Encode ((byte) 0x0B);
1538 case BuiltinTypeSpec.Type.Float:
1539 Encode ((byte) 0x0C);
1541 case BuiltinTypeSpec.Type.Double:
1542 Encode ((byte) 0x0D);
1544 case BuiltinTypeSpec.Type.String:
1545 Encode ((byte) 0x0E);
1547 case BuiltinTypeSpec.Type.Type:
1548 Encode ((byte) 0x50);
1550 case BuiltinTypeSpec.Type.Object:
1551 Encode ((byte) 0x51);
1553 case BuiltinTypeSpec.Type.Dynamic:
1554 Encode ((byte) 0x51);
1555 return EncodedTypeProperties.DynamicType;
1558 Encode ((byte) 0x1D);
1559 return Encode (TypeManager.GetElementType (type));
1562 if (type.Kind == MemberKind.Enum) {
1563 Encode ((byte) 0x55);
1564 EncodeTypeName (type);
1570 return EncodedTypeProperties.None;
1573 public void EncodeTypeName (TypeSpec type)
1575 var old_type = type.GetMetaInfo ();
1576 Encode (type.MemberDefinition.IsImported ? old_type.AssemblyQualifiedName : old_type.FullName);
1579 public void EncodeTypeName (TypeContainer type)
1581 Encode (type.GetSignatureForMetadata ());
1586 // Encodes single property named argument per call
1588 public void EncodeNamedPropertyArgument (PropertySpec property, Constant value)
1590 Encode ((ushort) 1); // length
1591 Encode ((byte) 0x54); // property
1592 Encode (property.MemberType);
1593 Encode (property.Name);
1594 value.EncodeAttributeValue (null, this, property.MemberType, property.MemberType);
1598 // Encodes single field named argument per call
1600 public void EncodeNamedFieldArgument (FieldSpec field, Constant value)
1602 Encode ((ushort) 1); // length
1603 Encode ((byte) 0x53); // field
1604 Encode (field.MemberType);
1605 Encode (field.Name);
1606 value.EncodeAttributeValue (null, this, field.MemberType, field.MemberType);
1609 public void EncodeNamedArguments<T> (T[] members, Constant[] values) where T : MemberSpec, IInterfaceMemberSpec
1611 Encode ((ushort) members.Length);
1613 for (int i = 0; i < members.Length; ++i)
1615 var member = members[i];
1617 if (member.Kind == MemberKind.Field)
1618 Encode ((byte) 0x53);
1619 else if (member.Kind == MemberKind.Property)
1620 Encode ((byte) 0x54);
1622 throw new NotImplementedException (member.Kind.ToString ());
1624 Encode (member.MemberType);
1625 Encode (member.Name);
1626 values [i].EncodeAttributeValue (null, this, member.MemberType, member.MemberType);
1630 public void EncodeEmptyNamedArguments ()
1632 Encode ((ushort) 0);
1637 int size = System.Math.Max (pos * 4, pos + inc + 2);
1638 Array.Resize (ref buffer, size);
1641 void WriteCompressedValue (int value)
1644 Encode ((byte) value);
1648 if (value < 0x4000) {
1649 Encode ((byte) (0x80 | (value >> 8)));
1650 Encode ((byte) value);
1657 public byte[] ToArray ()
1659 byte[] buf = new byte[pos];
1660 Array.Copy (buffer, buf, pos);
1667 /// Helper class for attribute verification routine.
1669 static class AttributeTester
1672 /// Common method for Obsolete error/warning reporting.
1674 public static void Report_ObsoleteMessage (ObsoleteAttribute oa, string member, Location loc, Report Report)
1677 Report.Error (619, loc, "`{0}' is obsolete: `{1}'", member, oa.Message);
1681 if (oa.Message == null || oa.Message.Length == 0) {
1682 Report.Warning (612, 1, loc, "`{0}' is obsolete", member);
1685 Report.Warning (618, 2, loc, "`{0}' is obsolete: `{1}'", member, oa.Message);
1690 // Predefined attribute types
1692 public class PredefinedAttributes
1694 // Build-in attributes
1695 public readonly PredefinedAttribute ParamArray;
1696 public readonly PredefinedAttribute Out;
1698 // Optional attributes
1699 public readonly PredefinedAttribute Obsolete;
1700 public readonly PredefinedAttribute DllImport;
1701 public readonly PredefinedAttribute MethodImpl;
1702 public readonly PredefinedAttribute MarshalAs;
1703 public readonly PredefinedAttribute In;
1704 public readonly PredefinedAttribute IndexerName;
1705 public readonly PredefinedAttribute Conditional;
1706 public readonly PredefinedAttribute CLSCompliant;
1707 public readonly PredefinedAttribute Security;
1708 public readonly PredefinedAttribute Required;
1709 public readonly PredefinedAttribute Guid;
1710 public readonly PredefinedAttribute AssemblyCulture;
1711 public readonly PredefinedAttribute AssemblyVersion;
1712 public readonly PredefinedAttribute AssemblyAlgorithmId;
1713 public readonly PredefinedAttribute AssemblyFlags;
1714 public readonly PredefinedAttribute AssemblyFileVersion;
1715 public readonly PredefinedAttribute AssemblyInformationalVersion;
1716 public readonly PredefinedAttribute ComImport;
1717 public readonly PredefinedAttribute CoClass;
1718 public readonly PredefinedAttribute AttributeUsage;
1719 public readonly PredefinedAttribute DefaultParameterValue;
1720 public readonly PredefinedAttribute OptionalParameter;
1721 public readonly PredefinedAttribute UnverifiableCode;
1722 public readonly PredefinedAttribute DefaultCharset;
1723 public readonly PredefinedAttribute TypeForwarder;
1724 public readonly PredefinedAttribute FixedBuffer;
1725 public readonly PredefinedAttribute CompilerGenerated;
1726 public readonly PredefinedAttribute InternalsVisibleTo;
1727 public readonly PredefinedAttribute RuntimeCompatibility;
1728 public readonly PredefinedAttribute DebuggerHidden;
1729 public readonly PredefinedAttribute UnsafeValueType;
1730 public readonly PredefinedAttribute UnmanagedFunctionPointer;
1731 public readonly PredefinedDebuggerBrowsableAttribute DebuggerBrowsable;
1732 public readonly PredefinedAttribute DebuggerStepThrough;
1733 public readonly PredefinedDebuggableAttribute Debuggable;
1734 public readonly PredefinedAttribute HostProtection;
1737 public readonly PredefinedAttribute Extension;
1740 public readonly PredefinedDynamicAttribute Dynamic;
1743 public readonly PredefinedStateMachineAttribute AsyncStateMachine;
1746 // Optional types which are used as types and for member lookup
1748 public readonly PredefinedAttribute DefaultMember;
1749 public readonly PredefinedDecimalAttribute DecimalConstant;
1750 public readonly PredefinedAttribute StructLayout;
1751 public readonly PredefinedAttribute FieldOffset;
1752 public readonly PredefinedAttribute AssemblyProduct;
1753 public readonly PredefinedAttribute AssemblyCompany;
1754 public readonly PredefinedAttribute AssemblyCopyright;
1755 public readonly PredefinedAttribute AssemblyTrademark;
1756 public readonly PredefinedAttribute CallerMemberNameAttribute;
1757 public readonly PredefinedAttribute CallerLineNumberAttribute;
1758 public readonly PredefinedAttribute CallerFilePathAttribute;
1760 public PredefinedAttributes (ModuleContainer module)
1762 ParamArray = new PredefinedAttribute (module, "System", "ParamArrayAttribute");
1763 Out = new PredefinedAttribute (module, "System.Runtime.InteropServices", "OutAttribute");
1764 ParamArray.Resolve ();
1767 Obsolete = new PredefinedAttribute (module, "System", "ObsoleteAttribute");
1768 DllImport = new PredefinedAttribute (module, "System.Runtime.InteropServices", "DllImportAttribute");
1769 MethodImpl = new PredefinedAttribute (module, "System.Runtime.CompilerServices", "MethodImplAttribute");
1770 MarshalAs = new PredefinedAttribute (module, "System.Runtime.InteropServices", "MarshalAsAttribute");
1771 In = new PredefinedAttribute (module, "System.Runtime.InteropServices", "InAttribute");
1772 IndexerName = new PredefinedAttribute (module, "System.Runtime.CompilerServices", "IndexerNameAttribute");
1773 Conditional = new PredefinedAttribute (module, "System.Diagnostics", "ConditionalAttribute");
1774 CLSCompliant = new PredefinedAttribute (module, "System", "CLSCompliantAttribute");
1775 Security = new PredefinedAttribute (module, "System.Security.Permissions", "SecurityAttribute");
1776 Required = new PredefinedAttribute (module, "System.Runtime.CompilerServices", "RequiredAttributeAttribute");
1777 Guid = new PredefinedAttribute (module, "System.Runtime.InteropServices", "GuidAttribute");
1778 AssemblyCulture = new PredefinedAttribute (module, "System.Reflection", "AssemblyCultureAttribute");
1779 AssemblyVersion = new PredefinedAttribute (module, "System.Reflection", "AssemblyVersionAttribute");
1780 AssemblyAlgorithmId = new PredefinedAttribute (module, "System.Reflection", "AssemblyAlgorithmIdAttribute");
1781 AssemblyFlags = new PredefinedAttribute (module, "System.Reflection", "AssemblyFlagsAttribute");
1782 AssemblyFileVersion = new PredefinedAttribute (module, "System.Reflection", "AssemblyFileVersionAttribute");
1783 ComImport = new PredefinedAttribute (module, "System.Runtime.InteropServices", "ComImportAttribute");
1784 CoClass = new PredefinedAttribute (module, "System.Runtime.InteropServices", "CoClassAttribute");
1785 AttributeUsage = new PredefinedAttribute (module, "System", "AttributeUsageAttribute");
1786 DefaultParameterValue = new PredefinedAttribute (module, "System.Runtime.InteropServices", "DefaultParameterValueAttribute");
1787 OptionalParameter = new PredefinedAttribute (module, "System.Runtime.InteropServices", "OptionalAttribute");
1788 UnverifiableCode = new PredefinedAttribute (module, "System.Security", "UnverifiableCodeAttribute");
1789 HostProtection = new PredefinedAttribute (module, "System.Security.Permissions", "HostProtectionAttribute");
1791 DefaultCharset = new PredefinedAttribute (module, "System.Runtime.InteropServices", "DefaultCharSetAttribute");
1792 TypeForwarder = new PredefinedAttribute (module, "System.Runtime.CompilerServices", "TypeForwardedToAttribute");
1793 FixedBuffer = new PredefinedAttribute (module, "System.Runtime.CompilerServices", "FixedBufferAttribute");
1794 CompilerGenerated = new PredefinedAttribute (module, "System.Runtime.CompilerServices", "CompilerGeneratedAttribute");
1795 InternalsVisibleTo = new PredefinedAttribute (module, "System.Runtime.CompilerServices", "InternalsVisibleToAttribute");
1796 RuntimeCompatibility = new PredefinedAttribute (module, "System.Runtime.CompilerServices", "RuntimeCompatibilityAttribute");
1797 DebuggerHidden = new PredefinedAttribute (module, "System.Diagnostics", "DebuggerHiddenAttribute");
1798 UnsafeValueType = new PredefinedAttribute (module, "System.Runtime.CompilerServices", "UnsafeValueTypeAttribute");
1799 UnmanagedFunctionPointer = new PredefinedAttribute (module, "System.Runtime.InteropServices", "UnmanagedFunctionPointerAttribute");
1800 DebuggerBrowsable = new PredefinedDebuggerBrowsableAttribute (module, "System.Diagnostics", "DebuggerBrowsableAttribute");
1801 DebuggerStepThrough = new PredefinedAttribute (module, "System.Diagnostics", "DebuggerStepThroughAttribute");
1802 Debuggable = new PredefinedDebuggableAttribute (module, "System.Diagnostics", "DebuggableAttribute");
1804 Extension = new PredefinedAttribute (module, "System.Runtime.CompilerServices", "ExtensionAttribute");
1806 Dynamic = new PredefinedDynamicAttribute (module, "System.Runtime.CompilerServices", "DynamicAttribute");
1808 DefaultMember = new PredefinedAttribute (module, "System.Reflection", "DefaultMemberAttribute");
1809 DecimalConstant = new PredefinedDecimalAttribute (module, "System.Runtime.CompilerServices", "DecimalConstantAttribute");
1810 StructLayout = new PredefinedAttribute (module, "System.Runtime.InteropServices", "StructLayoutAttribute");
1811 FieldOffset = new PredefinedAttribute (module, "System.Runtime.InteropServices", "FieldOffsetAttribute");
1812 AssemblyProduct = new PredefinedAttribute (module, "System.Reflection", "AssemblyProductAttribute");
1813 AssemblyCompany = new PredefinedAttribute (module, "System.Reflection", "AssemblyCompanyAttribute");
1814 AssemblyCopyright = new PredefinedAttribute (module, "System.Reflection", "AssemblyCopyrightAttribute");
1815 AssemblyTrademark = new PredefinedAttribute (module, "System.Reflection", "AssemblyTrademarkAttribute");
1816 AssemblyInformationalVersion = new PredefinedAttribute (module, "System.Reflection", "AssemblyInformationalVersionAttribute");
1818 AsyncStateMachine = new PredefinedStateMachineAttribute (module, "System.Runtime.CompilerServices", "AsyncStateMachineAttribute");
1820 CallerMemberNameAttribute = new PredefinedAttribute (module, "System.Runtime.CompilerServices", "CallerMemberNameAttribute");
1821 CallerLineNumberAttribute = new PredefinedAttribute (module, "System.Runtime.CompilerServices", "CallerLineNumberAttribute");
1822 CallerFilePathAttribute = new PredefinedAttribute (module, "System.Runtime.CompilerServices", "CallerFilePathAttribute");
1824 // TODO: Should define only attributes which are used for comparison
1825 const System.Reflection.BindingFlags all_fields = System.Reflection.BindingFlags.Public |
1826 System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.DeclaredOnly;
1828 foreach (var fi in GetType ().GetFields (all_fields)) {
1829 ((PredefinedAttribute) fi.GetValue (this)).Define ();
1834 public class PredefinedAttribute : PredefinedType
1836 protected MethodSpec ctor;
1838 public PredefinedAttribute (ModuleContainer module, string ns, string name)
1839 : base (module, MemberKind.Class, ns, name)
1845 public MethodSpec Constructor {
1853 public static bool operator == (TypeSpec type, PredefinedAttribute pa)
1855 return type == pa.type && pa.type != null;
1858 public static bool operator != (TypeSpec type, PredefinedAttribute pa)
1860 return type != pa.type;
1863 public override int GetHashCode ()
1865 return base.GetHashCode ();
1868 public override bool Equals (object obj)
1870 throw new NotSupportedException ();
1873 public void EmitAttribute (ConstructorBuilder builder)
1875 if (ResolveBuilder ())
1876 builder.SetCustomAttribute (GetCtorMetaInfo (), AttributeEncoder.Empty);
1879 public void EmitAttribute (MethodBuilder builder)
1881 if (ResolveBuilder ())
1882 builder.SetCustomAttribute (GetCtorMetaInfo (), AttributeEncoder.Empty);
1885 public void EmitAttribute (PropertyBuilder builder)
1887 if (ResolveBuilder ())
1888 builder.SetCustomAttribute (GetCtorMetaInfo (), AttributeEncoder.Empty);
1891 public void EmitAttribute (FieldBuilder builder)
1893 if (ResolveBuilder ())
1894 builder.SetCustomAttribute (GetCtorMetaInfo (), AttributeEncoder.Empty);
1897 public void EmitAttribute (TypeBuilder builder)
1899 if (ResolveBuilder ())
1900 builder.SetCustomAttribute (GetCtorMetaInfo (), AttributeEncoder.Empty);
1903 public void EmitAttribute (AssemblyBuilder builder)
1905 if (ResolveBuilder ())
1906 builder.SetCustomAttribute (GetCtorMetaInfo (), AttributeEncoder.Empty);
1909 public void EmitAttribute (ModuleBuilder builder)
1911 if (ResolveBuilder ())
1912 builder.SetCustomAttribute (GetCtorMetaInfo (), AttributeEncoder.Empty);
1915 public void EmitAttribute (ParameterBuilder builder)
1917 if (ResolveBuilder ())
1918 builder.SetCustomAttribute (GetCtorMetaInfo (), AttributeEncoder.Empty);
1921 ConstructorInfo GetCtorMetaInfo ()
1923 return (ConstructorInfo) ctor.GetMetaInfo ();
1926 public bool ResolveBuilder ()
1932 // Handle all parameter-less attributes as optional
1937 ctor = (MethodSpec) MemberCache.FindMember (type, MemberFilter.Constructor (ParametersCompiled.EmptyReadOnlyParameters), BindingRestriction.DeclaredOnly);
1938 return ctor != null;
1942 public class PredefinedDebuggerBrowsableAttribute : PredefinedAttribute
1944 public PredefinedDebuggerBrowsableAttribute (ModuleContainer module, string ns, string name)
1945 : base (module, ns, name)
1949 public void EmitAttribute (FieldBuilder builder, System.Diagnostics.DebuggerBrowsableState state)
1951 var ctor = module.PredefinedMembers.DebuggerBrowsableAttributeCtor.Get ();
1955 AttributeEncoder encoder = new AttributeEncoder ();
1956 encoder.Encode ((int) state);
1957 encoder.EncodeEmptyNamedArguments ();
1959 builder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), encoder.ToArray ());
1963 public class PredefinedDebuggableAttribute : PredefinedAttribute
1965 public PredefinedDebuggableAttribute (ModuleContainer module, string ns, string name)
1966 : base (module, ns, name)
1970 public void EmitAttribute (AssemblyBuilder builder, System.Diagnostics.DebuggableAttribute.DebuggingModes modes)
1972 var atype = module.PredefinedAttributes.Debuggable;
1973 if (!atype.Define ())
1976 MethodSpec ctor = null;
1977 foreach (MethodSpec m in MemberCache.FindMembers (atype.TypeSpec, CSharp.Constructor.ConstructorName, true)) {
1978 if (m.Parameters.Count != 1)
1981 if (m.Parameters.Types[0].Kind == MemberKind.Enum) {
1989 AttributeEncoder encoder = new AttributeEncoder ();
1990 encoder.Encode ((int) modes);
1991 encoder.EncodeEmptyNamedArguments ();
1993 builder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), encoder.ToArray ());
1997 public class PredefinedDecimalAttribute : PredefinedAttribute
1999 public PredefinedDecimalAttribute (ModuleContainer module, string ns, string name)
2000 : base (module, ns, name)
2004 public void EmitAttribute (ParameterBuilder builder, decimal value, Location loc)
2006 var ctor = module.PredefinedMembers.DecimalConstantAttributeCtor.Resolve (loc);
2010 int[] bits = decimal.GetBits (value);
2011 AttributeEncoder encoder = new AttributeEncoder ();
2012 encoder.Encode ((byte) (bits[3] >> 16));
2013 encoder.Encode ((byte) (bits[3] >> 31));
2014 encoder.Encode ((uint) bits[2]);
2015 encoder.Encode ((uint) bits[1]);
2016 encoder.Encode ((uint) bits[0]);
2017 encoder.EncodeEmptyNamedArguments ();
2019 builder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), encoder.ToArray ());
2022 public void EmitAttribute (FieldBuilder builder, decimal value, Location loc)
2024 var ctor = module.PredefinedMembers.DecimalConstantAttributeCtor.Resolve (loc);
2028 int[] bits = decimal.GetBits (value);
2029 AttributeEncoder encoder = new AttributeEncoder ();
2030 encoder.Encode ((byte) ((bits[3] & 0xFF0000) >> 16)); // Scale
2031 encoder.Encode ((byte) ((bits[3] >> 31) << 7)); // Sign encoded as 0x80 for negative, 0x0 for possitive
2032 encoder.Encode ((uint) bits[2]);
2033 encoder.Encode ((uint) bits[1]);
2034 encoder.Encode ((uint) bits[0]);
2035 encoder.EncodeEmptyNamedArguments ();
2037 builder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), encoder.ToArray ());
2041 public class PredefinedStateMachineAttribute : PredefinedAttribute
2043 public PredefinedStateMachineAttribute (ModuleContainer module, string ns, string name)
2044 : base (module, ns, name)
2048 public void EmitAttribute (MethodBuilder builder, StateMachine type)
2050 var predefined_ctor = module.PredefinedMembers.AsyncStateMachineAttributeCtor;
2052 var ctor = predefined_ctor.Get ();
2057 AttributeEncoder encoder = new AttributeEncoder ();
2058 encoder.EncodeTypeName (type);
2059 encoder.EncodeEmptyNamedArguments ();
2061 builder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), encoder.ToArray ());
2065 public class PredefinedDynamicAttribute : PredefinedAttribute
2069 public PredefinedDynamicAttribute (ModuleContainer module, string ns, string name)
2070 : base (module, ns, name)
2074 public void EmitAttribute (FieldBuilder builder, TypeSpec type, Location loc)
2076 if (ResolveTransformationCtor (loc)) {
2077 var cab = new CustomAttributeBuilder ((ConstructorInfo) tctor.GetMetaInfo (), new object[] { GetTransformationFlags (type) });
2078 builder.SetCustomAttribute (cab);
2082 public void EmitAttribute (ParameterBuilder builder, TypeSpec type, Location loc)
2084 if (ResolveTransformationCtor (loc)) {
2085 var cab = new CustomAttributeBuilder ((ConstructorInfo) tctor.GetMetaInfo (), new object[] { GetTransformationFlags (type) });
2086 builder.SetCustomAttribute (cab);
2090 public void EmitAttribute (PropertyBuilder builder, TypeSpec type, Location loc)
2092 if (ResolveTransformationCtor (loc)) {
2093 var cab = new CustomAttributeBuilder ((ConstructorInfo) tctor.GetMetaInfo (), new object[] { GetTransformationFlags (type) });
2094 builder.SetCustomAttribute (cab);
2098 public void EmitAttribute (TypeBuilder builder, TypeSpec type, Location loc)
2100 if (ResolveTransformationCtor (loc)) {
2101 var cab = new CustomAttributeBuilder ((ConstructorInfo) tctor.GetMetaInfo (), new object[] { GetTransformationFlags (type) });
2102 builder.SetCustomAttribute (cab);
2107 // When any element of the type is a dynamic type
2109 // This method builds a transformation array for dynamic types
2110 // used in places where DynamicAttribute cannot be applied to.
2111 // It uses bool flag when type is of dynamic type and each
2112 // section always starts with "false" for some reason.
2114 // LAMESPEC: This should be part of C# specification
2116 // Example: Func<dynamic, int, dynamic[]>
2117 // Transformation: { false, true, false, false, true }
2119 static bool[] GetTransformationFlags (TypeSpec t)
2122 var ac = t as ArrayContainer;
2124 element = GetTransformationFlags (ac.Element);
2125 if (element == null)
2126 return new bool[] { false, false };
2128 bool[] res = new bool[element.Length + 1];
2130 Array.Copy (element, 0, res, 1, element.Length);
2138 List<bool> transform = null;
2139 var targs = t.TypeArguments;
2140 for (int i = 0; i < targs.Length; ++i) {
2141 element = GetTransformationFlags (targs[i]);
2142 if (element != null) {
2143 if (transform == null) {
2144 transform = new List<bool> ();
2145 for (int ii = 0; ii <= i; ++ii)
2146 transform.Add (false);
2149 transform.AddRange (element);
2150 } else if (transform != null) {
2151 transform.Add (false);
2155 if (transform != null)
2156 return transform.ToArray ();
2159 if (t.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
2160 return new bool[] { true };
2165 bool ResolveTransformationCtor (Location loc)
2170 tctor = module.PredefinedMembers.DynamicAttributeCtor.Resolve (loc);
2171 return tctor != null;