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.CreateConstant (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 TypeManager.CSharpName (Type), 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 TypeManager.CSharpName (Type);
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, TypeManager.CSharpName (Type), 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 ();
1059 foreach (Attributable target in targets)
1060 target.ApplyAttributeBuilder (this, ctor, cdata, predefined);
1061 } catch (Exception e) {
1062 if (e is BadImageFormat && Report.Errors > 0)
1065 Error_AttributeEmitError (e.Message);
1069 if (!usage_attr.AllowMultiple && allEmitted != null) {
1070 if (allEmitted.ContainsKey (this)) {
1071 var a = allEmitted [this];
1073 a = new List<Attribute> (2);
1074 allEmitted [this] = a;
1078 allEmitted.Add (this, null);
1082 if (!context.Module.Compiler.Settings.VerifyClsCompliance)
1085 // Here we are testing attribute arguments for array usage (error 3016)
1086 if (Owner.IsClsComplianceRequired ()) {
1087 if (pos_args != null)
1088 pos_args.CheckArrayAsAttribute (context.Module.Compiler);
1090 if (NamedArguments == null)
1093 NamedArguments.CheckArrayAsAttribute (context.Module.Compiler);
1097 private Expression GetValue ()
1099 if (pos_args == null || pos_args.Count < 1)
1102 return pos_args[0].Expr;
1105 public string GetString ()
1107 Expression e = GetValue ();
1108 if (e is StringConstant)
1109 return ((StringConstant)e).Value;
1113 public bool GetBoolean ()
1115 Expression e = GetValue ();
1116 if (e is BoolConstant)
1117 return ((BoolConstant)e).Value;
1121 public TypeSpec GetArgumentType ()
1123 TypeOf e = GetValue () as TypeOf;
1126 return e.TypeArgument;
1130 public class Attributes
1132 public readonly List<Attribute> Attrs;
1134 public Attributes (Attribute a)
1136 Attrs = new List<Attribute> ();
1140 public Attributes (List<Attribute> attrs)
1145 public void AddAttribute (Attribute attr)
1150 public void AddAttributes (List<Attribute> attrs)
1152 Attrs.AddRange (attrs);
1155 public void AttachTo (Attributable attributable, IMemberContext context)
1157 foreach (Attribute a in Attrs)
1158 a.AttachTo (attributable, context);
1161 public Attributes Clone ()
1163 var al = new List<Attribute> (Attrs.Count);
1164 foreach (Attribute a in Attrs)
1165 al.Add (a.Clone ());
1167 return new Attributes (al);
1171 /// Checks whether attribute target is valid for the current element
1173 public bool CheckTargets ()
1175 for (int i = 0; i < Attrs.Count; ++i) {
1176 if (!Attrs [i].CheckTarget ())
1177 Attrs.RemoveAt (i--);
1183 public void ConvertGlobalAttributes (TypeContainer member, NamespaceContainer currentNamespace, bool isGlobal)
1185 var member_explicit_targets = member.ValidAttributeTargets;
1186 for (int i = 0; i < Attrs.Count; ++i) {
1187 var attr = Attrs[0];
1188 if (attr.ExplicitTarget == null)
1192 for (ii = 0; ii < member_explicit_targets.Length; ++ii) {
1193 if (attr.ExplicitTarget == member_explicit_targets[ii]) {
1199 if (ii < 0 || !isGlobal)
1202 member.Module.AddAttribute (attr, currentNamespace);
1208 public bool HasResolveError()
1210 foreach (var a in Attrs) {
1218 public Attribute Search (PredefinedAttribute t)
1220 return Search (null, t);
1223 public Attribute Search (string explicitTarget, PredefinedAttribute t)
1225 foreach (Attribute a in Attrs) {
1226 if (explicitTarget != null && a.ExplicitTarget != explicitTarget)
1229 if (a.ResolveTypeForComparison () == t)
1236 /// Returns all attributes of type 't'. Use it when attribute is AllowMultiple = true
1238 public Attribute[] SearchMulti (PredefinedAttribute t)
1240 List<Attribute> ar = null;
1242 foreach (Attribute a in Attrs) {
1243 if (a.ResolveTypeForComparison () == t) {
1245 ar = new List<Attribute> (Attrs.Count);
1250 return ar == null ? null : ar.ToArray ();
1257 Dictionary<Attribute, List<Attribute>> ld = Attrs.Count > 1 ? new Dictionary<Attribute, List<Attribute>> () : null;
1259 foreach (Attribute a in Attrs)
1262 if (ld == null || ld.Count == 0)
1265 foreach (var d in ld) {
1266 if (d.Value == null)
1269 Attribute a = d.Key;
1271 foreach (Attribute collision in d.Value)
1272 a.Report.SymbolRelatedToPreviousError (collision.Location, "");
1274 a.Report.Error (579, a.Location, "The attribute `{0}' cannot be applied multiple times",
1275 a.GetSignatureForError ());
1279 public bool Contains (PredefinedAttribute t)
1281 return Search (t) != null;
1285 public sealed class AttributeEncoder
1288 public enum EncodedTypeProperties
1292 TypeParameter = 1 << 1
1295 public static readonly byte[] Empty;
1299 const ushort Version = 1;
1301 static AttributeEncoder ()
1303 Empty = new byte[4];
1304 Empty[0] = (byte) Version;
1307 public AttributeEncoder ()
1309 buffer = new byte[32];
1313 public void Encode (bool value)
1315 Encode (value ? (byte) 1 : (byte) 0);
1318 public void Encode (byte value)
1320 if (pos == buffer.Length)
1323 buffer [pos++] = value;
1326 public void Encode (sbyte value)
1328 Encode ((byte) value);
1331 public void Encode (short value)
1333 if (pos + 2 > buffer.Length)
1336 buffer[pos++] = (byte) value;
1337 buffer[pos++] = (byte) (value >> 8);
1340 public void Encode (ushort value)
1342 Encode ((short) value);
1345 public void Encode (int value)
1347 if (pos + 4 > buffer.Length)
1350 buffer[pos++] = (byte) value;
1351 buffer[pos++] = (byte) (value >> 8);
1352 buffer[pos++] = (byte) (value >> 16);
1353 buffer[pos++] = (byte) (value >> 24);
1356 public void Encode (uint value)
1358 Encode ((int) value);
1361 public void Encode (long value)
1363 if (pos + 8 > buffer.Length)
1366 buffer[pos++] = (byte) value;
1367 buffer[pos++] = (byte) (value >> 8);
1368 buffer[pos++] = (byte) (value >> 16);
1369 buffer[pos++] = (byte) (value >> 24);
1370 buffer[pos++] = (byte) (value >> 32);
1371 buffer[pos++] = (byte) (value >> 40);
1372 buffer[pos++] = (byte) (value >> 48);
1373 buffer[pos++] = (byte) (value >> 56);
1376 public void Encode (ulong value)
1378 Encode ((long) value);
1381 public void Encode (float value)
1383 Encode (SingleConverter.SingleToInt32Bits (value));
1386 public void Encode (double value)
1388 Encode (BitConverter.DoubleToInt64Bits (value));
1391 public void Encode (string value)
1393 if (value == null) {
1394 Encode ((byte) 0xFF);
1398 var buf = Encoding.UTF8.GetBytes(value);
1399 WriteCompressedValue (buf.Length);
1401 if (pos + buf.Length > buffer.Length)
1404 Buffer.BlockCopy (buf, 0, buffer, pos, buf.Length);
1408 public EncodedTypeProperties Encode (TypeSpec type)
1410 switch (type.BuiltinType) {
1411 case BuiltinTypeSpec.Type.Bool:
1412 Encode ((byte) 0x02);
1414 case BuiltinTypeSpec.Type.Char:
1415 Encode ((byte) 0x03);
1417 case BuiltinTypeSpec.Type.SByte:
1418 Encode ((byte) 0x04);
1420 case BuiltinTypeSpec.Type.Byte:
1421 Encode ((byte) 0x05);
1423 case BuiltinTypeSpec.Type.Short:
1424 Encode ((byte) 0x06);
1426 case BuiltinTypeSpec.Type.UShort:
1427 Encode ((byte) 0x07);
1429 case BuiltinTypeSpec.Type.Int:
1430 Encode ((byte) 0x08);
1432 case BuiltinTypeSpec.Type.UInt:
1433 Encode ((byte) 0x09);
1435 case BuiltinTypeSpec.Type.Long:
1436 Encode ((byte) 0x0A);
1438 case BuiltinTypeSpec.Type.ULong:
1439 Encode ((byte) 0x0B);
1441 case BuiltinTypeSpec.Type.Float:
1442 Encode ((byte) 0x0C);
1444 case BuiltinTypeSpec.Type.Double:
1445 Encode ((byte) 0x0D);
1447 case BuiltinTypeSpec.Type.String:
1448 Encode ((byte) 0x0E);
1450 case BuiltinTypeSpec.Type.Type:
1451 Encode ((byte) 0x50);
1453 case BuiltinTypeSpec.Type.Object:
1454 Encode ((byte) 0x51);
1456 case BuiltinTypeSpec.Type.Dynamic:
1457 Encode ((byte) 0x51);
1458 return EncodedTypeProperties.DynamicType;
1461 Encode ((byte) 0x1D);
1462 return Encode (TypeManager.GetElementType (type));
1465 if (type.Kind == MemberKind.Enum) {
1466 Encode ((byte) 0x55);
1467 EncodeTypeName (type);
1473 return EncodedTypeProperties.None;
1476 public void EncodeTypeName (TypeSpec type)
1478 var old_type = type.GetMetaInfo ();
1479 Encode (type.MemberDefinition.IsImported ? old_type.AssemblyQualifiedName : old_type.FullName);
1482 public void EncodeTypeName (TypeContainer type)
1484 Encode (type.GetSignatureForMetadata ());
1489 // Encodes single property named argument per call
1491 public void EncodeNamedPropertyArgument (PropertySpec property, Constant value)
1493 Encode ((ushort) 1); // length
1494 Encode ((byte) 0x54); // property
1495 Encode (property.MemberType);
1496 Encode (property.Name);
1497 value.EncodeAttributeValue (null, this, property.MemberType);
1501 // Encodes single field named argument per call
1503 public void EncodeNamedFieldArgument (FieldSpec field, Constant value)
1505 Encode ((ushort) 1); // length
1506 Encode ((byte) 0x53); // field
1507 Encode (field.MemberType);
1508 Encode (field.Name);
1509 value.EncodeAttributeValue (null, this, field.MemberType);
1512 public void EncodeNamedArguments<T> (T[] members, Constant[] values) where T : MemberSpec, IInterfaceMemberSpec
1514 Encode ((ushort) members.Length);
1516 for (int i = 0; i < members.Length; ++i)
1518 var member = members[i];
1520 if (member.Kind == MemberKind.Field)
1521 Encode ((byte) 0x53);
1522 else if (member.Kind == MemberKind.Property)
1523 Encode ((byte) 0x54);
1525 throw new NotImplementedException (member.Kind.ToString ());
1527 Encode (member.MemberType);
1528 Encode (member.Name);
1529 values [i].EncodeAttributeValue (null, this, member.MemberType);
1533 public void EncodeEmptyNamedArguments ()
1535 Encode ((ushort) 0);
1540 int size = System.Math.Max (pos * 4, pos + inc + 2);
1541 Array.Resize (ref buffer, size);
1544 void WriteCompressedValue (int value)
1547 Encode ((byte) value);
1551 if (value < 0x4000) {
1552 Encode ((byte) (0x80 | (value >> 8)));
1553 Encode ((byte) value);
1560 public byte[] ToArray ()
1562 byte[] buf = new byte[pos];
1563 Array.Copy (buffer, buf, pos);
1570 /// Helper class for attribute verification routine.
1572 static class AttributeTester
1575 /// Common method for Obsolete error/warning reporting.
1577 public static void Report_ObsoleteMessage (ObsoleteAttribute oa, string member, Location loc, Report Report)
1580 Report.Error (619, loc, "`{0}' is obsolete: `{1}'", member, oa.Message);
1584 if (oa.Message == null || oa.Message.Length == 0) {
1585 Report.Warning (612, 1, loc, "`{0}' is obsolete", member);
1588 Report.Warning (618, 2, loc, "`{0}' is obsolete: `{1}'", member, oa.Message);
1593 // Predefined attribute types
1595 public class PredefinedAttributes
1597 // Build-in attributes
1598 public readonly PredefinedAttribute ParamArray;
1599 public readonly PredefinedAttribute Out;
1601 // Optional attributes
1602 public readonly PredefinedAttribute Obsolete;
1603 public readonly PredefinedAttribute DllImport;
1604 public readonly PredefinedAttribute MethodImpl;
1605 public readonly PredefinedAttribute MarshalAs;
1606 public readonly PredefinedAttribute In;
1607 public readonly PredefinedAttribute IndexerName;
1608 public readonly PredefinedAttribute Conditional;
1609 public readonly PredefinedAttribute CLSCompliant;
1610 public readonly PredefinedAttribute Security;
1611 public readonly PredefinedAttribute Required;
1612 public readonly PredefinedAttribute Guid;
1613 public readonly PredefinedAttribute AssemblyCulture;
1614 public readonly PredefinedAttribute AssemblyVersion;
1615 public readonly PredefinedAttribute AssemblyAlgorithmId;
1616 public readonly PredefinedAttribute AssemblyFlags;
1617 public readonly PredefinedAttribute AssemblyFileVersion;
1618 public readonly PredefinedAttribute ComImport;
1619 public readonly PredefinedAttribute CoClass;
1620 public readonly PredefinedAttribute AttributeUsage;
1621 public readonly PredefinedAttribute DefaultParameterValue;
1622 public readonly PredefinedAttribute OptionalParameter;
1623 public readonly PredefinedAttribute UnverifiableCode;
1624 public readonly PredefinedAttribute DefaultCharset;
1625 public readonly PredefinedAttribute TypeForwarder;
1626 public readonly PredefinedAttribute FixedBuffer;
1627 public readonly PredefinedAttribute CompilerGenerated;
1628 public readonly PredefinedAttribute InternalsVisibleTo;
1629 public readonly PredefinedAttribute RuntimeCompatibility;
1630 public readonly PredefinedAttribute DebuggerHidden;
1631 public readonly PredefinedAttribute UnsafeValueType;
1632 public readonly PredefinedAttribute UnmanagedFunctionPointer;
1633 public readonly PredefinedDebuggerBrowsableAttribute DebuggerBrowsable;
1636 public readonly PredefinedAttribute Extension;
1639 public readonly PredefinedDynamicAttribute Dynamic;
1642 public readonly PredefinedStateMachineAttribute AsyncStateMachine;
1643 public readonly PredefinedStateMachineAttribute IteratorStateMachine;
1646 // Optional types which are used as types and for member lookup
1648 public readonly PredefinedAttribute DefaultMember;
1649 public readonly PredefinedDecimalAttribute DecimalConstant;
1650 public readonly PredefinedAttribute StructLayout;
1651 public readonly PredefinedAttribute FieldOffset;
1652 public readonly PredefinedAttribute CallerMemberNameAttribute;
1653 public readonly PredefinedAttribute CallerLineNumberAttribute;
1654 public readonly PredefinedAttribute CallerFilePathAttribute;
1656 public PredefinedAttributes (ModuleContainer module)
1658 ParamArray = new PredefinedAttribute (module, "System", "ParamArrayAttribute");
1659 Out = new PredefinedAttribute (module, "System.Runtime.InteropServices", "OutAttribute");
1660 ParamArray.Resolve ();
1663 Obsolete = new PredefinedAttribute (module, "System", "ObsoleteAttribute");
1664 DllImport = new PredefinedAttribute (module, "System.Runtime.InteropServices", "DllImportAttribute");
1665 MethodImpl = new PredefinedAttribute (module, "System.Runtime.CompilerServices", "MethodImplAttribute");
1666 MarshalAs = new PredefinedAttribute (module, "System.Runtime.InteropServices", "MarshalAsAttribute");
1667 In = new PredefinedAttribute (module, "System.Runtime.InteropServices", "InAttribute");
1668 IndexerName = new PredefinedAttribute (module, "System.Runtime.CompilerServices", "IndexerNameAttribute");
1669 Conditional = new PredefinedAttribute (module, "System.Diagnostics", "ConditionalAttribute");
1670 CLSCompliant = new PredefinedAttribute (module, "System", "CLSCompliantAttribute");
1671 Security = new PredefinedAttribute (module, "System.Security.Permissions", "SecurityAttribute");
1672 Required = new PredefinedAttribute (module, "System.Runtime.CompilerServices", "RequiredAttributeAttribute");
1673 Guid = new PredefinedAttribute (module, "System.Runtime.InteropServices", "GuidAttribute");
1674 AssemblyCulture = new PredefinedAttribute (module, "System.Reflection", "AssemblyCultureAttribute");
1675 AssemblyVersion = new PredefinedAttribute (module, "System.Reflection", "AssemblyVersionAttribute");
1676 AssemblyAlgorithmId = new PredefinedAttribute (module, "System.Reflection", "AssemblyAlgorithmIdAttribute");
1677 AssemblyFlags = new PredefinedAttribute (module, "System.Reflection", "AssemblyFlagsAttribute");
1678 AssemblyFileVersion = new PredefinedAttribute (module, "System.Reflection", "AssemblyFileVersionAttribute");
1679 ComImport = new PredefinedAttribute (module, "System.Runtime.InteropServices", "ComImportAttribute");
1680 CoClass = new PredefinedAttribute (module, "System.Runtime.InteropServices", "CoClassAttribute");
1681 AttributeUsage = new PredefinedAttribute (module, "System", "AttributeUsageAttribute");
1682 DefaultParameterValue = new PredefinedAttribute (module, "System.Runtime.InteropServices", "DefaultParameterValueAttribute");
1683 OptionalParameter = new PredefinedAttribute (module, "System.Runtime.InteropServices", "OptionalAttribute");
1684 UnverifiableCode = new PredefinedAttribute (module, "System.Security", "UnverifiableCodeAttribute");
1686 DefaultCharset = new PredefinedAttribute (module, "System.Runtime.InteropServices", "DefaultCharSetAttribute");
1687 TypeForwarder = new PredefinedAttribute (module, "System.Runtime.CompilerServices", "TypeForwardedToAttribute");
1688 FixedBuffer = new PredefinedAttribute (module, "System.Runtime.CompilerServices", "FixedBufferAttribute");
1689 CompilerGenerated = new PredefinedAttribute (module, "System.Runtime.CompilerServices", "CompilerGeneratedAttribute");
1690 InternalsVisibleTo = new PredefinedAttribute (module, "System.Runtime.CompilerServices", "InternalsVisibleToAttribute");
1691 RuntimeCompatibility = new PredefinedAttribute (module, "System.Runtime.CompilerServices", "RuntimeCompatibilityAttribute");
1692 DebuggerHidden = new PredefinedAttribute (module, "System.Diagnostics", "DebuggerHiddenAttribute");
1693 UnsafeValueType = new PredefinedAttribute (module, "System.Runtime.CompilerServices", "UnsafeValueTypeAttribute");
1694 UnmanagedFunctionPointer = new PredefinedAttribute (module, "System.Runtime.InteropServices", "UnmanagedFunctionPointerAttribute");
1695 DebuggerBrowsable = new PredefinedDebuggerBrowsableAttribute (module, "System.Diagnostics", "DebuggerBrowsableAttribute");
1697 Extension = new PredefinedAttribute (module, "System.Runtime.CompilerServices", "ExtensionAttribute");
1699 Dynamic = new PredefinedDynamicAttribute (module, "System.Runtime.CompilerServices", "DynamicAttribute");
1701 DefaultMember = new PredefinedAttribute (module, "System.Reflection", "DefaultMemberAttribute");
1702 DecimalConstant = new PredefinedDecimalAttribute (module, "System.Runtime.CompilerServices", "DecimalConstantAttribute");
1703 StructLayout = new PredefinedAttribute (module, "System.Runtime.InteropServices", "StructLayoutAttribute");
1704 FieldOffset = new PredefinedAttribute (module, "System.Runtime.InteropServices", "FieldOffsetAttribute");
1706 AsyncStateMachine = new PredefinedStateMachineAttribute (module, "System.Runtime.CompilerServices", "AsyncStateMachineAttribute");
1707 IteratorStateMachine = new PredefinedStateMachineAttribute (module, "System.Runtime.CompilerServices", "IteratorStateMachineAttribute") {
1711 CallerMemberNameAttribute = new PredefinedAttribute (module, "System.Runtime.CompilerServices", "CallerMemberNameAttribute");
1712 CallerLineNumberAttribute = new PredefinedAttribute (module, "System.Runtime.CompilerServices", "CallerLineNumberAttribute");
1713 CallerFilePathAttribute = new PredefinedAttribute (module, "System.Runtime.CompilerServices", "CallerFilePathAttribute");
1715 // TODO: Should define only attributes which are used for comparison
1716 const System.Reflection.BindingFlags all_fields = System.Reflection.BindingFlags.Public |
1717 System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.DeclaredOnly;
1719 foreach (var fi in GetType ().GetFields (all_fields)) {
1720 ((PredefinedAttribute) fi.GetValue (this)).Define ();
1725 public class PredefinedAttribute : PredefinedType
1727 protected MethodSpec ctor;
1729 public PredefinedAttribute (ModuleContainer module, string ns, string name)
1730 : base (module, MemberKind.Class, ns, name)
1736 public MethodSpec Constructor {
1744 public static bool operator == (TypeSpec type, PredefinedAttribute pa)
1746 return type == pa.type && pa.type != null;
1749 public static bool operator != (TypeSpec type, PredefinedAttribute pa)
1751 return type != pa.type;
1754 public override int GetHashCode ()
1756 return base.GetHashCode ();
1759 public override bool Equals (object obj)
1761 throw new NotSupportedException ();
1764 public void EmitAttribute (ConstructorBuilder builder)
1766 if (ResolveBuilder ())
1767 builder.SetCustomAttribute (GetCtorMetaInfo (), AttributeEncoder.Empty);
1770 public void EmitAttribute (MethodBuilder builder)
1772 if (ResolveBuilder ())
1773 builder.SetCustomAttribute (GetCtorMetaInfo (), AttributeEncoder.Empty);
1776 public void EmitAttribute (PropertyBuilder builder)
1778 if (ResolveBuilder ())
1779 builder.SetCustomAttribute (GetCtorMetaInfo (), AttributeEncoder.Empty);
1782 public void EmitAttribute (FieldBuilder builder)
1784 if (ResolveBuilder ())
1785 builder.SetCustomAttribute (GetCtorMetaInfo (), AttributeEncoder.Empty);
1788 public void EmitAttribute (TypeBuilder builder)
1790 if (ResolveBuilder ())
1791 builder.SetCustomAttribute (GetCtorMetaInfo (), AttributeEncoder.Empty);
1794 public void EmitAttribute (AssemblyBuilder builder)
1796 if (ResolveBuilder ())
1797 builder.SetCustomAttribute (GetCtorMetaInfo (), AttributeEncoder.Empty);
1800 public void EmitAttribute (ModuleBuilder builder)
1802 if (ResolveBuilder ())
1803 builder.SetCustomAttribute (GetCtorMetaInfo (), AttributeEncoder.Empty);
1806 public void EmitAttribute (ParameterBuilder builder)
1808 if (ResolveBuilder ())
1809 builder.SetCustomAttribute (GetCtorMetaInfo (), AttributeEncoder.Empty);
1812 ConstructorInfo GetCtorMetaInfo ()
1814 return (ConstructorInfo) ctor.GetMetaInfo ();
1817 public bool ResolveBuilder ()
1823 // Handle all parameter-less attributes as optional
1828 ctor = (MethodSpec) MemberCache.FindMember (type, MemberFilter.Constructor (ParametersCompiled.EmptyReadOnlyParameters), BindingRestriction.DeclaredOnly);
1829 return ctor != null;
1833 public class PredefinedDebuggerBrowsableAttribute : PredefinedAttribute
1835 public PredefinedDebuggerBrowsableAttribute (ModuleContainer module, string ns, string name)
1836 : base (module, ns, name)
1840 public void EmitAttribute (FieldBuilder builder, System.Diagnostics.DebuggerBrowsableState state)
1842 var ctor = module.PredefinedMembers.DebuggerBrowsableAttributeCtor.Get ();
1846 AttributeEncoder encoder = new AttributeEncoder ();
1847 encoder.Encode ((int) state);
1848 encoder.EncodeEmptyNamedArguments ();
1850 builder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), encoder.ToArray ());
1854 public class PredefinedDecimalAttribute : PredefinedAttribute
1856 public PredefinedDecimalAttribute (ModuleContainer module, string ns, string name)
1857 : base (module, ns, name)
1861 public void EmitAttribute (ParameterBuilder builder, decimal value, Location loc)
1863 var ctor = module.PredefinedMembers.DecimalConstantAttributeCtor.Resolve (loc);
1867 int[] bits = decimal.GetBits (value);
1868 AttributeEncoder encoder = new AttributeEncoder ();
1869 encoder.Encode ((byte) (bits[3] >> 16));
1870 encoder.Encode ((byte) (bits[3] >> 31));
1871 encoder.Encode ((uint) bits[2]);
1872 encoder.Encode ((uint) bits[1]);
1873 encoder.Encode ((uint) bits[0]);
1874 encoder.EncodeEmptyNamedArguments ();
1876 builder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), encoder.ToArray ());
1879 public void EmitAttribute (FieldBuilder builder, decimal value, Location loc)
1881 var ctor = module.PredefinedMembers.DecimalConstantAttributeCtor.Resolve (loc);
1885 int[] bits = decimal.GetBits (value);
1886 AttributeEncoder encoder = new AttributeEncoder ();
1887 encoder.Encode ((byte) (bits[3] >> 16));
1888 encoder.Encode ((byte) (bits[3] >> 31));
1889 encoder.Encode ((uint) bits[2]);
1890 encoder.Encode ((uint) bits[1]);
1891 encoder.Encode ((uint) bits[0]);
1892 encoder.EncodeEmptyNamedArguments ();
1894 builder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), encoder.ToArray ());
1898 public class PredefinedStateMachineAttribute : PredefinedAttribute
1900 public PredefinedStateMachineAttribute (ModuleContainer module, string ns, string name)
1901 : base (module, ns, name)
1905 public bool IsIterator { get; set; }
1907 public void EmitAttribute (MethodBuilder builder, StateMachine type)
1909 var predefined_ctor = IsIterator ?
1910 module.PredefinedMembers.IteratorStateMachineAttributeCtor :
1911 module.PredefinedMembers.AsyncStateMachineAttributeCtor;
1913 var ctor = predefined_ctor.Get ();
1918 AttributeEncoder encoder = new AttributeEncoder ();
1919 encoder.EncodeTypeName (type);
1920 encoder.EncodeEmptyNamedArguments ();
1922 builder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), encoder.ToArray ());
1926 public class PredefinedDynamicAttribute : PredefinedAttribute
1930 public PredefinedDynamicAttribute (ModuleContainer module, string ns, string name)
1931 : base (module, ns, name)
1935 public void EmitAttribute (FieldBuilder builder, TypeSpec type, Location loc)
1937 if (ResolveTransformationCtor (loc)) {
1938 var cab = new CustomAttributeBuilder ((ConstructorInfo) tctor.GetMetaInfo (), new object[] { GetTransformationFlags (type) });
1939 builder.SetCustomAttribute (cab);
1943 public void EmitAttribute (ParameterBuilder builder, TypeSpec type, Location loc)
1945 if (ResolveTransformationCtor (loc)) {
1946 var cab = new CustomAttributeBuilder ((ConstructorInfo) tctor.GetMetaInfo (), new object[] { GetTransformationFlags (type) });
1947 builder.SetCustomAttribute (cab);
1951 public void EmitAttribute (PropertyBuilder builder, TypeSpec type, Location loc)
1953 if (ResolveTransformationCtor (loc)) {
1954 var cab = new CustomAttributeBuilder ((ConstructorInfo) tctor.GetMetaInfo (), new object[] { GetTransformationFlags (type) });
1955 builder.SetCustomAttribute (cab);
1959 public void EmitAttribute (TypeBuilder builder, TypeSpec type, Location loc)
1961 if (ResolveTransformationCtor (loc)) {
1962 var cab = new CustomAttributeBuilder ((ConstructorInfo) tctor.GetMetaInfo (), new object[] { GetTransformationFlags (type) });
1963 builder.SetCustomAttribute (cab);
1968 // When any element of the type is a dynamic type
1970 // This method builds a transformation array for dynamic types
1971 // used in places where DynamicAttribute cannot be applied to.
1972 // It uses bool flag when type is of dynamic type and each
1973 // section always starts with "false" for some reason.
1975 // LAMESPEC: This should be part of C# specification
1977 // Example: Func<dynamic, int, dynamic[]>
1978 // Transformation: { false, true, false, false, true }
1980 static bool[] GetTransformationFlags (TypeSpec t)
1983 var ac = t as ArrayContainer;
1985 element = GetTransformationFlags (ac.Element);
1986 if (element == null)
1989 bool[] res = new bool[element.Length + 1];
1991 Array.Copy (element, 0, res, 1, element.Length);
1999 List<bool> transform = null;
2000 var targs = t.TypeArguments;
2001 for (int i = 0; i < targs.Length; ++i) {
2002 element = GetTransformationFlags (targs[i]);
2003 if (element != null) {
2004 if (transform == null) {
2005 transform = new List<bool> ();
2006 for (int ii = 0; ii <= i; ++ii)
2007 transform.Add (false);
2010 transform.AddRange (element);
2011 } else if (transform != null) {
2012 transform.Add (false);
2016 if (transform != null)
2017 return transform.ToArray ();
2020 if (t.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
2021 return new bool[] { true };
2026 bool ResolveTransformationCtor (Location loc)
2031 tctor = module.PredefinedMembers.DynamicAttributeCtor.Resolve (loc);
2032 return tctor != null;