2 // attribute.cs: Attributes handling
4 // Author: Ravi Pratap (ravi@ximian.com)
5 // Marek Safar (marek.safar@gmail.com)
7 // Dual licensed under the terms of the MIT X11 or GNU GPL
9 // Copyright 2001-2003 Ximian, Inc (http://www.ximian.com)
10 // Copyright 2003-2008 Novell, Inc.
11 // Copyright 2011-2013 Xamarin Inc
15 using System.Collections.Generic;
16 using System.Runtime.InteropServices;
17 using System.Runtime.CompilerServices;
18 using System.Security;
19 using System.Security.Permissions;
24 using SecurityType = System.Collections.Generic.List<IKVM.Reflection.Emit.CustomAttributeBuilder>;
25 using BadImageFormat = IKVM.Reflection.BadImageFormatException;
26 using IKVM.Reflection;
27 using IKVM.Reflection.Emit;
29 using SecurityType = System.Collections.Generic.Dictionary<System.Security.Permissions.SecurityAction, System.Security.PermissionSet>;
30 using BadImageFormat = System.BadImageFormatException;
31 using System.Reflection;
32 using System.Reflection.Emit;
35 namespace Mono.CSharp {
38 /// Base class for objects that can have Attributes applied to them.
40 public abstract class Attributable {
42 // Holds all attributes attached to this element
44 protected Attributes attributes;
46 public void AddAttributes (Attributes attrs, IMemberContext context)
51 if (attributes == null)
54 attributes.AddAttributes (attrs.Attrs);
56 attrs.AttachTo (this, context);
59 public Attributes OptAttributes {
69 /// Use member-specific procedure to apply attribute @a in @cb to the entity being built in @builder
71 public abstract void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa);
74 /// Returns one AttributeTarget for this element.
76 public abstract AttributeTargets AttributeTargets { get; }
78 public abstract bool IsClsComplianceRequired ();
81 /// Gets list of valid attribute targets for explicit target declaration.
82 /// The first array item is default target. Don't break this rule.
84 public abstract string[] ValidAttributeTargets { get; }
87 public class Attribute
89 public readonly string ExplicitTarget;
90 public AttributeTargets Target;
91 readonly ATypeNameExpression expression;
93 Arguments pos_args, named_args;
97 readonly bool nameEscaped;
98 readonly Location loc;
102 // An attribute can be attached to multiple targets (e.g. multiple fields)
104 Attributable[] targets;
107 // A member context for the attribute, it's much easier to hold it here
108 // than trying to pull it during resolve
110 IMemberContext context;
112 public static readonly AttributeUsageAttribute DefaultUsageAttribute = new AttributeUsageAttribute (AttributeTargets.All);
113 public static readonly object[] EmptyObject = new object [0];
115 List<KeyValuePair<MemberExpr, NamedArgument>> named_values;
117 public Attribute (string target, ATypeNameExpression expr, Arguments[] args, Location loc, bool nameEscaped)
119 this.expression = expr;
122 named_args = args[1];
125 ExplicitTarget = target;
126 this.nameEscaped = nameEscaped;
129 public Location Location {
135 public Arguments NamedArguments {
141 public Arguments PositionalArguments {
147 public bool ResolveError {
149 return resolve_error;
153 public ATypeNameExpression TypeExpression {
159 void AddModuleCharSet (ResolveContext rc)
161 const string dll_import_char_set = "CharSet";
164 // Only when not customized by user
166 if (HasField (dll_import_char_set))
169 if (!rc.Module.PredefinedTypes.CharSet.Define ()) {
173 if (NamedArguments == null)
174 named_args = new Arguments (1);
176 var value = Constant.CreateConstantFromValue (rc.Module.PredefinedTypes.CharSet.TypeSpec, rc.Module.DefaultCharSet, Location);
177 NamedArguments.Add (new NamedArgument (dll_import_char_set, loc, value));
180 public Attribute Clone ()
182 Attribute a = new Attribute (ExplicitTarget, expression, null, loc, nameEscaped);
183 a.pos_args = pos_args;
184 a.named_args = NamedArguments;
189 // When the same attribute is attached to multiple fiels
190 // we use @target field as a list of targets. The attribute
191 // has to be resolved only once but emitted for each target.
193 public void AttachTo (Attributable target, IMemberContext context)
195 if (this.targets == null) {
196 this.targets = new Attributable[] { target };
197 this.context = context;
201 // When re-attaching global attributes
202 if (context is NamespaceContainer) {
203 this.targets[0] = target;
204 this.context = context;
208 // Resize target array
209 Attributable[] new_array = new Attributable [this.targets.Length + 1];
210 targets.CopyTo (new_array, 0);
211 new_array [targets.Length] = target;
212 this.targets = new_array;
214 // No need to update context, different targets cannot have
215 // different contexts, it's enough to remove same attributes
216 // from secondary members.
218 target.OptAttributes = null;
221 public ResolveContext CreateResolveContext ()
223 return new ResolveContext (context, ResolveContext.Options.ConstantScope);
226 static void Error_InvalidNamedArgument (ResolveContext rc, NamedArgument name)
228 rc.Report.Error (617, name.Location, "`{0}' is not a valid named attribute argument. Named attribute arguments " +
229 "must be fields which are not readonly, static, const or read-write properties which are " +
230 "public and not static",
234 static void Error_InvalidNamedArgumentType (ResolveContext rc, NamedArgument name)
236 rc.Report.Error (655, name.Location,
237 "`{0}' is not a valid named attribute argument because it is not a valid attribute parameter type",
241 public static void Error_AttributeArgumentIsDynamic (IMemberContext context, Location loc)
243 context.Module.Compiler.Report.Error (1982, loc, "An attribute argument cannot be dynamic expression");
246 public void Error_MissingGuidAttribute ()
248 Report.Error (596, Location, "The Guid attribute must be specified with the ComImport attribute");
251 public void Error_MisusedExtensionAttribute ()
253 Report.Error (1112, Location, "Do not use `{0}' directly. Use parameter modifier `this' instead", GetSignatureForError ());
256 public void Error_MisusedDynamicAttribute ()
258 Report.Error (1970, loc, "Do not use `{0}' directly. Use `dynamic' keyword instead", GetSignatureForError ());
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 IsValidMethodImplOption (int value)
391 // Allow to use AggressiveInlining on any runtime/corlib
393 MethodImplOptions all = (MethodImplOptions) 256;
394 foreach (MethodImplOptions v in System.Enum.GetValues (typeof (MethodImplOptions))) {
398 return ((MethodImplOptions) value | all) == all;
401 static bool IsValidArgumentType (TypeSpec t)
404 var ac = (ArrayContainer) t;
411 switch (t.BuiltinType) {
412 case BuiltinTypeSpec.Type.Int:
413 case BuiltinTypeSpec.Type.UInt:
414 case BuiltinTypeSpec.Type.Long:
415 case BuiltinTypeSpec.Type.ULong:
416 case BuiltinTypeSpec.Type.Float:
417 case BuiltinTypeSpec.Type.Double:
418 case BuiltinTypeSpec.Type.Char:
419 case BuiltinTypeSpec.Type.Short:
420 case BuiltinTypeSpec.Type.Bool:
421 case BuiltinTypeSpec.Type.SByte:
422 case BuiltinTypeSpec.Type.Byte:
423 case BuiltinTypeSpec.Type.UShort:
425 case BuiltinTypeSpec.Type.String:
426 case BuiltinTypeSpec.Type.Object:
427 case BuiltinTypeSpec.Type.Dynamic:
428 case BuiltinTypeSpec.Type.Type:
435 // TODO: Don't use this ambiguous value
437 get { return expression.Name; }
440 public Report Report {
441 get { return context.Module.Compiler.Report; }
444 public MethodSpec Resolve ()
449 resolve_error = true;
453 ResolveAttributeType (false);
458 if (Type.IsAbstract) {
459 Report.Error (653, Location, "Cannot apply attribute class `{0}' because it is abstract", GetSignatureForError ());
463 ObsoleteAttribute obsolete_attr = Type.GetAttributeObsolete ();
464 if (obsolete_attr != null) {
465 AttributeTester.Report_ObsoleteMessage (obsolete_attr, Type.GetSignatureForError (), Location, Report);
468 ResolveContext rc = null;
471 // Try if the attribute is simple and has been resolved before
472 if (pos_args != null || !context.Module.AttributeConstructorCache.TryGetValue (Type, out ctor)) {
473 rc = CreateResolveContext ();
474 ctor = ResolveConstructor (rc);
479 if (pos_args == null && ctor.Parameters.IsEmpty)
480 context.Module.AttributeConstructorCache.Add (Type, ctor);
484 // Add [module: DefaultCharSet] to all DllImport import attributes
486 var module = context.Module;
487 if ((Type == module.PredefinedAttributes.DllImport || Type == module.PredefinedAttributes.UnmanagedFunctionPointer) && module.HasDefaultCharSet) {
489 rc = CreateResolveContext ();
491 AddModuleCharSet (rc);
494 if (NamedArguments != null) {
496 rc = CreateResolveContext ();
498 if (!ResolveNamedArguments (rc))
502 resolve_error = false;
506 MethodSpec ResolveConstructor (ResolveContext ec)
508 if (pos_args != null) {
510 pos_args.Resolve (ec, out dynamic);
512 Error_AttributeArgumentIsDynamic (ec.MemberContext, loc);
517 return Expression.ConstructorLookup (ec, Type, ref pos_args, loc);
520 bool ResolveNamedArguments (ResolveContext ec)
522 int named_arg_count = NamedArguments.Count;
523 var seen_names = new List<string> (named_arg_count);
525 named_values = new List<KeyValuePair<MemberExpr, NamedArgument>> (named_arg_count);
527 foreach (NamedArgument a in NamedArguments) {
528 string name = a.Name;
529 if (seen_names.Contains (name)) {
530 ec.Report.Error (643, a.Location, "Duplicate named attribute `{0}' argument", name);
534 seen_names.Add (name);
538 Expression member = Expression.MemberLookup (ec, false, Type, name, 0, Expression.MemberLookupRestrictions.ExactArity, loc);
540 if (member == null) {
541 member = Expression.MemberLookup (ec, true, Type, name, 0, Expression.MemberLookupRestrictions.ExactArity, loc);
543 if (member != null) {
544 // TODO: ec.Report.SymbolRelatedToPreviousError (member);
545 Expression.ErrorIsInaccesible (ec, member.GetSignatureForError (), loc);
551 Expression.Error_TypeDoesNotContainDefinition (ec, Location, Type, name);
555 if (!(member is PropertyExpr || member is FieldExpr)) {
556 Error_InvalidNamedArgument (ec, a);
560 ObsoleteAttribute obsolete_attr;
562 if (member is PropertyExpr) {
563 var pi = ((PropertyExpr) member).PropertyInfo;
565 if (!pi.HasSet || !pi.HasGet || pi.IsStatic || !pi.Get.IsPublic || !pi.Set.IsPublic) {
566 ec.Report.SymbolRelatedToPreviousError (pi);
567 Error_InvalidNamedArgument (ec, a);
571 if (!IsValidArgumentType (member.Type)) {
572 ec.Report.SymbolRelatedToPreviousError (pi);
573 Error_InvalidNamedArgumentType (ec, a);
577 obsolete_attr = pi.GetAttributeObsolete ();
578 pi.MemberDefinition.SetIsAssigned ();
580 var fi = ((FieldExpr) member).Spec;
582 if (fi.IsReadOnly || fi.IsStatic || !fi.IsPublic) {
583 Error_InvalidNamedArgument (ec, a);
587 if (!IsValidArgumentType (member.Type)) {
588 ec.Report.SymbolRelatedToPreviousError (fi);
589 Error_InvalidNamedArgumentType (ec, a);
593 obsolete_attr = fi.GetAttributeObsolete ();
594 fi.MemberDefinition.SetIsAssigned ();
597 if (obsolete_attr != null && !context.IsObsolete)
598 AttributeTester.Report_ObsoleteMessage (obsolete_attr, member.GetSignatureForError (), member.Location, Report);
600 if (a.Type != member.Type) {
601 a.Expr = Convert.ImplicitConversionRequired (ec, a.Expr, member.Type, a.Expr.Location);
605 named_values.Add (new KeyValuePair<MemberExpr, NamedArgument> ((MemberExpr) member, a));
612 /// Get a string containing a list of valid targets for the attribute 'attr'
614 public string GetValidTargets ()
616 StringBuilder sb = new StringBuilder ();
617 AttributeTargets targets = Type.GetAttributeUsage (context.Module.PredefinedAttributes.AttributeUsage).ValidOn;
619 if ((targets & AttributeTargets.Assembly) != 0)
620 sb.Append ("assembly, ");
622 if ((targets & AttributeTargets.Module) != 0)
623 sb.Append ("module, ");
625 if ((targets & AttributeTargets.Class) != 0)
626 sb.Append ("class, ");
628 if ((targets & AttributeTargets.Struct) != 0)
629 sb.Append ("struct, ");
631 if ((targets & AttributeTargets.Enum) != 0)
632 sb.Append ("enum, ");
634 if ((targets & AttributeTargets.Constructor) != 0)
635 sb.Append ("constructor, ");
637 if ((targets & AttributeTargets.Method) != 0)
638 sb.Append ("method, ");
640 if ((targets & AttributeTargets.Property) != 0)
641 sb.Append ("property, indexer, ");
643 if ((targets & AttributeTargets.Field) != 0)
644 sb.Append ("field, ");
646 if ((targets & AttributeTargets.Event) != 0)
647 sb.Append ("event, ");
649 if ((targets & AttributeTargets.Interface) != 0)
650 sb.Append ("interface, ");
652 if ((targets & AttributeTargets.Parameter) != 0)
653 sb.Append ("parameter, ");
655 if ((targets & AttributeTargets.Delegate) != 0)
656 sb.Append ("delegate, ");
658 if ((targets & AttributeTargets.ReturnValue) != 0)
659 sb.Append ("return, ");
661 if ((targets & AttributeTargets.GenericParameter) != 0)
662 sb.Append ("type parameter, ");
664 return sb.Remove (sb.Length - 2, 2).ToString ();
667 public AttributeUsageAttribute GetAttributeUsageAttribute ()
670 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
671 // But because a lot of attribute class code must be rewritten will be better to wait...
675 return DefaultUsageAttribute;
677 AttributeUsageAttribute usage_attribute = new AttributeUsageAttribute ((AttributeTargets) ((Constant) pos_args[0].Expr).GetValue ());
679 var field = GetNamedValue ("AllowMultiple") as BoolConstant;
681 usage_attribute.AllowMultiple = field.Value;
683 field = GetNamedValue ("Inherited") as BoolConstant;
685 usage_attribute.Inherited = field.Value;
687 return usage_attribute;
691 /// Returns custom name of indexer
693 public string GetIndexerAttributeValue ()
696 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
697 // But because a lot of attribute class code must be rewritten will be better to wait...
700 if (resolve_error || pos_args.Count != 1 || !(pos_args[0].Expr is Constant))
703 return ((Constant) pos_args[0].Expr).GetValue () as string;
707 /// Returns condition of ConditionalAttribute
709 public string GetConditionalAttributeValue ()
712 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
713 // But because a lot of attribute class code must be rewritten will be better to wait...
719 return ((Constant) pos_args[0].Expr).GetValue () as string;
723 /// Creates the instance of ObsoleteAttribute from this attribute instance
725 public ObsoleteAttribute GetObsoleteAttribute ()
728 // corlib only case when obsolete is used before is resolved
729 var c = Type.MemberDefinition as Class;
730 if (c != null && !c.HasMembersDefined)
733 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
734 // But because a lot of attribute class code must be rewritten will be better to wait...
741 if (pos_args == null)
742 return new ObsoleteAttribute ();
744 string msg = ((Constant) pos_args[0].Expr).GetValue () as string;
745 if (pos_args.Count == 1)
746 return new ObsoleteAttribute (msg);
748 return new ObsoleteAttribute (msg, ((BoolConstant) pos_args[1].Expr).Value);
752 /// Returns value of CLSCompliantAttribute contructor parameter but because the method can be called
753 /// before ApplyAttribute. We need to resolve the arguments.
754 /// This situation occurs when class deps is differs from Emit order.
756 public bool GetClsCompliantAttributeValue ()
759 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
760 // But because a lot of attribute class code must be rewritten will be better to wait...
766 return ((BoolConstant) pos_args[0].Expr).Value;
769 public TypeSpec GetCoClassAttributeValue ()
777 return GetArgumentType ();
780 public bool CheckTarget ()
782 string[] valid_targets = Owner.ValidAttributeTargets;
783 if (ExplicitTarget == null || ExplicitTarget == valid_targets [0]) {
784 Target = Owner.AttributeTargets;
788 // TODO: we can skip the first item
789 if (Array.Exists (valid_targets, i => i == ExplicitTarget)) {
790 switch (ExplicitTarget) {
791 case "return": Target = AttributeTargets.ReturnValue; return true;
792 case "param": Target = AttributeTargets.Parameter; return true;
793 case "field": Target = AttributeTargets.Field; return true;
794 case "method": Target = AttributeTargets.Method; return true;
795 case "property": Target = AttributeTargets.Property; return true;
796 case "module": Target = AttributeTargets.Module; return true;
798 throw new InternalErrorException ("Unknown explicit target: " + ExplicitTarget);
801 StringBuilder sb = new StringBuilder ();
802 foreach (string s in valid_targets) {
806 sb.Remove (sb.Length - 2, 2);
807 Report.Warning (657, 1, Location,
808 "`{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",
809 ExplicitTarget, sb.ToString ());
814 /// Tests permitted SecurityAction for assembly or other types
816 bool IsSecurityActionValid ()
818 SecurityAction action = GetSecurityActionValue ();
819 bool for_assembly = Target == AttributeTargets.Assembly || Target == AttributeTargets.Module;
822 #pragma warning disable 618
823 case SecurityAction.Demand:
824 case SecurityAction.Assert:
825 case SecurityAction.Deny:
826 case SecurityAction.PermitOnly:
827 case SecurityAction.LinkDemand:
828 case SecurityAction.InheritanceDemand:
833 case SecurityAction.RequestMinimum:
834 case SecurityAction.RequestOptional:
835 case SecurityAction.RequestRefuse:
839 #pragma warning restore 618
842 Error_AttributeEmitError ("SecurityAction is out of range");
846 Error_AttributeEmitError (String.Concat ("SecurityAction `", action, "' is not valid for this declaration"));
850 System.Security.Permissions.SecurityAction GetSecurityActionValue ()
852 return (SecurityAction) ((Constant) pos_args[0].Expr).GetValue ();
856 /// Creates instance of SecurityAttribute class and add result of CreatePermission method to permission table.
858 /// <returns></returns>
859 public void ExtractSecurityPermissionSet (MethodSpec ctor, ref SecurityType permissions)
862 object[] values = new object[pos_args.Count];
863 for (int i = 0; i < values.Length; ++i)
864 values[i] = ((Constant) pos_args[i].Expr).GetValue ();
867 object[] prop_values;
868 if (named_values == null) {
872 prop = new PropertyInfo[named_values.Count];
873 prop_values = new object [named_values.Count];
874 for (int i = 0; i < prop.Length; ++i) {
875 prop [i] = ((PropertyExpr) named_values [i].Key).PropertyInfo.MetaInfo;
876 prop_values [i] = ((Constant) named_values [i].Value.Expr).GetValue ();
880 if (permissions == null)
881 permissions = new SecurityType ();
883 var cab = new CustomAttributeBuilder ((ConstructorInfo) ctor.GetMetaInfo (), values, prop, prop_values);
884 permissions.Add (cab);
886 throw new NotSupportedException ();
890 public Constant GetNamedValue (string name)
892 if (named_values == null)
895 for (int i = 0; i < named_values.Count; ++i) {
896 if (named_values [i].Value.Name == name)
897 return named_values [i].Value.Expr as Constant;
903 public CharSet GetCharSetValue ()
905 return (CharSet) System.Enum.Parse (typeof (CharSet), ((Constant) pos_args[0].Expr).GetValue ().ToString ());
908 public bool HasField (string fieldName)
910 if (named_values == null)
913 foreach (var na in named_values) {
914 if (na.Value.Name == fieldName)
922 // Returns true for MethodImplAttribute with MethodImplOptions.InternalCall value
924 public bool IsInternalCall ()
926 return (GetMethodImplOptions () & MethodImplOptions.InternalCall) != 0;
929 public MethodImplOptions GetMethodImplOptions ()
931 MethodImplOptions options = 0;
932 if (pos_args.Count == 1) {
933 options = (MethodImplOptions) System.Enum.Parse (typeof (MethodImplOptions), ((Constant) pos_args[0].Expr).GetValue ().ToString ());
934 } else if (HasField ("Value")) {
935 var named = GetNamedValue ("Value");
936 options = (MethodImplOptions) System.Enum.Parse (typeof (MethodImplOptions), named.GetValue ().ToString ());
943 // Returns true for StructLayoutAttribute with LayoutKind.Explicit value
945 public bool IsExplicitLayoutKind ()
947 if (pos_args == null || pos_args.Count != 1)
950 var value = (LayoutKind) System.Enum.Parse (typeof (LayoutKind), ((Constant) pos_args[0].Expr).GetValue ().ToString ());
951 return value == LayoutKind.Explicit;
954 public Expression GetParameterDefaultValue ()
956 if (pos_args == null)
959 return pos_args[0].Expr;
962 public override bool Equals (object obj)
964 Attribute a = obj as Attribute;
968 return Type == a.Type && Target == a.Target;
971 public override int GetHashCode ()
973 return Type.GetHashCode () ^ Target.GetHashCode ();
977 /// Emit attribute for Attributable symbol
979 public void Emit (Dictionary<Attribute, List<Attribute>> allEmitted)
981 var ctor = Resolve ();
985 var predefined = context.Module.PredefinedAttributes;
987 AttributeUsageAttribute usage_attr = Type.GetAttributeUsage (predefined.AttributeUsage);
988 if ((usage_attr.ValidOn & Target) == 0) {
989 Report.Error (592, Location, "The attribute `{0}' is not valid on this declaration type. " +
990 "It is valid on `{1}' declarations only",
991 GetSignatureForError (), GetValidTargets ());
996 if (pos_args == null && named_values == null) {
997 cdata = AttributeEncoder.Empty;
999 AttributeEncoder encoder = new AttributeEncoder ();
1001 if (pos_args != null) {
1002 var param_types = ctor.Parameters.Types;
1003 for (int j = 0; j < pos_args.Count; ++j) {
1004 var pt = param_types[j];
1005 var arg_expr = pos_args[j].Expr;
1007 if ((Type == predefined.IndexerName || Type == predefined.Conditional) && arg_expr is Constant) {
1008 string v = ((Constant) arg_expr).GetValue () as string;
1009 if (!Tokenizer.IsValidIdentifier (v) || (Type == predefined.IndexerName && Tokenizer.IsKeyword (v))) {
1010 context.Module.Compiler.Report.Error (633, arg_expr.Location,
1011 "The argument to the `{0}' attribute must be a valid identifier", GetSignatureForError ());
1014 } else if (Type == predefined.Guid) {
1016 string v = ((StringConstant) arg_expr).Value;
1018 } catch (Exception e) {
1019 Error_AttributeEmitError (e.Message);
1022 } else if (Type == predefined.AttributeUsage) {
1023 int v = ((IntConstant) ((EnumConstant) arg_expr).Child).Value;
1025 context.Module.Compiler.Report.Error (591, Location, "Invalid value for argument to `{0}' attribute",
1026 "System.AttributeUsage");
1028 } else if (Type == predefined.MarshalAs) {
1029 if (pos_args.Count == 1) {
1030 var u_type = (UnmanagedType) System.Enum.Parse (typeof (UnmanagedType), ((Constant) pos_args[0].Expr).GetValue ().ToString ());
1031 if (u_type == UnmanagedType.ByValArray && !(Owner is FieldBase)) {
1032 Error_AttributeEmitError ("Specified unmanaged type is only valid on fields");
1035 } else if (Type == predefined.DllImport) {
1036 if (pos_args.Count == 1 && pos_args[0].Expr is Constant) {
1037 var value = ((Constant) pos_args[0].Expr).GetValue () as string;
1038 if (string.IsNullOrEmpty (value))
1039 Error_AttributeEmitError ("DllName cannot be empty or null");
1041 } else if (Type == predefined.MethodImpl) {
1042 if (pos_args.Count == 1) {
1043 var value = (int) ((Constant) arg_expr).GetValueAsLong ();
1045 if (!IsValidMethodImplOption (value)) {
1046 Error_AttributeEmitError ("Incorrect argument value");
1052 arg_expr.EncodeAttributeValue (context, encoder, pt);
1056 if (named_values != null) {
1057 encoder.Encode ((ushort) named_values.Count);
1058 foreach (var na in named_values) {
1059 if (na.Key is FieldExpr)
1060 encoder.Encode ((byte) 0x53);
1062 encoder.Encode ((byte) 0x54);
1064 encoder.Encode (na.Key.Type);
1065 encoder.Encode (na.Value.Name);
1066 na.Value.Expr.EncodeAttributeValue (context, encoder, na.Key.Type);
1069 encoder.EncodeEmptyNamedArguments ();
1072 cdata = encoder.ToArray ();
1075 if (!ctor.DeclaringType.IsConditionallyExcluded (context, Location)) {
1077 foreach (Attributable target in targets)
1078 target.ApplyAttributeBuilder (this, ctor, cdata, predefined);
1079 } catch (Exception e) {
1080 if (e is BadImageFormat && Report.Errors > 0)
1083 Error_AttributeEmitError (e.Message);
1088 if (!usage_attr.AllowMultiple && allEmitted != null) {
1089 if (allEmitted.ContainsKey (this)) {
1090 var a = allEmitted [this];
1092 a = new List<Attribute> (2);
1093 allEmitted [this] = a;
1097 allEmitted.Add (this, null);
1101 if (!context.Module.Compiler.Settings.VerifyClsCompliance)
1104 // Here we are testing attribute arguments for array usage (error 3016)
1105 if (Owner.IsClsComplianceRequired ()) {
1106 if (pos_args != null)
1107 pos_args.CheckArrayAsAttribute (context.Module.Compiler);
1109 if (NamedArguments == null)
1112 NamedArguments.CheckArrayAsAttribute (context.Module.Compiler);
1116 private Expression GetValue ()
1118 if (pos_args == null || pos_args.Count < 1)
1121 return pos_args[0].Expr;
1124 public string GetString ()
1126 Expression e = GetValue ();
1127 if (e is StringConstant)
1128 return ((StringConstant)e).Value;
1132 public bool GetBoolean ()
1134 Expression e = GetValue ();
1135 if (e is BoolConstant)
1136 return ((BoolConstant)e).Value;
1140 public TypeSpec GetArgumentType ()
1142 TypeOf e = GetValue () as TypeOf;
1145 return e.TypeArgument;
1149 public class Attributes
1151 public readonly List<Attribute> Attrs;
1153 public Attributes (Attribute a)
1155 Attrs = new List<Attribute> ();
1159 public Attributes (List<Attribute> attrs)
1164 public void AddAttribute (Attribute attr)
1169 public void AddAttributes (List<Attribute> attrs)
1171 Attrs.AddRange (attrs);
1174 public void AttachTo (Attributable attributable, IMemberContext context)
1176 foreach (Attribute a in Attrs)
1177 a.AttachTo (attributable, context);
1180 public Attributes Clone ()
1182 var al = new List<Attribute> (Attrs.Count);
1183 foreach (Attribute a in Attrs)
1184 al.Add (a.Clone ());
1186 return new Attributes (al);
1190 /// Checks whether attribute target is valid for the current element
1192 public bool CheckTargets ()
1194 for (int i = 0; i < Attrs.Count; ++i) {
1195 if (!Attrs [i].CheckTarget ())
1196 Attrs.RemoveAt (i--);
1202 public void ConvertGlobalAttributes (TypeContainer member, NamespaceContainer currentNamespace, bool isGlobal)
1204 var member_explicit_targets = member.ValidAttributeTargets;
1205 for (int i = 0; i < Attrs.Count; ++i) {
1206 var attr = Attrs[0];
1207 if (attr.ExplicitTarget == null)
1211 for (ii = 0; ii < member_explicit_targets.Length; ++ii) {
1212 if (attr.ExplicitTarget == member_explicit_targets[ii]) {
1218 if (ii < 0 || !isGlobal)
1221 member.Module.AddAttribute (attr, currentNamespace);
1227 public bool HasResolveError()
1229 foreach (var a in Attrs) {
1237 public Attribute Search (PredefinedAttribute t)
1239 return Search (null, t);
1242 public Attribute Search (string explicitTarget, PredefinedAttribute t)
1244 foreach (Attribute a in Attrs) {
1245 if (explicitTarget != null && a.ExplicitTarget != explicitTarget)
1248 if (a.ResolveTypeForComparison () == t)
1255 /// Returns all attributes of type 't'. Use it when attribute is AllowMultiple = true
1257 public Attribute[] SearchMulti (PredefinedAttribute t)
1259 List<Attribute> ar = null;
1261 foreach (Attribute a in Attrs) {
1262 if (a.ResolveTypeForComparison () == t) {
1264 ar = new List<Attribute> (Attrs.Count);
1269 return ar == null ? null : ar.ToArray ();
1276 Dictionary<Attribute, List<Attribute>> ld = Attrs.Count > 1 ? new Dictionary<Attribute, List<Attribute>> () : null;
1278 foreach (Attribute a in Attrs)
1281 if (ld == null || ld.Count == 0)
1284 foreach (var d in ld) {
1285 if (d.Value == null)
1288 Attribute a = d.Key;
1290 foreach (Attribute collision in d.Value)
1291 a.Report.SymbolRelatedToPreviousError (collision.Location, "");
1293 a.Report.Error (579, a.Location, "The attribute `{0}' cannot be applied multiple times",
1294 a.GetSignatureForError ());
1298 public bool Contains (PredefinedAttribute t)
1300 return Search (t) != null;
1304 public sealed class AttributeEncoder
1307 public enum EncodedTypeProperties
1311 TypeParameter = 1 << 1
1314 public static readonly byte[] Empty;
1318 const ushort Version = 1;
1320 static AttributeEncoder ()
1322 Empty = new byte[4];
1323 Empty[0] = (byte) Version;
1326 public AttributeEncoder ()
1328 buffer = new byte[32];
1332 public void Encode (bool value)
1334 Encode (value ? (byte) 1 : (byte) 0);
1337 public void Encode (byte value)
1339 if (pos == buffer.Length)
1342 buffer [pos++] = value;
1345 public void Encode (sbyte value)
1347 Encode ((byte) value);
1350 public void Encode (short value)
1352 if (pos + 2 > buffer.Length)
1355 buffer[pos++] = (byte) value;
1356 buffer[pos++] = (byte) (value >> 8);
1359 public void Encode (ushort value)
1361 Encode ((short) value);
1364 public void Encode (int value)
1366 if (pos + 4 > buffer.Length)
1369 buffer[pos++] = (byte) value;
1370 buffer[pos++] = (byte) (value >> 8);
1371 buffer[pos++] = (byte) (value >> 16);
1372 buffer[pos++] = (byte) (value >> 24);
1375 public void Encode (uint value)
1377 Encode ((int) value);
1380 public void Encode (long value)
1382 if (pos + 8 > buffer.Length)
1385 buffer[pos++] = (byte) value;
1386 buffer[pos++] = (byte) (value >> 8);
1387 buffer[pos++] = (byte) (value >> 16);
1388 buffer[pos++] = (byte) (value >> 24);
1389 buffer[pos++] = (byte) (value >> 32);
1390 buffer[pos++] = (byte) (value >> 40);
1391 buffer[pos++] = (byte) (value >> 48);
1392 buffer[pos++] = (byte) (value >> 56);
1395 public void Encode (ulong value)
1397 Encode ((long) value);
1400 public void Encode (float value)
1402 Encode (SingleConverter.SingleToInt32Bits (value));
1405 public void Encode (double value)
1407 Encode (BitConverter.DoubleToInt64Bits (value));
1410 public void Encode (string value)
1412 if (value == null) {
1413 Encode ((byte) 0xFF);
1417 var buf = Encoding.UTF8.GetBytes(value);
1418 WriteCompressedValue (buf.Length);
1420 if (pos + buf.Length > buffer.Length)
1423 Buffer.BlockCopy (buf, 0, buffer, pos, buf.Length);
1427 public EncodedTypeProperties Encode (TypeSpec type)
1429 switch (type.BuiltinType) {
1430 case BuiltinTypeSpec.Type.Bool:
1431 Encode ((byte) 0x02);
1433 case BuiltinTypeSpec.Type.Char:
1434 Encode ((byte) 0x03);
1436 case BuiltinTypeSpec.Type.SByte:
1437 Encode ((byte) 0x04);
1439 case BuiltinTypeSpec.Type.Byte:
1440 Encode ((byte) 0x05);
1442 case BuiltinTypeSpec.Type.Short:
1443 Encode ((byte) 0x06);
1445 case BuiltinTypeSpec.Type.UShort:
1446 Encode ((byte) 0x07);
1448 case BuiltinTypeSpec.Type.Int:
1449 Encode ((byte) 0x08);
1451 case BuiltinTypeSpec.Type.UInt:
1452 Encode ((byte) 0x09);
1454 case BuiltinTypeSpec.Type.Long:
1455 Encode ((byte) 0x0A);
1457 case BuiltinTypeSpec.Type.ULong:
1458 Encode ((byte) 0x0B);
1460 case BuiltinTypeSpec.Type.Float:
1461 Encode ((byte) 0x0C);
1463 case BuiltinTypeSpec.Type.Double:
1464 Encode ((byte) 0x0D);
1466 case BuiltinTypeSpec.Type.String:
1467 Encode ((byte) 0x0E);
1469 case BuiltinTypeSpec.Type.Type:
1470 Encode ((byte) 0x50);
1472 case BuiltinTypeSpec.Type.Object:
1473 Encode ((byte) 0x51);
1475 case BuiltinTypeSpec.Type.Dynamic:
1476 Encode ((byte) 0x51);
1477 return EncodedTypeProperties.DynamicType;
1480 Encode ((byte) 0x1D);
1481 return Encode (TypeManager.GetElementType (type));
1484 if (type.Kind == MemberKind.Enum) {
1485 Encode ((byte) 0x55);
1486 EncodeTypeName (type);
1492 return EncodedTypeProperties.None;
1495 public void EncodeTypeName (TypeSpec type)
1497 var old_type = type.GetMetaInfo ();
1498 Encode (type.MemberDefinition.IsImported ? old_type.AssemblyQualifiedName : old_type.FullName);
1501 public void EncodeTypeName (TypeContainer type)
1503 Encode (type.GetSignatureForMetadata ());
1508 // Encodes single property named argument per call
1510 public void EncodeNamedPropertyArgument (PropertySpec property, Constant value)
1512 Encode ((ushort) 1); // length
1513 Encode ((byte) 0x54); // property
1514 Encode (property.MemberType);
1515 Encode (property.Name);
1516 value.EncodeAttributeValue (null, this, property.MemberType);
1520 // Encodes single field named argument per call
1522 public void EncodeNamedFieldArgument (FieldSpec field, Constant value)
1524 Encode ((ushort) 1); // length
1525 Encode ((byte) 0x53); // field
1526 Encode (field.MemberType);
1527 Encode (field.Name);
1528 value.EncodeAttributeValue (null, this, field.MemberType);
1531 public void EncodeNamedArguments<T> (T[] members, Constant[] values) where T : MemberSpec, IInterfaceMemberSpec
1533 Encode ((ushort) members.Length);
1535 for (int i = 0; i < members.Length; ++i)
1537 var member = members[i];
1539 if (member.Kind == MemberKind.Field)
1540 Encode ((byte) 0x53);
1541 else if (member.Kind == MemberKind.Property)
1542 Encode ((byte) 0x54);
1544 throw new NotImplementedException (member.Kind.ToString ());
1546 Encode (member.MemberType);
1547 Encode (member.Name);
1548 values [i].EncodeAttributeValue (null, this, member.MemberType);
1552 public void EncodeEmptyNamedArguments ()
1554 Encode ((ushort) 0);
1559 int size = System.Math.Max (pos * 4, pos + inc + 2);
1560 Array.Resize (ref buffer, size);
1563 void WriteCompressedValue (int value)
1566 Encode ((byte) value);
1570 if (value < 0x4000) {
1571 Encode ((byte) (0x80 | (value >> 8)));
1572 Encode ((byte) value);
1579 public byte[] ToArray ()
1581 byte[] buf = new byte[pos];
1582 Array.Copy (buffer, buf, pos);
1589 /// Helper class for attribute verification routine.
1591 static class AttributeTester
1594 /// Common method for Obsolete error/warning reporting.
1596 public static void Report_ObsoleteMessage (ObsoleteAttribute oa, string member, Location loc, Report Report)
1599 Report.Error (619, loc, "`{0}' is obsolete: `{1}'", member, oa.Message);
1603 if (oa.Message == null || oa.Message.Length == 0) {
1604 Report.Warning (612, 1, loc, "`{0}' is obsolete", member);
1607 Report.Warning (618, 2, loc, "`{0}' is obsolete: `{1}'", member, oa.Message);
1612 // Predefined attribute types
1614 public class PredefinedAttributes
1616 // Build-in attributes
1617 public readonly PredefinedAttribute ParamArray;
1618 public readonly PredefinedAttribute Out;
1620 // Optional attributes
1621 public readonly PredefinedAttribute Obsolete;
1622 public readonly PredefinedAttribute DllImport;
1623 public readonly PredefinedAttribute MethodImpl;
1624 public readonly PredefinedAttribute MarshalAs;
1625 public readonly PredefinedAttribute In;
1626 public readonly PredefinedAttribute IndexerName;
1627 public readonly PredefinedAttribute Conditional;
1628 public readonly PredefinedAttribute CLSCompliant;
1629 public readonly PredefinedAttribute Security;
1630 public readonly PredefinedAttribute Required;
1631 public readonly PredefinedAttribute Guid;
1632 public readonly PredefinedAttribute AssemblyCulture;
1633 public readonly PredefinedAttribute AssemblyVersion;
1634 public readonly PredefinedAttribute AssemblyAlgorithmId;
1635 public readonly PredefinedAttribute AssemblyFlags;
1636 public readonly PredefinedAttribute AssemblyFileVersion;
1637 public readonly PredefinedAttribute ComImport;
1638 public readonly PredefinedAttribute CoClass;
1639 public readonly PredefinedAttribute AttributeUsage;
1640 public readonly PredefinedAttribute DefaultParameterValue;
1641 public readonly PredefinedAttribute OptionalParameter;
1642 public readonly PredefinedAttribute UnverifiableCode;
1643 public readonly PredefinedAttribute DefaultCharset;
1644 public readonly PredefinedAttribute TypeForwarder;
1645 public readonly PredefinedAttribute FixedBuffer;
1646 public readonly PredefinedAttribute CompilerGenerated;
1647 public readonly PredefinedAttribute InternalsVisibleTo;
1648 public readonly PredefinedAttribute RuntimeCompatibility;
1649 public readonly PredefinedAttribute DebuggerHidden;
1650 public readonly PredefinedAttribute UnsafeValueType;
1651 public readonly PredefinedAttribute UnmanagedFunctionPointer;
1652 public readonly PredefinedDebuggerBrowsableAttribute DebuggerBrowsable;
1655 public readonly PredefinedAttribute Extension;
1658 public readonly PredefinedDynamicAttribute Dynamic;
1661 public readonly PredefinedStateMachineAttribute AsyncStateMachine;
1664 // Optional types which are used as types and for member lookup
1666 public readonly PredefinedAttribute DefaultMember;
1667 public readonly PredefinedDecimalAttribute DecimalConstant;
1668 public readonly PredefinedAttribute StructLayout;
1669 public readonly PredefinedAttribute FieldOffset;
1670 public readonly PredefinedAttribute AssemblyProduct;
1671 public readonly PredefinedAttribute AssemblyCompany;
1672 public readonly PredefinedAttribute AssemblyDescription;
1673 public readonly PredefinedAttribute AssemblyCopyright;
1674 public readonly PredefinedAttribute AssemblyTrademark;
1675 public readonly PredefinedAttribute CallerMemberNameAttribute;
1676 public readonly PredefinedAttribute CallerLineNumberAttribute;
1677 public readonly PredefinedAttribute CallerFilePathAttribute;
1679 public PredefinedAttributes (ModuleContainer module)
1681 ParamArray = new PredefinedAttribute (module, "System", "ParamArrayAttribute");
1682 Out = new PredefinedAttribute (module, "System.Runtime.InteropServices", "OutAttribute");
1683 ParamArray.Resolve ();
1686 Obsolete = new PredefinedAttribute (module, "System", "ObsoleteAttribute");
1687 DllImport = new PredefinedAttribute (module, "System.Runtime.InteropServices", "DllImportAttribute");
1688 MethodImpl = new PredefinedAttribute (module, "System.Runtime.CompilerServices", "MethodImplAttribute");
1689 MarshalAs = new PredefinedAttribute (module, "System.Runtime.InteropServices", "MarshalAsAttribute");
1690 In = new PredefinedAttribute (module, "System.Runtime.InteropServices", "InAttribute");
1691 IndexerName = new PredefinedAttribute (module, "System.Runtime.CompilerServices", "IndexerNameAttribute");
1692 Conditional = new PredefinedAttribute (module, "System.Diagnostics", "ConditionalAttribute");
1693 CLSCompliant = new PredefinedAttribute (module, "System", "CLSCompliantAttribute");
1694 Security = new PredefinedAttribute (module, "System.Security.Permissions", "SecurityAttribute");
1695 Required = new PredefinedAttribute (module, "System.Runtime.CompilerServices", "RequiredAttributeAttribute");
1696 Guid = new PredefinedAttribute (module, "System.Runtime.InteropServices", "GuidAttribute");
1697 AssemblyCulture = new PredefinedAttribute (module, "System.Reflection", "AssemblyCultureAttribute");
1698 AssemblyVersion = new PredefinedAttribute (module, "System.Reflection", "AssemblyVersionAttribute");
1699 AssemblyAlgorithmId = new PredefinedAttribute (module, "System.Reflection", "AssemblyAlgorithmIdAttribute");
1700 AssemblyFlags = new PredefinedAttribute (module, "System.Reflection", "AssemblyFlagsAttribute");
1701 AssemblyFileVersion = new PredefinedAttribute (module, "System.Reflection", "AssemblyFileVersionAttribute");
1702 ComImport = new PredefinedAttribute (module, "System.Runtime.InteropServices", "ComImportAttribute");
1703 CoClass = new PredefinedAttribute (module, "System.Runtime.InteropServices", "CoClassAttribute");
1704 AttributeUsage = new PredefinedAttribute (module, "System", "AttributeUsageAttribute");
1705 DefaultParameterValue = new PredefinedAttribute (module, "System.Runtime.InteropServices", "DefaultParameterValueAttribute");
1706 OptionalParameter = new PredefinedAttribute (module, "System.Runtime.InteropServices", "OptionalAttribute");
1707 UnverifiableCode = new PredefinedAttribute (module, "System.Security", "UnverifiableCodeAttribute");
1709 DefaultCharset = new PredefinedAttribute (module, "System.Runtime.InteropServices", "DefaultCharSetAttribute");
1710 TypeForwarder = new PredefinedAttribute (module, "System.Runtime.CompilerServices", "TypeForwardedToAttribute");
1711 FixedBuffer = new PredefinedAttribute (module, "System.Runtime.CompilerServices", "FixedBufferAttribute");
1712 CompilerGenerated = new PredefinedAttribute (module, "System.Runtime.CompilerServices", "CompilerGeneratedAttribute");
1713 InternalsVisibleTo = new PredefinedAttribute (module, "System.Runtime.CompilerServices", "InternalsVisibleToAttribute");
1714 RuntimeCompatibility = new PredefinedAttribute (module, "System.Runtime.CompilerServices", "RuntimeCompatibilityAttribute");
1715 DebuggerHidden = new PredefinedAttribute (module, "System.Diagnostics", "DebuggerHiddenAttribute");
1716 UnsafeValueType = new PredefinedAttribute (module, "System.Runtime.CompilerServices", "UnsafeValueTypeAttribute");
1717 UnmanagedFunctionPointer = new PredefinedAttribute (module, "System.Runtime.InteropServices", "UnmanagedFunctionPointerAttribute");
1718 DebuggerBrowsable = new PredefinedDebuggerBrowsableAttribute (module, "System.Diagnostics", "DebuggerBrowsableAttribute");
1720 Extension = new PredefinedAttribute (module, "System.Runtime.CompilerServices", "ExtensionAttribute");
1722 Dynamic = new PredefinedDynamicAttribute (module, "System.Runtime.CompilerServices", "DynamicAttribute");
1724 DefaultMember = new PredefinedAttribute (module, "System.Reflection", "DefaultMemberAttribute");
1725 DecimalConstant = new PredefinedDecimalAttribute (module, "System.Runtime.CompilerServices", "DecimalConstantAttribute");
1726 StructLayout = new PredefinedAttribute (module, "System.Runtime.InteropServices", "StructLayoutAttribute");
1727 FieldOffset = new PredefinedAttribute (module, "System.Runtime.InteropServices", "FieldOffsetAttribute");
1728 AssemblyProduct = new PredefinedAttribute (module, "System.Reflection", "AssemblyProductAttribute");
1729 AssemblyCompany = new PredefinedAttribute (module, "System.Reflection", "AssemblyCompanyAttribute");
1730 AssemblyDescription = new PredefinedAttribute (module, "System.Reflection", "AssemblyDescriptionAttribute");
1731 AssemblyCopyright = new PredefinedAttribute (module, "System.Reflection", "AssemblyCopyrightAttribute");
1732 AssemblyTrademark = new PredefinedAttribute (module, "System.Reflection", "AssemblyTrademarkAttribute");
1734 AsyncStateMachine = new PredefinedStateMachineAttribute (module, "System.Runtime.CompilerServices", "AsyncStateMachineAttribute");
1736 CallerMemberNameAttribute = new PredefinedAttribute (module, "System.Runtime.CompilerServices", "CallerMemberNameAttribute");
1737 CallerLineNumberAttribute = new PredefinedAttribute (module, "System.Runtime.CompilerServices", "CallerLineNumberAttribute");
1738 CallerFilePathAttribute = new PredefinedAttribute (module, "System.Runtime.CompilerServices", "CallerFilePathAttribute");
1740 // TODO: Should define only attributes which are used for comparison
1741 const System.Reflection.BindingFlags all_fields = System.Reflection.BindingFlags.Public |
1742 System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.DeclaredOnly;
1744 foreach (var fi in GetType ().GetFields (all_fields)) {
1745 ((PredefinedAttribute) fi.GetValue (this)).Define ();
1750 public class PredefinedAttribute : PredefinedType
1752 protected MethodSpec ctor;
1754 public PredefinedAttribute (ModuleContainer module, string ns, string name)
1755 : base (module, MemberKind.Class, ns, name)
1761 public MethodSpec Constructor {
1769 public static bool operator == (TypeSpec type, PredefinedAttribute pa)
1771 return type == pa.type && pa.type != null;
1774 public static bool operator != (TypeSpec type, PredefinedAttribute pa)
1776 return type != pa.type;
1779 public override int GetHashCode ()
1781 return base.GetHashCode ();
1784 public override bool Equals (object obj)
1786 throw new NotSupportedException ();
1789 public void EmitAttribute (ConstructorBuilder builder)
1791 if (ResolveBuilder ())
1792 builder.SetCustomAttribute (GetCtorMetaInfo (), AttributeEncoder.Empty);
1795 public void EmitAttribute (MethodBuilder builder)
1797 if (ResolveBuilder ())
1798 builder.SetCustomAttribute (GetCtorMetaInfo (), AttributeEncoder.Empty);
1801 public void EmitAttribute (PropertyBuilder builder)
1803 if (ResolveBuilder ())
1804 builder.SetCustomAttribute (GetCtorMetaInfo (), AttributeEncoder.Empty);
1807 public void EmitAttribute (FieldBuilder builder)
1809 if (ResolveBuilder ())
1810 builder.SetCustomAttribute (GetCtorMetaInfo (), AttributeEncoder.Empty);
1813 public void EmitAttribute (TypeBuilder builder)
1815 if (ResolveBuilder ())
1816 builder.SetCustomAttribute (GetCtorMetaInfo (), AttributeEncoder.Empty);
1819 public void EmitAttribute (AssemblyBuilder builder)
1821 if (ResolveBuilder ())
1822 builder.SetCustomAttribute (GetCtorMetaInfo (), AttributeEncoder.Empty);
1825 public void EmitAttribute (ModuleBuilder builder)
1827 if (ResolveBuilder ())
1828 builder.SetCustomAttribute (GetCtorMetaInfo (), AttributeEncoder.Empty);
1831 public void EmitAttribute (ParameterBuilder builder)
1833 if (ResolveBuilder ())
1834 builder.SetCustomAttribute (GetCtorMetaInfo (), AttributeEncoder.Empty);
1837 ConstructorInfo GetCtorMetaInfo ()
1839 return (ConstructorInfo) ctor.GetMetaInfo ();
1842 public bool ResolveBuilder ()
1848 // Handle all parameter-less attributes as optional
1853 ctor = (MethodSpec) MemberCache.FindMember (type, MemberFilter.Constructor (ParametersCompiled.EmptyReadOnlyParameters), BindingRestriction.DeclaredOnly);
1854 return ctor != null;
1858 public class PredefinedDebuggerBrowsableAttribute : PredefinedAttribute
1860 public PredefinedDebuggerBrowsableAttribute (ModuleContainer module, string ns, string name)
1861 : base (module, ns, name)
1865 public void EmitAttribute (FieldBuilder builder, System.Diagnostics.DebuggerBrowsableState state)
1867 var ctor = module.PredefinedMembers.DebuggerBrowsableAttributeCtor.Get ();
1871 AttributeEncoder encoder = new AttributeEncoder ();
1872 encoder.Encode ((int) state);
1873 encoder.EncodeEmptyNamedArguments ();
1875 builder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), encoder.ToArray ());
1879 public class PredefinedDecimalAttribute : PredefinedAttribute
1881 public PredefinedDecimalAttribute (ModuleContainer module, string ns, string name)
1882 : base (module, ns, name)
1886 public void EmitAttribute (ParameterBuilder builder, decimal value, Location loc)
1888 var ctor = module.PredefinedMembers.DecimalConstantAttributeCtor.Resolve (loc);
1892 int[] bits = decimal.GetBits (value);
1893 AttributeEncoder encoder = new AttributeEncoder ();
1894 encoder.Encode ((byte) (bits[3] >> 16));
1895 encoder.Encode ((byte) (bits[3] >> 31));
1896 encoder.Encode ((uint) bits[2]);
1897 encoder.Encode ((uint) bits[1]);
1898 encoder.Encode ((uint) bits[0]);
1899 encoder.EncodeEmptyNamedArguments ();
1901 builder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), encoder.ToArray ());
1904 public void EmitAttribute (FieldBuilder builder, decimal value, Location loc)
1906 var ctor = module.PredefinedMembers.DecimalConstantAttributeCtor.Resolve (loc);
1910 int[] bits = decimal.GetBits (value);
1911 AttributeEncoder encoder = new AttributeEncoder ();
1912 encoder.Encode ((byte) (bits[3] >> 16));
1913 encoder.Encode ((byte) (bits[3] >> 31));
1914 encoder.Encode ((uint) bits[2]);
1915 encoder.Encode ((uint) bits[1]);
1916 encoder.Encode ((uint) bits[0]);
1917 encoder.EncodeEmptyNamedArguments ();
1919 builder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), encoder.ToArray ());
1923 public class PredefinedStateMachineAttribute : PredefinedAttribute
1925 public PredefinedStateMachineAttribute (ModuleContainer module, string ns, string name)
1926 : base (module, ns, name)
1930 public void EmitAttribute (MethodBuilder builder, StateMachine type)
1932 var predefined_ctor = module.PredefinedMembers.AsyncStateMachineAttributeCtor;
1934 var ctor = predefined_ctor.Get ();
1939 AttributeEncoder encoder = new AttributeEncoder ();
1940 encoder.EncodeTypeName (type);
1941 encoder.EncodeEmptyNamedArguments ();
1943 builder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), encoder.ToArray ());
1947 public class PredefinedDynamicAttribute : PredefinedAttribute
1951 public PredefinedDynamicAttribute (ModuleContainer module, string ns, string name)
1952 : base (module, ns, name)
1956 public void EmitAttribute (FieldBuilder builder, TypeSpec type, Location loc)
1958 if (ResolveTransformationCtor (loc)) {
1959 var cab = new CustomAttributeBuilder ((ConstructorInfo) tctor.GetMetaInfo (), new object[] { GetTransformationFlags (type) });
1960 builder.SetCustomAttribute (cab);
1964 public void EmitAttribute (ParameterBuilder builder, TypeSpec type, Location loc)
1966 if (ResolveTransformationCtor (loc)) {
1967 var cab = new CustomAttributeBuilder ((ConstructorInfo) tctor.GetMetaInfo (), new object[] { GetTransformationFlags (type) });
1968 builder.SetCustomAttribute (cab);
1972 public void EmitAttribute (PropertyBuilder builder, TypeSpec type, Location loc)
1974 if (ResolveTransformationCtor (loc)) {
1975 var cab = new CustomAttributeBuilder ((ConstructorInfo) tctor.GetMetaInfo (), new object[] { GetTransformationFlags (type) });
1976 builder.SetCustomAttribute (cab);
1980 public void EmitAttribute (TypeBuilder builder, TypeSpec type, Location loc)
1982 if (ResolveTransformationCtor (loc)) {
1983 var cab = new CustomAttributeBuilder ((ConstructorInfo) tctor.GetMetaInfo (), new object[] { GetTransformationFlags (type) });
1984 builder.SetCustomAttribute (cab);
1989 // When any element of the type is a dynamic type
1991 // This method builds a transformation array for dynamic types
1992 // used in places where DynamicAttribute cannot be applied to.
1993 // It uses bool flag when type is of dynamic type and each
1994 // section always starts with "false" for some reason.
1996 // LAMESPEC: This should be part of C# specification
1998 // Example: Func<dynamic, int, dynamic[]>
1999 // Transformation: { false, true, false, false, true }
2001 static bool[] GetTransformationFlags (TypeSpec t)
2004 var ac = t as ArrayContainer;
2006 element = GetTransformationFlags (ac.Element);
2007 if (element == null)
2008 return new bool[] { false, false };
2010 bool[] res = new bool[element.Length + 1];
2012 Array.Copy (element, 0, res, 1, element.Length);
2020 List<bool> transform = null;
2021 var targs = t.TypeArguments;
2022 for (int i = 0; i < targs.Length; ++i) {
2023 element = GetTransformationFlags (targs[i]);
2024 if (element != null) {
2025 if (transform == null) {
2026 transform = new List<bool> ();
2027 for (int ii = 0; ii <= i; ++ii)
2028 transform.Add (false);
2031 transform.AddRange (element);
2032 } else if (transform != null) {
2033 transform.Add (false);
2037 if (transform != null)
2038 return transform.ToArray ();
2041 if (t.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
2042 return new bool[] { true };
2047 bool ResolveTransformationCtor (Location loc)
2052 tctor = module.PredefinedMembers.DynamicAttributeCtor.Resolve (loc);
2053 return tctor != null;