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.
11 // Copyright 2011 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 ());
262 /// This is rather hack. We report many emit attribute error with same error to be compatible with
263 /// csc. But because csc has to report them this way because error came from ilasm we needn't.
265 public void Error_AttributeEmitError (string inner)
267 Report.Error (647, Location, "Error during emitting `{0}' attribute. The reason is `{1}'",
268 Type.GetSignatureForError (), inner);
271 public void Error_InvalidSecurityParent ()
273 Error_AttributeEmitError ("it is attached to invalid parent");
283 /// Tries to resolve the type of the attribute. Flags an error if it can't, and complain is true.
285 void ResolveAttributeType (bool comparisonOnly)
287 SessionReportPrinter resolve_printer = new SessionReportPrinter ();
288 ReportPrinter prev_recorder = Report.SetPrinter (resolve_printer);
290 bool t1_is_attr = false;
291 bool t2_is_attr = false;
293 ATypeNameExpression expanded = null;
295 // TODO: Additional warnings such as CS0436 are swallowed because we don't
299 t1 = expression.ResolveAsType (context);
301 t1_is_attr = t1.IsAttribute;
303 resolve_printer.EndSession ();
308 expanded = (ATypeNameExpression) expression.Clone (null);
309 expanded.Name += "Attribute";
311 t2 = expanded.ResolveAsType (context);
313 t2_is_attr = t2.IsAttribute;
316 context.Module.Compiler.Report.SetPrinter (prev_recorder);
319 if (t1_is_attr && t2_is_attr && t1 != t2) {
320 if (!comparisonOnly) {
321 Report.Error (1614, Location, "`{0}' is ambiguous between `{1}' and `{2}'. Use either `@{0}' or `{0}Attribute'",
322 GetSignatureForError (), expression.GetSignatureForError (), expanded.GetSignatureForError ());
323 resolve_error = true;
342 resolve_error = true;
345 resolve_printer.Merge (prev_recorder);
347 Report.SymbolRelatedToPreviousError (t1);
348 Report.Error (616, Location, "`{0}': is not an attribute class", t1.GetSignatureForError ());
353 Report.SymbolRelatedToPreviousError (t2);
354 Report.Error (616, Location, "`{0}': is not an attribute class", t2.GetSignatureForError ());
358 resolve_printer.Merge (prev_recorder);
361 public TypeSpec ResolveTypeForComparison ()
363 if (Type == null && !resolve_error)
364 ResolveAttributeType (true);
368 public string GetSignatureForError ()
371 return Type.GetSignatureForError ();
373 return expression.GetSignatureForError ();
376 public bool HasSecurityAttribute {
378 PredefinedAttribute pa = context.Module.PredefinedAttributes.Security;
379 return pa.IsDefined && TypeSpec.IsBaseClass (Type, pa.TypeSpec, false);
383 public bool IsValidSecurityAttribute ()
385 return HasSecurityAttribute && IsSecurityActionValid ();
388 static bool IsValidArgumentType (TypeSpec t)
391 var ac = (ArrayContainer) t;
398 switch (t.BuiltinType) {
399 case BuiltinTypeSpec.Type.Int:
400 case BuiltinTypeSpec.Type.UInt:
401 case BuiltinTypeSpec.Type.Long:
402 case BuiltinTypeSpec.Type.ULong:
403 case BuiltinTypeSpec.Type.Float:
404 case BuiltinTypeSpec.Type.Double:
405 case BuiltinTypeSpec.Type.Char:
406 case BuiltinTypeSpec.Type.Short:
407 case BuiltinTypeSpec.Type.Bool:
408 case BuiltinTypeSpec.Type.SByte:
409 case BuiltinTypeSpec.Type.Byte:
410 case BuiltinTypeSpec.Type.UShort:
412 case BuiltinTypeSpec.Type.String:
413 case BuiltinTypeSpec.Type.Object:
414 case BuiltinTypeSpec.Type.Dynamic:
415 case BuiltinTypeSpec.Type.Type:
422 // TODO: Don't use this ambiguous value
424 get { return expression.Name; }
427 public Report Report {
428 get { return context.Module.Compiler.Report; }
431 public MethodSpec Resolve ()
436 resolve_error = true;
440 ResolveAttributeType (false);
445 if (Type.IsAbstract) {
446 Report.Error (653, Location, "Cannot apply attribute class `{0}' because it is abstract", GetSignatureForError ());
450 ObsoleteAttribute obsolete_attr = Type.GetAttributeObsolete ();
451 if (obsolete_attr != null) {
452 AttributeTester.Report_ObsoleteMessage (obsolete_attr, Type.GetSignatureForError (), Location, Report);
455 ResolveContext rc = null;
458 // Try if the attribute is simple and has been resolved before
459 if (pos_args != null || !context.Module.AttributeConstructorCache.TryGetValue (Type, out ctor)) {
460 rc = CreateResolveContext ();
461 ctor = ResolveConstructor (rc);
466 if (pos_args == null && ctor.Parameters.IsEmpty)
467 context.Module.AttributeConstructorCache.Add (Type, ctor);
471 // Add [module: DefaultCharSet] to all DllImport import attributes
473 var module = context.Module;
474 if ((Type == module.PredefinedAttributes.DllImport || Type == module.PredefinedAttributes.UnmanagedFunctionPointer) && module.HasDefaultCharSet) {
476 rc = CreateResolveContext ();
478 AddModuleCharSet (rc);
481 if (NamedArguments != null) {
483 rc = CreateResolveContext ();
485 if (!ResolveNamedArguments (rc))
489 resolve_error = false;
493 MethodSpec ResolveConstructor (ResolveContext ec)
495 if (pos_args != null) {
497 pos_args.Resolve (ec, out dynamic);
499 Error_AttributeArgumentIsDynamic (ec.MemberContext, loc);
504 return Expression.ConstructorLookup (ec, Type, ref pos_args, loc);
507 bool ResolveNamedArguments (ResolveContext ec)
509 int named_arg_count = NamedArguments.Count;
510 var seen_names = new List<string> (named_arg_count);
512 named_values = new List<KeyValuePair<MemberExpr, NamedArgument>> (named_arg_count);
514 foreach (NamedArgument a in NamedArguments) {
515 string name = a.Name;
516 if (seen_names.Contains (name)) {
517 ec.Report.Error (643, a.Location, "Duplicate named attribute `{0}' argument", name);
521 seen_names.Add (name);
525 Expression member = Expression.MemberLookup (ec, false, Type, name, 0, Expression.MemberLookupRestrictions.ExactArity, loc);
527 if (member == null) {
528 member = Expression.MemberLookup (ec, true, Type, name, 0, Expression.MemberLookupRestrictions.ExactArity, loc);
530 if (member != null) {
531 // TODO: ec.Report.SymbolRelatedToPreviousError (member);
532 Expression.ErrorIsInaccesible (ec, member.GetSignatureForError (), loc);
538 Expression.Error_TypeDoesNotContainDefinition (ec, Location, Type, name);
542 if (!(member is PropertyExpr || member is FieldExpr)) {
543 Error_InvalidNamedArgument (ec, a);
547 ObsoleteAttribute obsolete_attr;
549 if (member is PropertyExpr) {
550 var pi = ((PropertyExpr) member).PropertyInfo;
552 if (!pi.HasSet || !pi.HasGet || pi.IsStatic || !pi.Get.IsPublic || !pi.Set.IsPublic) {
553 ec.Report.SymbolRelatedToPreviousError (pi);
554 Error_InvalidNamedArgument (ec, a);
558 if (!IsValidArgumentType (member.Type)) {
559 ec.Report.SymbolRelatedToPreviousError (pi);
560 Error_InvalidNamedArgumentType (ec, a);
564 obsolete_attr = pi.GetAttributeObsolete ();
565 pi.MemberDefinition.SetIsAssigned ();
567 var fi = ((FieldExpr) member).Spec;
569 if (fi.IsReadOnly || fi.IsStatic || !fi.IsPublic) {
570 Error_InvalidNamedArgument (ec, a);
574 if (!IsValidArgumentType (member.Type)) {
575 ec.Report.SymbolRelatedToPreviousError (fi);
576 Error_InvalidNamedArgumentType (ec, a);
580 obsolete_attr = fi.GetAttributeObsolete ();
581 fi.MemberDefinition.SetIsAssigned ();
584 if (obsolete_attr != null && !context.IsObsolete)
585 AttributeTester.Report_ObsoleteMessage (obsolete_attr, member.GetSignatureForError (), member.Location, Report);
587 if (a.Type != member.Type) {
588 a.Expr = Convert.ImplicitConversionRequired (ec, a.Expr, member.Type, a.Expr.Location);
592 named_values.Add (new KeyValuePair<MemberExpr, NamedArgument> ((MemberExpr) member, a));
599 /// Get a string containing a list of valid targets for the attribute 'attr'
601 public string GetValidTargets ()
603 StringBuilder sb = new StringBuilder ();
604 AttributeTargets targets = Type.GetAttributeUsage (context.Module.PredefinedAttributes.AttributeUsage).ValidOn;
606 if ((targets & AttributeTargets.Assembly) != 0)
607 sb.Append ("assembly, ");
609 if ((targets & AttributeTargets.Module) != 0)
610 sb.Append ("module, ");
612 if ((targets & AttributeTargets.Class) != 0)
613 sb.Append ("class, ");
615 if ((targets & AttributeTargets.Struct) != 0)
616 sb.Append ("struct, ");
618 if ((targets & AttributeTargets.Enum) != 0)
619 sb.Append ("enum, ");
621 if ((targets & AttributeTargets.Constructor) != 0)
622 sb.Append ("constructor, ");
624 if ((targets & AttributeTargets.Method) != 0)
625 sb.Append ("method, ");
627 if ((targets & AttributeTargets.Property) != 0)
628 sb.Append ("property, indexer, ");
630 if ((targets & AttributeTargets.Field) != 0)
631 sb.Append ("field, ");
633 if ((targets & AttributeTargets.Event) != 0)
634 sb.Append ("event, ");
636 if ((targets & AttributeTargets.Interface) != 0)
637 sb.Append ("interface, ");
639 if ((targets & AttributeTargets.Parameter) != 0)
640 sb.Append ("parameter, ");
642 if ((targets & AttributeTargets.Delegate) != 0)
643 sb.Append ("delegate, ");
645 if ((targets & AttributeTargets.ReturnValue) != 0)
646 sb.Append ("return, ");
648 if ((targets & AttributeTargets.GenericParameter) != 0)
649 sb.Append ("type parameter, ");
651 return sb.Remove (sb.Length - 2, 2).ToString ();
654 public AttributeUsageAttribute GetAttributeUsageAttribute ()
657 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
658 // But because a lot of attribute class code must be rewritten will be better to wait...
662 return DefaultUsageAttribute;
664 AttributeUsageAttribute usage_attribute = new AttributeUsageAttribute ((AttributeTargets) ((Constant) pos_args[0].Expr).GetValue ());
666 var field = GetNamedValue ("AllowMultiple") as BoolConstant;
668 usage_attribute.AllowMultiple = field.Value;
670 field = GetNamedValue ("Inherited") as BoolConstant;
672 usage_attribute.Inherited = field.Value;
674 return usage_attribute;
678 /// Returns custom name of indexer
680 public string GetIndexerAttributeValue ()
683 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
684 // But because a lot of attribute class code must be rewritten will be better to wait...
687 if (resolve_error || pos_args.Count != 1 || !(pos_args[0].Expr is Constant))
690 return ((Constant) pos_args[0].Expr).GetValue () as string;
694 /// Returns condition of ConditionalAttribute
696 public string GetConditionalAttributeValue ()
699 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
700 // But because a lot of attribute class code must be rewritten will be better to wait...
706 return ((Constant) pos_args[0].Expr).GetValue () as string;
710 /// Creates the instance of ObsoleteAttribute from this attribute instance
712 public ObsoleteAttribute GetObsoleteAttribute ()
715 // corlib only case when obsolete is used before is resolved
716 var c = Type.MemberDefinition as Class;
717 if (c != null && !c.HasMembersDefined)
720 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
721 // But because a lot of attribute class code must be rewritten will be better to wait...
728 if (pos_args == null)
729 return new ObsoleteAttribute ();
731 string msg = ((Constant) pos_args[0].Expr).GetValue () as string;
732 if (pos_args.Count == 1)
733 return new ObsoleteAttribute (msg);
735 return new ObsoleteAttribute (msg, ((BoolConstant) pos_args[1].Expr).Value);
739 /// Returns value of CLSCompliantAttribute contructor parameter but because the method can be called
740 /// before ApplyAttribute. We need to resolve the arguments.
741 /// This situation occurs when class deps is differs from Emit order.
743 public bool GetClsCompliantAttributeValue ()
746 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
747 // But because a lot of attribute class code must be rewritten will be better to wait...
753 return ((BoolConstant) pos_args[0].Expr).Value;
756 public TypeSpec GetCoClassAttributeValue ()
764 return GetArgumentType ();
767 public bool CheckTarget ()
769 string[] valid_targets = Owner.ValidAttributeTargets;
770 if (ExplicitTarget == null || ExplicitTarget == valid_targets [0]) {
771 Target = Owner.AttributeTargets;
775 // TODO: we can skip the first item
776 if (Array.Exists (valid_targets, i => i == ExplicitTarget)) {
777 switch (ExplicitTarget) {
778 case "return": Target = AttributeTargets.ReturnValue; return true;
779 case "param": Target = AttributeTargets.Parameter; return true;
780 case "field": Target = AttributeTargets.Field; return true;
781 case "method": Target = AttributeTargets.Method; return true;
782 case "property": Target = AttributeTargets.Property; return true;
783 case "module": Target = AttributeTargets.Module; return true;
785 throw new InternalErrorException ("Unknown explicit target: " + ExplicitTarget);
788 StringBuilder sb = new StringBuilder ();
789 foreach (string s in valid_targets) {
793 sb.Remove (sb.Length - 2, 2);
794 Report.Warning (657, 1, Location,
795 "`{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",
796 ExplicitTarget, sb.ToString ());
801 /// Tests permitted SecurityAction for assembly or other types
803 bool IsSecurityActionValid ()
805 SecurityAction action = GetSecurityActionValue ();
806 bool for_assembly = Target == AttributeTargets.Assembly || Target == AttributeTargets.Module;
809 #pragma warning disable 618
810 case SecurityAction.Demand:
811 case SecurityAction.Assert:
812 case SecurityAction.Deny:
813 case SecurityAction.PermitOnly:
814 case SecurityAction.LinkDemand:
815 case SecurityAction.InheritanceDemand:
820 case SecurityAction.RequestMinimum:
821 case SecurityAction.RequestOptional:
822 case SecurityAction.RequestRefuse:
826 #pragma warning restore 618
829 Error_AttributeEmitError ("SecurityAction is out of range");
833 Error_AttributeEmitError (String.Concat ("SecurityAction `", action, "' is not valid for this declaration"));
837 System.Security.Permissions.SecurityAction GetSecurityActionValue ()
839 return (SecurityAction) ((Constant) pos_args[0].Expr).GetValue ();
843 /// Creates instance of SecurityAttribute class and add result of CreatePermission method to permission table.
845 /// <returns></returns>
846 public void ExtractSecurityPermissionSet (MethodSpec ctor, ref SecurityType permissions)
849 object[] values = new object[pos_args.Count];
850 for (int i = 0; i < values.Length; ++i)
851 values[i] = ((Constant) pos_args[i].Expr).GetValue ();
854 object[] prop_values;
855 if (named_values == null) {
859 prop = new PropertyInfo[named_values.Count];
860 prop_values = new object [named_values.Count];
861 for (int i = 0; i < prop.Length; ++i) {
862 prop [i] = ((PropertyExpr) named_values [i].Key).PropertyInfo.MetaInfo;
863 prop_values [i] = ((Constant) named_values [i].Value.Expr).GetValue ();
867 if (permissions == null)
868 permissions = new SecurityType ();
870 var cab = new CustomAttributeBuilder ((ConstructorInfo) ctor.GetMetaInfo (), values, prop, prop_values);
871 permissions.Add (cab);
873 throw new NotSupportedException ();
877 public Constant GetNamedValue (string name)
879 if (named_values == null)
882 for (int i = 0; i < named_values.Count; ++i) {
883 if (named_values [i].Value.Name == name)
884 return named_values [i].Value.Expr as Constant;
890 public CharSet GetCharSetValue ()
892 return (CharSet) System.Enum.Parse (typeof (CharSet), ((Constant) pos_args[0].Expr).GetValue ().ToString ());
895 public bool HasField (string fieldName)
897 if (named_values == null)
900 foreach (var na in named_values) {
901 if (na.Value.Name == fieldName)
909 // Returns true for MethodImplAttribute with MethodImplOptions.InternalCall value
911 public bool IsInternalCall ()
913 return (GetMethodImplOptions () & MethodImplOptions.InternalCall) != 0;
916 public MethodImplOptions GetMethodImplOptions ()
918 MethodImplOptions options = 0;
919 if (pos_args.Count == 1) {
920 options = (MethodImplOptions) System.Enum.Parse (typeof (MethodImplOptions), ((Constant) pos_args[0].Expr).GetValue ().ToString ());
921 } else if (HasField ("Value")) {
922 var named = GetNamedValue ("Value");
923 options = (MethodImplOptions) System.Enum.Parse (typeof (MethodImplOptions), named.GetValue ().ToString ());
930 // Returns true for StructLayoutAttribute with LayoutKind.Explicit value
932 public bool IsExplicitLayoutKind ()
934 if (pos_args == null || pos_args.Count != 1)
937 var value = (LayoutKind) System.Enum.Parse (typeof (LayoutKind), ((Constant) pos_args[0].Expr).GetValue ().ToString ());
938 return value == LayoutKind.Explicit;
941 public Expression GetParameterDefaultValue ()
943 if (pos_args == null)
946 return pos_args[0].Expr;
949 public override bool Equals (object obj)
951 Attribute a = obj as Attribute;
955 return Type == a.Type && Target == a.Target;
958 public override int GetHashCode ()
960 return Type.GetHashCode () ^ Target.GetHashCode ();
964 /// Emit attribute for Attributable symbol
966 public void Emit (Dictionary<Attribute, List<Attribute>> allEmitted)
968 var ctor = Resolve ();
972 var predefined = context.Module.PredefinedAttributes;
974 AttributeUsageAttribute usage_attr = Type.GetAttributeUsage (predefined.AttributeUsage);
975 if ((usage_attr.ValidOn & Target) == 0) {
976 Report.Error (592, Location, "The attribute `{0}' is not valid on this declaration type. " +
977 "It is valid on `{1}' declarations only",
978 GetSignatureForError (), GetValidTargets ());
983 if (pos_args == null && named_values == null) {
984 cdata = AttributeEncoder.Empty;
986 AttributeEncoder encoder = new AttributeEncoder ();
988 if (pos_args != null) {
989 var param_types = ctor.Parameters.Types;
990 for (int j = 0; j < pos_args.Count; ++j) {
991 var pt = param_types[j];
992 var arg_expr = pos_args[j].Expr;
994 if ((Type == predefined.IndexerName || Type == predefined.Conditional) && arg_expr is Constant) {
995 string v = ((Constant) arg_expr).GetValue () as string;
996 if (!Tokenizer.IsValidIdentifier (v) || (Type == predefined.IndexerName && Tokenizer.IsKeyword (v))) {
997 context.Module.Compiler.Report.Error (633, arg_expr.Location,
998 "The argument to the `{0}' attribute must be a valid identifier", GetSignatureForError ());
1001 } else if (Type == predefined.Guid) {
1003 string v = ((StringConstant) arg_expr).Value;
1005 } catch (Exception e) {
1006 Error_AttributeEmitError (e.Message);
1009 } else if (Type == predefined.AttributeUsage) {
1010 int v = ((IntConstant) ((EnumConstant) arg_expr).Child).Value;
1012 context.Module.Compiler.Report.Error (591, Location, "Invalid value for argument to `{0}' attribute",
1013 "System.AttributeUsage");
1015 } else if (Type == predefined.MarshalAs) {
1016 if (pos_args.Count == 1) {
1017 var u_type = (UnmanagedType) System.Enum.Parse (typeof (UnmanagedType), ((Constant) pos_args[0].Expr).GetValue ().ToString ());
1018 if (u_type == UnmanagedType.ByValArray && !(Owner is FieldBase)) {
1019 Error_AttributeEmitError ("Specified unmanaged type is only valid on fields");
1022 } else if (Type == predefined.DllImport) {
1023 if (pos_args.Count == 1 && pos_args[0].Expr is Constant) {
1024 var value = ((Constant) pos_args[0].Expr).GetValue () as string;
1025 if (string.IsNullOrEmpty (value))
1026 Error_AttributeEmitError ("DllName cannot be empty or null");
1028 } else if (Type == predefined.MethodImpl && pt.BuiltinType == BuiltinTypeSpec.Type.Short &&
1029 !System.Enum.IsDefined (typeof (MethodImplOptions), ((Constant) arg_expr).GetValue ().ToString ())) {
1030 Error_AttributeEmitError ("Incorrect argument value.");
1035 arg_expr.EncodeAttributeValue (context, encoder, pt);
1039 if (named_values != null) {
1040 encoder.Encode ((ushort) named_values.Count);
1041 foreach (var na in named_values) {
1042 if (na.Key is FieldExpr)
1043 encoder.Encode ((byte) 0x53);
1045 encoder.Encode ((byte) 0x54);
1047 encoder.Encode (na.Key.Type);
1048 encoder.Encode (na.Value.Name);
1049 na.Value.Expr.EncodeAttributeValue (context, encoder, na.Key.Type);
1052 encoder.EncodeEmptyNamedArguments ();
1055 cdata = encoder.ToArray ();
1058 if (!ctor.DeclaringType.IsConditionallyExcluded (context, Location)) {
1060 foreach (Attributable target in targets)
1061 target.ApplyAttributeBuilder (this, ctor, cdata, predefined);
1062 } catch (Exception e) {
1063 if (e is BadImageFormat && Report.Errors > 0)
1066 Error_AttributeEmitError (e.Message);
1071 if (!usage_attr.AllowMultiple && allEmitted != null) {
1072 if (allEmitted.ContainsKey (this)) {
1073 var a = allEmitted [this];
1075 a = new List<Attribute> (2);
1076 allEmitted [this] = a;
1080 allEmitted.Add (this, null);
1084 if (!context.Module.Compiler.Settings.VerifyClsCompliance)
1087 // Here we are testing attribute arguments for array usage (error 3016)
1088 if (Owner.IsClsComplianceRequired ()) {
1089 if (pos_args != null)
1090 pos_args.CheckArrayAsAttribute (context.Module.Compiler);
1092 if (NamedArguments == null)
1095 NamedArguments.CheckArrayAsAttribute (context.Module.Compiler);
1099 private Expression GetValue ()
1101 if (pos_args == null || pos_args.Count < 1)
1104 return pos_args[0].Expr;
1107 public string GetString ()
1109 Expression e = GetValue ();
1110 if (e is StringConstant)
1111 return ((StringConstant)e).Value;
1115 public bool GetBoolean ()
1117 Expression e = GetValue ();
1118 if (e is BoolConstant)
1119 return ((BoolConstant)e).Value;
1123 public TypeSpec GetArgumentType ()
1125 TypeOf e = GetValue () as TypeOf;
1128 return e.TypeArgument;
1132 public class Attributes
1134 public readonly List<Attribute> Attrs;
1136 public Attributes (Attribute a)
1138 Attrs = new List<Attribute> ();
1142 public Attributes (List<Attribute> attrs)
1147 public void AddAttribute (Attribute attr)
1152 public void AddAttributes (List<Attribute> attrs)
1154 Attrs.AddRange (attrs);
1157 public void AttachTo (Attributable attributable, IMemberContext context)
1159 foreach (Attribute a in Attrs)
1160 a.AttachTo (attributable, context);
1163 public Attributes Clone ()
1165 var al = new List<Attribute> (Attrs.Count);
1166 foreach (Attribute a in Attrs)
1167 al.Add (a.Clone ());
1169 return new Attributes (al);
1173 /// Checks whether attribute target is valid for the current element
1175 public bool CheckTargets ()
1177 for (int i = 0; i < Attrs.Count; ++i) {
1178 if (!Attrs [i].CheckTarget ())
1179 Attrs.RemoveAt (i--);
1185 public void ConvertGlobalAttributes (TypeContainer member, NamespaceContainer currentNamespace, bool isGlobal)
1187 var member_explicit_targets = member.ValidAttributeTargets;
1188 for (int i = 0; i < Attrs.Count; ++i) {
1189 var attr = Attrs[0];
1190 if (attr.ExplicitTarget == null)
1194 for (ii = 0; ii < member_explicit_targets.Length; ++ii) {
1195 if (attr.ExplicitTarget == member_explicit_targets[ii]) {
1201 if (ii < 0 || !isGlobal)
1204 member.Module.AddAttribute (attr, currentNamespace);
1210 public bool HasResolveError()
1212 foreach (var a in Attrs) {
1220 public Attribute Search (PredefinedAttribute t)
1222 return Search (null, t);
1225 public Attribute Search (string explicitTarget, PredefinedAttribute t)
1227 foreach (Attribute a in Attrs) {
1228 if (explicitTarget != null && a.ExplicitTarget != explicitTarget)
1231 if (a.ResolveTypeForComparison () == t)
1238 /// Returns all attributes of type 't'. Use it when attribute is AllowMultiple = true
1240 public Attribute[] SearchMulti (PredefinedAttribute t)
1242 List<Attribute> ar = null;
1244 foreach (Attribute a in Attrs) {
1245 if (a.ResolveTypeForComparison () == t) {
1247 ar = new List<Attribute> (Attrs.Count);
1252 return ar == null ? null : ar.ToArray ();
1259 Dictionary<Attribute, List<Attribute>> ld = Attrs.Count > 1 ? new Dictionary<Attribute, List<Attribute>> () : null;
1261 foreach (Attribute a in Attrs)
1264 if (ld == null || ld.Count == 0)
1267 foreach (var d in ld) {
1268 if (d.Value == null)
1271 Attribute a = d.Key;
1273 foreach (Attribute collision in d.Value)
1274 a.Report.SymbolRelatedToPreviousError (collision.Location, "");
1276 a.Report.Error (579, a.Location, "The attribute `{0}' cannot be applied multiple times",
1277 a.GetSignatureForError ());
1281 public bool Contains (PredefinedAttribute t)
1283 return Search (t) != null;
1287 public sealed class AttributeEncoder
1290 public enum EncodedTypeProperties
1294 TypeParameter = 1 << 1
1297 public static readonly byte[] Empty;
1301 const ushort Version = 1;
1303 static AttributeEncoder ()
1305 Empty = new byte[4];
1306 Empty[0] = (byte) Version;
1309 public AttributeEncoder ()
1311 buffer = new byte[32];
1315 public void Encode (bool value)
1317 Encode (value ? (byte) 1 : (byte) 0);
1320 public void Encode (byte value)
1322 if (pos == buffer.Length)
1325 buffer [pos++] = value;
1328 public void Encode (sbyte value)
1330 Encode ((byte) value);
1333 public void Encode (short value)
1335 if (pos + 2 > buffer.Length)
1338 buffer[pos++] = (byte) value;
1339 buffer[pos++] = (byte) (value >> 8);
1342 public void Encode (ushort value)
1344 Encode ((short) value);
1347 public void Encode (int value)
1349 if (pos + 4 > buffer.Length)
1352 buffer[pos++] = (byte) value;
1353 buffer[pos++] = (byte) (value >> 8);
1354 buffer[pos++] = (byte) (value >> 16);
1355 buffer[pos++] = (byte) (value >> 24);
1358 public void Encode (uint value)
1360 Encode ((int) value);
1363 public void Encode (long value)
1365 if (pos + 8 > buffer.Length)
1368 buffer[pos++] = (byte) value;
1369 buffer[pos++] = (byte) (value >> 8);
1370 buffer[pos++] = (byte) (value >> 16);
1371 buffer[pos++] = (byte) (value >> 24);
1372 buffer[pos++] = (byte) (value >> 32);
1373 buffer[pos++] = (byte) (value >> 40);
1374 buffer[pos++] = (byte) (value >> 48);
1375 buffer[pos++] = (byte) (value >> 56);
1378 public void Encode (ulong value)
1380 Encode ((long) value);
1383 public void Encode (float value)
1385 Encode (SingleConverter.SingleToInt32Bits (value));
1388 public void Encode (double value)
1390 Encode (BitConverter.DoubleToInt64Bits (value));
1393 public void Encode (string value)
1395 if (value == null) {
1396 Encode ((byte) 0xFF);
1400 var buf = Encoding.UTF8.GetBytes(value);
1401 WriteCompressedValue (buf.Length);
1403 if (pos + buf.Length > buffer.Length)
1406 Buffer.BlockCopy (buf, 0, buffer, pos, buf.Length);
1410 public EncodedTypeProperties Encode (TypeSpec type)
1412 switch (type.BuiltinType) {
1413 case BuiltinTypeSpec.Type.Bool:
1414 Encode ((byte) 0x02);
1416 case BuiltinTypeSpec.Type.Char:
1417 Encode ((byte) 0x03);
1419 case BuiltinTypeSpec.Type.SByte:
1420 Encode ((byte) 0x04);
1422 case BuiltinTypeSpec.Type.Byte:
1423 Encode ((byte) 0x05);
1425 case BuiltinTypeSpec.Type.Short:
1426 Encode ((byte) 0x06);
1428 case BuiltinTypeSpec.Type.UShort:
1429 Encode ((byte) 0x07);
1431 case BuiltinTypeSpec.Type.Int:
1432 Encode ((byte) 0x08);
1434 case BuiltinTypeSpec.Type.UInt:
1435 Encode ((byte) 0x09);
1437 case BuiltinTypeSpec.Type.Long:
1438 Encode ((byte) 0x0A);
1440 case BuiltinTypeSpec.Type.ULong:
1441 Encode ((byte) 0x0B);
1443 case BuiltinTypeSpec.Type.Float:
1444 Encode ((byte) 0x0C);
1446 case BuiltinTypeSpec.Type.Double:
1447 Encode ((byte) 0x0D);
1449 case BuiltinTypeSpec.Type.String:
1450 Encode ((byte) 0x0E);
1452 case BuiltinTypeSpec.Type.Type:
1453 Encode ((byte) 0x50);
1455 case BuiltinTypeSpec.Type.Object:
1456 Encode ((byte) 0x51);
1458 case BuiltinTypeSpec.Type.Dynamic:
1459 Encode ((byte) 0x51);
1460 return EncodedTypeProperties.DynamicType;
1463 Encode ((byte) 0x1D);
1464 return Encode (TypeManager.GetElementType (type));
1467 if (type.Kind == MemberKind.Enum) {
1468 Encode ((byte) 0x55);
1469 EncodeTypeName (type);
1475 return EncodedTypeProperties.None;
1478 public void EncodeTypeName (TypeSpec type)
1480 var old_type = type.GetMetaInfo ();
1481 Encode (type.MemberDefinition.IsImported ? old_type.AssemblyQualifiedName : old_type.FullName);
1484 public void EncodeTypeName (TypeContainer type)
1486 Encode (type.GetSignatureForMetadata ());
1491 // Encodes single property named argument per call
1493 public void EncodeNamedPropertyArgument (PropertySpec property, Constant value)
1495 Encode ((ushort) 1); // length
1496 Encode ((byte) 0x54); // property
1497 Encode (property.MemberType);
1498 Encode (property.Name);
1499 value.EncodeAttributeValue (null, this, property.MemberType);
1503 // Encodes single field named argument per call
1505 public void EncodeNamedFieldArgument (FieldSpec field, Constant value)
1507 Encode ((ushort) 1); // length
1508 Encode ((byte) 0x53); // field
1509 Encode (field.MemberType);
1510 Encode (field.Name);
1511 value.EncodeAttributeValue (null, this, field.MemberType);
1514 public void EncodeNamedArguments<T> (T[] members, Constant[] values) where T : MemberSpec, IInterfaceMemberSpec
1516 Encode ((ushort) members.Length);
1518 for (int i = 0; i < members.Length; ++i)
1520 var member = members[i];
1522 if (member.Kind == MemberKind.Field)
1523 Encode ((byte) 0x53);
1524 else if (member.Kind == MemberKind.Property)
1525 Encode ((byte) 0x54);
1527 throw new NotImplementedException (member.Kind.ToString ());
1529 Encode (member.MemberType);
1530 Encode (member.Name);
1531 values [i].EncodeAttributeValue (null, this, member.MemberType);
1535 public void EncodeEmptyNamedArguments ()
1537 Encode ((ushort) 0);
1542 int size = System.Math.Max (pos * 4, pos + inc + 2);
1543 Array.Resize (ref buffer, size);
1546 void WriteCompressedValue (int value)
1549 Encode ((byte) value);
1553 if (value < 0x4000) {
1554 Encode ((byte) (0x80 | (value >> 8)));
1555 Encode ((byte) value);
1562 public byte[] ToArray ()
1564 byte[] buf = new byte[pos];
1565 Array.Copy (buffer, buf, pos);
1572 /// Helper class for attribute verification routine.
1574 static class AttributeTester
1577 /// Common method for Obsolete error/warning reporting.
1579 public static void Report_ObsoleteMessage (ObsoleteAttribute oa, string member, Location loc, Report Report)
1582 Report.Error (619, loc, "`{0}' is obsolete: `{1}'", member, oa.Message);
1586 if (oa.Message == null || oa.Message.Length == 0) {
1587 Report.Warning (612, 1, loc, "`{0}' is obsolete", member);
1590 Report.Warning (618, 2, loc, "`{0}' is obsolete: `{1}'", member, oa.Message);
1595 // Predefined attribute types
1597 public class PredefinedAttributes
1599 // Build-in attributes
1600 public readonly PredefinedAttribute ParamArray;
1601 public readonly PredefinedAttribute Out;
1603 // Optional attributes
1604 public readonly PredefinedAttribute Obsolete;
1605 public readonly PredefinedAttribute DllImport;
1606 public readonly PredefinedAttribute MethodImpl;
1607 public readonly PredefinedAttribute MarshalAs;
1608 public readonly PredefinedAttribute In;
1609 public readonly PredefinedAttribute IndexerName;
1610 public readonly PredefinedAttribute Conditional;
1611 public readonly PredefinedAttribute CLSCompliant;
1612 public readonly PredefinedAttribute Security;
1613 public readonly PredefinedAttribute Required;
1614 public readonly PredefinedAttribute Guid;
1615 public readonly PredefinedAttribute AssemblyCulture;
1616 public readonly PredefinedAttribute AssemblyVersion;
1617 public readonly PredefinedAttribute AssemblyAlgorithmId;
1618 public readonly PredefinedAttribute AssemblyFlags;
1619 public readonly PredefinedAttribute AssemblyFileVersion;
1620 public readonly PredefinedAttribute ComImport;
1621 public readonly PredefinedAttribute CoClass;
1622 public readonly PredefinedAttribute AttributeUsage;
1623 public readonly PredefinedAttribute DefaultParameterValue;
1624 public readonly PredefinedAttribute OptionalParameter;
1625 public readonly PredefinedAttribute UnverifiableCode;
1626 public readonly PredefinedAttribute DefaultCharset;
1627 public readonly PredefinedAttribute TypeForwarder;
1628 public readonly PredefinedAttribute FixedBuffer;
1629 public readonly PredefinedAttribute CompilerGenerated;
1630 public readonly PredefinedAttribute InternalsVisibleTo;
1631 public readonly PredefinedAttribute RuntimeCompatibility;
1632 public readonly PredefinedAttribute DebuggerHidden;
1633 public readonly PredefinedAttribute UnsafeValueType;
1634 public readonly PredefinedAttribute UnmanagedFunctionPointer;
1635 public readonly PredefinedDebuggerBrowsableAttribute DebuggerBrowsable;
1638 public readonly PredefinedAttribute Extension;
1641 public readonly PredefinedDynamicAttribute Dynamic;
1644 public readonly PredefinedStateMachineAttribute AsyncStateMachine;
1647 // Optional types which are used as types and for member lookup
1649 public readonly PredefinedAttribute DefaultMember;
1650 public readonly PredefinedDecimalAttribute DecimalConstant;
1651 public readonly PredefinedAttribute StructLayout;
1652 public readonly PredefinedAttribute FieldOffset;
1653 public readonly PredefinedAttribute CallerMemberNameAttribute;
1654 public readonly PredefinedAttribute CallerLineNumberAttribute;
1655 public readonly PredefinedAttribute CallerFilePathAttribute;
1657 public PredefinedAttributes (ModuleContainer module)
1659 ParamArray = new PredefinedAttribute (module, "System", "ParamArrayAttribute");
1660 Out = new PredefinedAttribute (module, "System.Runtime.InteropServices", "OutAttribute");
1661 ParamArray.Resolve ();
1664 Obsolete = new PredefinedAttribute (module, "System", "ObsoleteAttribute");
1665 DllImport = new PredefinedAttribute (module, "System.Runtime.InteropServices", "DllImportAttribute");
1666 MethodImpl = new PredefinedAttribute (module, "System.Runtime.CompilerServices", "MethodImplAttribute");
1667 MarshalAs = new PredefinedAttribute (module, "System.Runtime.InteropServices", "MarshalAsAttribute");
1668 In = new PredefinedAttribute (module, "System.Runtime.InteropServices", "InAttribute");
1669 IndexerName = new PredefinedAttribute (module, "System.Runtime.CompilerServices", "IndexerNameAttribute");
1670 Conditional = new PredefinedAttribute (module, "System.Diagnostics", "ConditionalAttribute");
1671 CLSCompliant = new PredefinedAttribute (module, "System", "CLSCompliantAttribute");
1672 Security = new PredefinedAttribute (module, "System.Security.Permissions", "SecurityAttribute");
1673 Required = new PredefinedAttribute (module, "System.Runtime.CompilerServices", "RequiredAttributeAttribute");
1674 Guid = new PredefinedAttribute (module, "System.Runtime.InteropServices", "GuidAttribute");
1675 AssemblyCulture = new PredefinedAttribute (module, "System.Reflection", "AssemblyCultureAttribute");
1676 AssemblyVersion = new PredefinedAttribute (module, "System.Reflection", "AssemblyVersionAttribute");
1677 AssemblyAlgorithmId = new PredefinedAttribute (module, "System.Reflection", "AssemblyAlgorithmIdAttribute");
1678 AssemblyFlags = new PredefinedAttribute (module, "System.Reflection", "AssemblyFlagsAttribute");
1679 AssemblyFileVersion = new PredefinedAttribute (module, "System.Reflection", "AssemblyFileVersionAttribute");
1680 ComImport = new PredefinedAttribute (module, "System.Runtime.InteropServices", "ComImportAttribute");
1681 CoClass = new PredefinedAttribute (module, "System.Runtime.InteropServices", "CoClassAttribute");
1682 AttributeUsage = new PredefinedAttribute (module, "System", "AttributeUsageAttribute");
1683 DefaultParameterValue = new PredefinedAttribute (module, "System.Runtime.InteropServices", "DefaultParameterValueAttribute");
1684 OptionalParameter = new PredefinedAttribute (module, "System.Runtime.InteropServices", "OptionalAttribute");
1685 UnverifiableCode = new PredefinedAttribute (module, "System.Security", "UnverifiableCodeAttribute");
1687 DefaultCharset = new PredefinedAttribute (module, "System.Runtime.InteropServices", "DefaultCharSetAttribute");
1688 TypeForwarder = new PredefinedAttribute (module, "System.Runtime.CompilerServices", "TypeForwardedToAttribute");
1689 FixedBuffer = new PredefinedAttribute (module, "System.Runtime.CompilerServices", "FixedBufferAttribute");
1690 CompilerGenerated = new PredefinedAttribute (module, "System.Runtime.CompilerServices", "CompilerGeneratedAttribute");
1691 InternalsVisibleTo = new PredefinedAttribute (module, "System.Runtime.CompilerServices", "InternalsVisibleToAttribute");
1692 RuntimeCompatibility = new PredefinedAttribute (module, "System.Runtime.CompilerServices", "RuntimeCompatibilityAttribute");
1693 DebuggerHidden = new PredefinedAttribute (module, "System.Diagnostics", "DebuggerHiddenAttribute");
1694 UnsafeValueType = new PredefinedAttribute (module, "System.Runtime.CompilerServices", "UnsafeValueTypeAttribute");
1695 UnmanagedFunctionPointer = new PredefinedAttribute (module, "System.Runtime.InteropServices", "UnmanagedFunctionPointerAttribute");
1696 DebuggerBrowsable = new PredefinedDebuggerBrowsableAttribute (module, "System.Diagnostics", "DebuggerBrowsableAttribute");
1698 Extension = new PredefinedAttribute (module, "System.Runtime.CompilerServices", "ExtensionAttribute");
1700 Dynamic = new PredefinedDynamicAttribute (module, "System.Runtime.CompilerServices", "DynamicAttribute");
1702 DefaultMember = new PredefinedAttribute (module, "System.Reflection", "DefaultMemberAttribute");
1703 DecimalConstant = new PredefinedDecimalAttribute (module, "System.Runtime.CompilerServices", "DecimalConstantAttribute");
1704 StructLayout = new PredefinedAttribute (module, "System.Runtime.InteropServices", "StructLayoutAttribute");
1705 FieldOffset = new PredefinedAttribute (module, "System.Runtime.InteropServices", "FieldOffsetAttribute");
1707 AsyncStateMachine = new PredefinedStateMachineAttribute (module, "System.Runtime.CompilerServices", "AsyncStateMachineAttribute");
1709 CallerMemberNameAttribute = new PredefinedAttribute (module, "System.Runtime.CompilerServices", "CallerMemberNameAttribute");
1710 CallerLineNumberAttribute = new PredefinedAttribute (module, "System.Runtime.CompilerServices", "CallerLineNumberAttribute");
1711 CallerFilePathAttribute = new PredefinedAttribute (module, "System.Runtime.CompilerServices", "CallerFilePathAttribute");
1713 // TODO: Should define only attributes which are used for comparison
1714 const System.Reflection.BindingFlags all_fields = System.Reflection.BindingFlags.Public |
1715 System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.DeclaredOnly;
1717 foreach (var fi in GetType ().GetFields (all_fields)) {
1718 ((PredefinedAttribute) fi.GetValue (this)).Define ();
1723 public class PredefinedAttribute : PredefinedType
1725 protected MethodSpec ctor;
1727 public PredefinedAttribute (ModuleContainer module, string ns, string name)
1728 : base (module, MemberKind.Class, ns, name)
1734 public MethodSpec Constructor {
1742 public static bool operator == (TypeSpec type, PredefinedAttribute pa)
1744 return type == pa.type && pa.type != null;
1747 public static bool operator != (TypeSpec type, PredefinedAttribute pa)
1749 return type != pa.type;
1752 public override int GetHashCode ()
1754 return base.GetHashCode ();
1757 public override bool Equals (object obj)
1759 throw new NotSupportedException ();
1762 public void EmitAttribute (ConstructorBuilder builder)
1764 if (ResolveBuilder ())
1765 builder.SetCustomAttribute (GetCtorMetaInfo (), AttributeEncoder.Empty);
1768 public void EmitAttribute (MethodBuilder builder)
1770 if (ResolveBuilder ())
1771 builder.SetCustomAttribute (GetCtorMetaInfo (), AttributeEncoder.Empty);
1774 public void EmitAttribute (PropertyBuilder builder)
1776 if (ResolveBuilder ())
1777 builder.SetCustomAttribute (GetCtorMetaInfo (), AttributeEncoder.Empty);
1780 public void EmitAttribute (FieldBuilder builder)
1782 if (ResolveBuilder ())
1783 builder.SetCustomAttribute (GetCtorMetaInfo (), AttributeEncoder.Empty);
1786 public void EmitAttribute (TypeBuilder builder)
1788 if (ResolveBuilder ())
1789 builder.SetCustomAttribute (GetCtorMetaInfo (), AttributeEncoder.Empty);
1792 public void EmitAttribute (AssemblyBuilder builder)
1794 if (ResolveBuilder ())
1795 builder.SetCustomAttribute (GetCtorMetaInfo (), AttributeEncoder.Empty);
1798 public void EmitAttribute (ModuleBuilder builder)
1800 if (ResolveBuilder ())
1801 builder.SetCustomAttribute (GetCtorMetaInfo (), AttributeEncoder.Empty);
1804 public void EmitAttribute (ParameterBuilder builder)
1806 if (ResolveBuilder ())
1807 builder.SetCustomAttribute (GetCtorMetaInfo (), AttributeEncoder.Empty);
1810 ConstructorInfo GetCtorMetaInfo ()
1812 return (ConstructorInfo) ctor.GetMetaInfo ();
1815 public bool ResolveBuilder ()
1821 // Handle all parameter-less attributes as optional
1826 ctor = (MethodSpec) MemberCache.FindMember (type, MemberFilter.Constructor (ParametersCompiled.EmptyReadOnlyParameters), BindingRestriction.DeclaredOnly);
1827 return ctor != null;
1831 public class PredefinedDebuggerBrowsableAttribute : PredefinedAttribute
1833 public PredefinedDebuggerBrowsableAttribute (ModuleContainer module, string ns, string name)
1834 : base (module, ns, name)
1838 public void EmitAttribute (FieldBuilder builder, System.Diagnostics.DebuggerBrowsableState state)
1840 var ctor = module.PredefinedMembers.DebuggerBrowsableAttributeCtor.Get ();
1844 AttributeEncoder encoder = new AttributeEncoder ();
1845 encoder.Encode ((int) state);
1846 encoder.EncodeEmptyNamedArguments ();
1848 builder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), encoder.ToArray ());
1852 public class PredefinedDecimalAttribute : PredefinedAttribute
1854 public PredefinedDecimalAttribute (ModuleContainer module, string ns, string name)
1855 : base (module, ns, name)
1859 public void EmitAttribute (ParameterBuilder builder, decimal value, Location loc)
1861 var ctor = module.PredefinedMembers.DecimalConstantAttributeCtor.Resolve (loc);
1865 int[] bits = decimal.GetBits (value);
1866 AttributeEncoder encoder = new AttributeEncoder ();
1867 encoder.Encode ((byte) (bits[3] >> 16));
1868 encoder.Encode ((byte) (bits[3] >> 31));
1869 encoder.Encode ((uint) bits[2]);
1870 encoder.Encode ((uint) bits[1]);
1871 encoder.Encode ((uint) bits[0]);
1872 encoder.EncodeEmptyNamedArguments ();
1874 builder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), encoder.ToArray ());
1877 public void EmitAttribute (FieldBuilder builder, decimal value, Location loc)
1879 var ctor = module.PredefinedMembers.DecimalConstantAttributeCtor.Resolve (loc);
1883 int[] bits = decimal.GetBits (value);
1884 AttributeEncoder encoder = new AttributeEncoder ();
1885 encoder.Encode ((byte) (bits[3] >> 16));
1886 encoder.Encode ((byte) (bits[3] >> 31));
1887 encoder.Encode ((uint) bits[2]);
1888 encoder.Encode ((uint) bits[1]);
1889 encoder.Encode ((uint) bits[0]);
1890 encoder.EncodeEmptyNamedArguments ();
1892 builder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), encoder.ToArray ());
1896 public class PredefinedStateMachineAttribute : PredefinedAttribute
1898 public PredefinedStateMachineAttribute (ModuleContainer module, string ns, string name)
1899 : base (module, ns, name)
1903 public void EmitAttribute (MethodBuilder builder, StateMachine type)
1905 var predefined_ctor = module.PredefinedMembers.AsyncStateMachineAttributeCtor;
1907 var ctor = predefined_ctor.Get ();
1912 AttributeEncoder encoder = new AttributeEncoder ();
1913 encoder.EncodeTypeName (type);
1914 encoder.EncodeEmptyNamedArguments ();
1916 builder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), encoder.ToArray ());
1920 public class PredefinedDynamicAttribute : PredefinedAttribute
1924 public PredefinedDynamicAttribute (ModuleContainer module, string ns, string name)
1925 : base (module, ns, name)
1929 public void EmitAttribute (FieldBuilder builder, TypeSpec type, Location loc)
1931 if (ResolveTransformationCtor (loc)) {
1932 var cab = new CustomAttributeBuilder ((ConstructorInfo) tctor.GetMetaInfo (), new object[] { GetTransformationFlags (type) });
1933 builder.SetCustomAttribute (cab);
1937 public void EmitAttribute (ParameterBuilder builder, TypeSpec type, Location loc)
1939 if (ResolveTransformationCtor (loc)) {
1940 var cab = new CustomAttributeBuilder ((ConstructorInfo) tctor.GetMetaInfo (), new object[] { GetTransformationFlags (type) });
1941 builder.SetCustomAttribute (cab);
1945 public void EmitAttribute (PropertyBuilder builder, TypeSpec type, Location loc)
1947 if (ResolveTransformationCtor (loc)) {
1948 var cab = new CustomAttributeBuilder ((ConstructorInfo) tctor.GetMetaInfo (), new object[] { GetTransformationFlags (type) });
1949 builder.SetCustomAttribute (cab);
1953 public void EmitAttribute (TypeBuilder builder, TypeSpec type, Location loc)
1955 if (ResolveTransformationCtor (loc)) {
1956 var cab = new CustomAttributeBuilder ((ConstructorInfo) tctor.GetMetaInfo (), new object[] { GetTransformationFlags (type) });
1957 builder.SetCustomAttribute (cab);
1962 // When any element of the type is a dynamic type
1964 // This method builds a transformation array for dynamic types
1965 // used in places where DynamicAttribute cannot be applied to.
1966 // It uses bool flag when type is of dynamic type and each
1967 // section always starts with "false" for some reason.
1969 // LAMESPEC: This should be part of C# specification
1971 // Example: Func<dynamic, int, dynamic[]>
1972 // Transformation: { false, true, false, false, true }
1974 static bool[] GetTransformationFlags (TypeSpec t)
1977 var ac = t as ArrayContainer;
1979 element = GetTransformationFlags (ac.Element);
1980 if (element == null)
1983 bool[] res = new bool[element.Length + 1];
1985 Array.Copy (element, 0, res, 1, element.Length);
1993 List<bool> transform = null;
1994 var targs = t.TypeArguments;
1995 for (int i = 0; i < targs.Length; ++i) {
1996 element = GetTransformationFlags (targs[i]);
1997 if (element != null) {
1998 if (transform == null) {
1999 transform = new List<bool> ();
2000 for (int ii = 0; ii <= i; ++ii)
2001 transform.Add (false);
2004 transform.AddRange (element);
2005 } else if (transform != null) {
2006 transform.Add (false);
2010 if (transform != null)
2011 return transform.ToArray ();
2014 if (t.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
2015 return new bool[] { true };
2020 bool ResolveTransformationCtor (Location loc)
2025 tctor = module.PredefinedMembers.DynamicAttributeCtor.Resolve (loc);
2026 return tctor != null;