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 var resolve_printer = new SessionReportPrinter ();
288 SessionReportPrinter secondary_printer = null;
289 ReportPrinter prev_recorder = Report.SetPrinter (resolve_printer);
291 bool t1_is_attr = false;
292 bool t2_is_attr = false;
294 ATypeNameExpression expanded = null;
296 // TODO: Additional warnings such as CS0436 are swallowed because we don't
300 t1 = expression.ResolveAsType (context);
301 resolve_printer.EndSession ();
303 if (t1 != null && resolve_printer.ErrorsCount == 0)
304 t1_is_attr = t1.IsAttribute;
309 expanded = (ATypeNameExpression) expression.Clone (null);
310 expanded.Name += "Attribute";
312 secondary_printer = new SessionReportPrinter ();
313 Report.SetPrinter (secondary_printer);
314 t2 = expanded.ResolveAsType (context);
315 secondary_printer.EndSession ();
316 if (t2 != null && secondary_printer.ErrorsCount == 0)
317 t2_is_attr = t2.IsAttribute;
319 secondary_printer.EndSession ();
322 context.Module.Compiler.Report.SetPrinter (prev_recorder);
325 if (t1_is_attr && t2_is_attr && t1 != t2) {
326 if (!comparisonOnly) {
327 Report.Error (1614, Location, "`{0}' is ambiguous between `{1}' and `{2}'. Use either `@{0}' or `{0}Attribute'",
328 GetSignatureForError (), expression.GetSignatureForError (), expanded.GetSignatureForError ());
329 resolve_error = true;
348 resolve_error = true;
351 if (resolve_printer.IsEmpty) {
352 Report.SymbolRelatedToPreviousError (t1);
353 Report.Error (616, Location, "`{0}': is not an attribute class", t1.GetSignatureForError ());
355 resolve_printer.Merge (prev_recorder);
362 if (secondary_printer.IsEmpty) {
363 Report.SymbolRelatedToPreviousError (t2);
364 Report.Error (616, Location, "`{0}': is not an attribute class", t2.GetSignatureForError ());
366 secondary_printer.Merge (prev_recorder);
372 resolve_printer.Merge (prev_recorder);
375 public TypeSpec ResolveTypeForComparison ()
377 if (Type == null && !resolve_error)
378 ResolveAttributeType (true);
382 public string GetSignatureForError ()
385 return Type.GetSignatureForError ();
387 return expression.GetSignatureForError ();
390 public bool HasSecurityAttribute {
392 PredefinedAttribute pa = context.Module.PredefinedAttributes.Security;
393 return pa.IsDefined && TypeSpec.IsBaseClass (Type, pa.TypeSpec, false);
397 public bool IsValidSecurityAttribute ()
399 return HasSecurityAttribute && IsSecurityActionValid ();
402 static bool IsValidMethodImplOption (int value)
405 // Allow to use AggressiveInlining on any runtime/corlib
407 MethodImplOptions all = (MethodImplOptions) 256;
408 foreach (MethodImplOptions v in System.Enum.GetValues (typeof (MethodImplOptions))) {
412 return ((MethodImplOptions) value | all) == all;
415 static bool IsValidArgumentType (TypeSpec t)
418 var ac = (ArrayContainer) t;
425 switch (t.BuiltinType) {
426 case BuiltinTypeSpec.Type.Int:
427 case BuiltinTypeSpec.Type.UInt:
428 case BuiltinTypeSpec.Type.Long:
429 case BuiltinTypeSpec.Type.ULong:
430 case BuiltinTypeSpec.Type.Float:
431 case BuiltinTypeSpec.Type.Double:
432 case BuiltinTypeSpec.Type.Char:
433 case BuiltinTypeSpec.Type.Short:
434 case BuiltinTypeSpec.Type.Bool:
435 case BuiltinTypeSpec.Type.SByte:
436 case BuiltinTypeSpec.Type.Byte:
437 case BuiltinTypeSpec.Type.UShort:
439 case BuiltinTypeSpec.Type.String:
440 case BuiltinTypeSpec.Type.Object:
441 case BuiltinTypeSpec.Type.Dynamic:
442 case BuiltinTypeSpec.Type.Type:
449 // TODO: Don't use this ambiguous value
451 get { return expression.Name; }
454 public Report Report {
455 get { return context.Module.Compiler.Report; }
458 public MethodSpec Resolve ()
463 resolve_error = true;
467 ResolveAttributeType (false);
472 if (Type.IsAbstract) {
473 Report.Error (653, Location, "Cannot apply attribute class `{0}' because it is abstract", GetSignatureForError ());
477 ObsoleteAttribute obsolete_attr = Type.GetAttributeObsolete ();
478 if (obsolete_attr != null) {
479 AttributeTester.Report_ObsoleteMessage (obsolete_attr, Type.GetSignatureForError (), Location, Report);
482 ResolveContext rc = null;
485 // Try if the attribute is simple and has been resolved before
486 if (pos_args != null || !context.Module.AttributeConstructorCache.TryGetValue (Type, out ctor)) {
487 rc = CreateResolveContext ();
488 ctor = ResolveConstructor (rc);
493 if (pos_args == null && ctor.Parameters.IsEmpty)
494 context.Module.AttributeConstructorCache.Add (Type, ctor);
498 // Add [module: DefaultCharSet] to all DllImport import attributes
500 var module = context.Module;
501 if ((Type == module.PredefinedAttributes.DllImport || Type == module.PredefinedAttributes.UnmanagedFunctionPointer) && module.HasDefaultCharSet) {
503 rc = CreateResolveContext ();
505 AddModuleCharSet (rc);
508 if (NamedArguments != null) {
510 rc = CreateResolveContext ();
512 if (!ResolveNamedArguments (rc))
516 resolve_error = false;
520 MethodSpec ResolveConstructor (ResolveContext ec)
522 if (pos_args != null) {
524 pos_args.Resolve (ec, out dynamic);
526 Error_AttributeArgumentIsDynamic (ec.MemberContext, loc);
531 return Expression.ConstructorLookup (ec, Type, ref pos_args, loc);
534 bool ResolveNamedArguments (ResolveContext ec)
536 int named_arg_count = NamedArguments.Count;
537 var seen_names = new List<string> (named_arg_count);
539 named_values = new List<KeyValuePair<MemberExpr, NamedArgument>> (named_arg_count);
541 foreach (NamedArgument a in NamedArguments) {
542 string name = a.Name;
543 if (seen_names.Contains (name)) {
544 ec.Report.Error (643, a.Location, "Duplicate named attribute `{0}' argument", name);
548 seen_names.Add (name);
552 Expression member = Expression.MemberLookup (ec, false, Type, name, 0, Expression.MemberLookupRestrictions.ExactArity, loc);
554 if (member == null) {
555 member = Expression.MemberLookup (ec, true, Type, name, 0, Expression.MemberLookupRestrictions.ExactArity, loc);
557 if (member != null) {
558 // TODO: ec.Report.SymbolRelatedToPreviousError (member);
559 Expression.ErrorIsInaccesible (ec, member.GetSignatureForError (), loc);
565 Expression.Error_TypeDoesNotContainDefinition (ec, Location, Type, name);
569 if (!(member is PropertyExpr || member is FieldExpr)) {
570 Error_InvalidNamedArgument (ec, a);
574 ObsoleteAttribute obsolete_attr;
576 if (member is PropertyExpr) {
577 var pi = ((PropertyExpr) member).PropertyInfo;
579 if (!pi.HasSet || !pi.HasGet || pi.IsStatic || !pi.Get.IsPublic || !pi.Set.IsPublic) {
580 ec.Report.SymbolRelatedToPreviousError (pi);
581 Error_InvalidNamedArgument (ec, a);
585 if (!IsValidArgumentType (member.Type)) {
586 ec.Report.SymbolRelatedToPreviousError (pi);
587 Error_InvalidNamedArgumentType (ec, a);
591 obsolete_attr = pi.GetAttributeObsolete ();
592 pi.MemberDefinition.SetIsAssigned ();
594 var fi = ((FieldExpr) member).Spec;
596 if (fi.IsReadOnly || fi.IsStatic || !fi.IsPublic) {
597 Error_InvalidNamedArgument (ec, a);
601 if (!IsValidArgumentType (member.Type)) {
602 ec.Report.SymbolRelatedToPreviousError (fi);
603 Error_InvalidNamedArgumentType (ec, a);
607 obsolete_attr = fi.GetAttributeObsolete ();
608 fi.MemberDefinition.SetIsAssigned ();
611 if (obsolete_attr != null && !context.IsObsolete)
612 AttributeTester.Report_ObsoleteMessage (obsolete_attr, member.GetSignatureForError (), member.Location, Report);
614 if (a.Type != member.Type) {
615 a.Expr = Convert.ImplicitConversionRequired (ec, a.Expr, member.Type, a.Expr.Location);
619 named_values.Add (new KeyValuePair<MemberExpr, NamedArgument> ((MemberExpr) member, a));
626 /// Get a string containing a list of valid targets for the attribute 'attr'
628 public string GetValidTargets ()
630 StringBuilder sb = new StringBuilder ();
631 AttributeTargets targets = Type.GetAttributeUsage (context.Module.PredefinedAttributes.AttributeUsage).ValidOn;
633 if ((targets & AttributeTargets.Assembly) != 0)
634 sb.Append ("assembly, ");
636 if ((targets & AttributeTargets.Module) != 0)
637 sb.Append ("module, ");
639 if ((targets & AttributeTargets.Class) != 0)
640 sb.Append ("class, ");
642 if ((targets & AttributeTargets.Struct) != 0)
643 sb.Append ("struct, ");
645 if ((targets & AttributeTargets.Enum) != 0)
646 sb.Append ("enum, ");
648 if ((targets & AttributeTargets.Constructor) != 0)
649 sb.Append ("constructor, ");
651 if ((targets & AttributeTargets.Method) != 0)
652 sb.Append ("method, ");
654 if ((targets & AttributeTargets.Property) != 0)
655 sb.Append ("property, indexer, ");
657 if ((targets & AttributeTargets.Field) != 0)
658 sb.Append ("field, ");
660 if ((targets & AttributeTargets.Event) != 0)
661 sb.Append ("event, ");
663 if ((targets & AttributeTargets.Interface) != 0)
664 sb.Append ("interface, ");
666 if ((targets & AttributeTargets.Parameter) != 0)
667 sb.Append ("parameter, ");
669 if ((targets & AttributeTargets.Delegate) != 0)
670 sb.Append ("delegate, ");
672 if ((targets & AttributeTargets.ReturnValue) != 0)
673 sb.Append ("return, ");
675 if ((targets & AttributeTargets.GenericParameter) != 0)
676 sb.Append ("type parameter, ");
678 return sb.Remove (sb.Length - 2, 2).ToString ();
681 public AttributeUsageAttribute GetAttributeUsageAttribute ()
684 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
685 // But because a lot of attribute class code must be rewritten will be better to wait...
689 return DefaultUsageAttribute;
691 AttributeUsageAttribute usage_attribute = new AttributeUsageAttribute ((AttributeTargets) ((Constant) pos_args[0].Expr).GetValue ());
693 var field = GetNamedValue ("AllowMultiple") as BoolConstant;
695 usage_attribute.AllowMultiple = field.Value;
697 field = GetNamedValue ("Inherited") as BoolConstant;
699 usage_attribute.Inherited = field.Value;
701 return usage_attribute;
705 /// Returns custom name of indexer
707 public string GetIndexerAttributeValue ()
710 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
711 // But because a lot of attribute class code must be rewritten will be better to wait...
714 if (resolve_error || pos_args.Count != 1 || !(pos_args[0].Expr is Constant))
717 return ((Constant) pos_args[0].Expr).GetValue () as string;
721 /// Returns condition of ConditionalAttribute
723 public string GetConditionalAttributeValue ()
726 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
727 // But because a lot of attribute class code must be rewritten will be better to wait...
733 return ((Constant) pos_args[0].Expr).GetValue () as string;
737 /// Creates the instance of ObsoleteAttribute from this attribute instance
739 public ObsoleteAttribute GetObsoleteAttribute ()
742 // corlib only case when obsolete is used before is resolved
743 var c = Type.MemberDefinition as Class;
744 if (c != null && !c.HasMembersDefined)
747 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
748 // But because a lot of attribute class code must be rewritten will be better to wait...
755 if (pos_args == null)
756 return new ObsoleteAttribute ();
758 string msg = ((Constant) pos_args[0].Expr).GetValue () as string;
759 if (pos_args.Count == 1)
760 return new ObsoleteAttribute (msg);
762 return new ObsoleteAttribute (msg, ((BoolConstant) pos_args[1].Expr).Value);
766 /// Returns value of CLSCompliantAttribute contructor parameter but because the method can be called
767 /// before ApplyAttribute. We need to resolve the arguments.
768 /// This situation occurs when class deps is differs from Emit order.
770 public bool GetClsCompliantAttributeValue ()
773 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
774 // But because a lot of attribute class code must be rewritten will be better to wait...
780 return ((BoolConstant) pos_args[0].Expr).Value;
783 public TypeSpec GetCoClassAttributeValue ()
791 return GetArgumentType ();
794 public bool CheckTarget ()
796 string[] valid_targets = Owner.ValidAttributeTargets;
797 if (ExplicitTarget == null || ExplicitTarget == valid_targets [0]) {
798 Target = Owner.AttributeTargets;
802 // TODO: we can skip the first item
803 if (Array.Exists (valid_targets, i => i == ExplicitTarget)) {
804 switch (ExplicitTarget) {
805 case "return": Target = AttributeTargets.ReturnValue; return true;
806 case "param": Target = AttributeTargets.Parameter; return true;
807 case "field": Target = AttributeTargets.Field; return true;
808 case "method": Target = AttributeTargets.Method; return true;
809 case "property": Target = AttributeTargets.Property; return true;
810 case "module": Target = AttributeTargets.Module; return true;
812 throw new InternalErrorException ("Unknown explicit target: " + ExplicitTarget);
815 StringBuilder sb = new StringBuilder ();
816 foreach (string s in valid_targets) {
820 sb.Remove (sb.Length - 2, 2);
821 Report.Warning (657, 1, Location,
822 "`{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",
823 ExplicitTarget, sb.ToString ());
828 /// Tests permitted SecurityAction for assembly or other types
830 bool IsSecurityActionValid ()
832 SecurityAction action = GetSecurityActionValue ();
833 bool for_assembly = Target == AttributeTargets.Assembly || Target == AttributeTargets.Module;
836 #pragma warning disable 618
837 case SecurityAction.Demand:
838 case SecurityAction.Assert:
839 case SecurityAction.Deny:
840 case SecurityAction.PermitOnly:
841 case SecurityAction.LinkDemand:
842 case SecurityAction.InheritanceDemand:
847 case SecurityAction.RequestMinimum:
848 case SecurityAction.RequestOptional:
849 case SecurityAction.RequestRefuse:
853 #pragma warning restore 618
856 Error_AttributeEmitError ("SecurityAction is out of range");
860 Error_AttributeEmitError (String.Concat ("SecurityAction `", action, "' is not valid for this declaration"));
864 System.Security.Permissions.SecurityAction GetSecurityActionValue ()
866 return (SecurityAction) ((Constant) pos_args[0].Expr).GetValue ();
870 /// Creates instance of SecurityAttribute class and add result of CreatePermission method to permission table.
872 /// <returns></returns>
873 public void ExtractSecurityPermissionSet (MethodSpec ctor, ref SecurityType permissions)
876 object[] values = new object[pos_args.Count];
877 for (int i = 0; i < values.Length; ++i)
878 values[i] = ((Constant) pos_args[i].Expr).GetValue ();
881 object[] prop_values;
882 if (named_values == null) {
886 prop = new PropertyInfo[named_values.Count];
887 prop_values = new object [named_values.Count];
888 for (int i = 0; i < prop.Length; ++i) {
889 prop [i] = ((PropertyExpr) named_values [i].Key).PropertyInfo.MetaInfo;
890 prop_values [i] = ((Constant) named_values [i].Value.Expr).GetValue ();
894 if (permissions == null)
895 permissions = new SecurityType ();
897 var cab = new CustomAttributeBuilder ((ConstructorInfo) ctor.GetMetaInfo (), values, prop, prop_values);
898 permissions.Add (cab);
900 throw new NotSupportedException ();
904 public Constant GetNamedValue (string name)
906 if (named_values == null)
909 for (int i = 0; i < named_values.Count; ++i) {
910 if (named_values [i].Value.Name == name)
911 return named_values [i].Value.Expr as Constant;
917 public CharSet GetCharSetValue ()
919 return (CharSet) System.Enum.Parse (typeof (CharSet), ((Constant) pos_args[0].Expr).GetValue ().ToString ());
922 public bool HasField (string fieldName)
924 if (named_values == null)
927 foreach (var na in named_values) {
928 if (na.Value.Name == fieldName)
936 // Returns true for MethodImplAttribute with MethodImplOptions.InternalCall value
938 public bool IsInternalCall ()
940 return (GetMethodImplOptions () & MethodImplOptions.InternalCall) != 0;
943 public MethodImplOptions GetMethodImplOptions ()
945 MethodImplOptions options = 0;
946 if (pos_args.Count == 1) {
947 options = (MethodImplOptions) System.Enum.Parse (typeof (MethodImplOptions), ((Constant) pos_args[0].Expr).GetValue ().ToString ());
948 } else if (HasField ("Value")) {
949 var named = GetNamedValue ("Value");
950 options = (MethodImplOptions) System.Enum.Parse (typeof (MethodImplOptions), named.GetValue ().ToString ());
957 // Returns true for StructLayoutAttribute with LayoutKind.Explicit value
959 public bool IsExplicitLayoutKind ()
961 if (pos_args == null || pos_args.Count != 1)
964 var value = (LayoutKind) System.Enum.Parse (typeof (LayoutKind), ((Constant) pos_args[0].Expr).GetValue ().ToString ());
965 return value == LayoutKind.Explicit;
968 public Expression GetParameterDefaultValue ()
970 if (pos_args == null)
973 return pos_args[0].Expr;
976 public override bool Equals (object obj)
978 Attribute a = obj as Attribute;
982 return Type == a.Type && Target == a.Target;
985 public override int GetHashCode ()
987 return Type.GetHashCode () ^ Target.GetHashCode ();
991 /// Emit attribute for Attributable symbol
993 public void Emit (Dictionary<Attribute, List<Attribute>> allEmitted)
995 var ctor = Resolve ();
999 var predefined = context.Module.PredefinedAttributes;
1001 AttributeUsageAttribute usage_attr = Type.GetAttributeUsage (predefined.AttributeUsage);
1002 if ((usage_attr.ValidOn & Target) == 0) {
1003 Report.Error (592, Location, "The attribute `{0}' is not valid on this declaration type. " +
1004 "It is valid on `{1}' declarations only",
1005 GetSignatureForError (), GetValidTargets ());
1010 if (pos_args == null && named_values == null) {
1011 cdata = AttributeEncoder.Empty;
1013 AttributeEncoder encoder = new AttributeEncoder ();
1015 if (pos_args != null) {
1016 var param_types = ctor.Parameters.Types;
1017 for (int j = 0; j < pos_args.Count; ++j) {
1018 var pt = param_types[j];
1019 var arg_expr = pos_args[j].Expr;
1021 if ((Type == predefined.IndexerName || Type == predefined.Conditional) && arg_expr is Constant) {
1022 string v = ((Constant) arg_expr).GetValue () as string;
1023 if (!Tokenizer.IsValidIdentifier (v) || (Type == predefined.IndexerName && Tokenizer.IsKeyword (v))) {
1024 context.Module.Compiler.Report.Error (633, arg_expr.Location,
1025 "The argument to the `{0}' attribute must be a valid identifier", GetSignatureForError ());
1028 } else if (Type == predefined.Guid) {
1030 string v = ((StringConstant) arg_expr).Value;
1032 } catch (Exception e) {
1033 Error_AttributeEmitError (e.Message);
1036 } else if (Type == predefined.AttributeUsage) {
1037 int v = ((IntConstant) ((EnumConstant) arg_expr).Child).Value;
1039 context.Module.Compiler.Report.Error (591, Location, "Invalid value for argument to `{0}' attribute",
1040 "System.AttributeUsage");
1042 } else if (Type == predefined.MarshalAs) {
1043 if (pos_args.Count == 1) {
1044 var u_type = (UnmanagedType) System.Enum.Parse (typeof (UnmanagedType), ((Constant) pos_args[0].Expr).GetValue ().ToString ());
1045 if (u_type == UnmanagedType.ByValArray && !(Owner is FieldBase)) {
1046 Error_AttributeEmitError ("Specified unmanaged type is only valid on fields");
1049 } else if (Type == predefined.DllImport) {
1050 if (pos_args.Count == 1 && pos_args[0].Expr is Constant) {
1051 var value = ((Constant) pos_args[0].Expr).GetValue () as string;
1052 if (string.IsNullOrEmpty (value))
1053 Error_AttributeEmitError ("DllName cannot be empty or null");
1055 } else if (Type == predefined.MethodImpl) {
1056 if (pos_args.Count == 1) {
1057 var value = (int) ((Constant) arg_expr).GetValueAsLong ();
1059 if (!IsValidMethodImplOption (value)) {
1060 Error_AttributeEmitError ("Incorrect argument value");
1066 arg_expr.EncodeAttributeValue (context, encoder, pt);
1070 if (named_values != null) {
1071 encoder.Encode ((ushort) named_values.Count);
1072 foreach (var na in named_values) {
1073 if (na.Key is FieldExpr)
1074 encoder.Encode ((byte) 0x53);
1076 encoder.Encode ((byte) 0x54);
1078 encoder.Encode (na.Key.Type);
1079 encoder.Encode (na.Value.Name);
1080 na.Value.Expr.EncodeAttributeValue (context, encoder, na.Key.Type);
1083 encoder.EncodeEmptyNamedArguments ();
1086 cdata = encoder.ToArray ();
1089 if (!ctor.DeclaringType.IsConditionallyExcluded (context)) {
1091 foreach (Attributable target in targets)
1092 target.ApplyAttributeBuilder (this, ctor, cdata, predefined);
1093 } catch (Exception e) {
1094 if (e is BadImageFormat && Report.Errors > 0)
1097 Error_AttributeEmitError (e.Message);
1102 if (!usage_attr.AllowMultiple && allEmitted != null) {
1103 if (allEmitted.ContainsKey (this)) {
1104 var a = allEmitted [this];
1106 a = new List<Attribute> (2);
1107 allEmitted [this] = a;
1111 allEmitted.Add (this, null);
1115 if (!context.Module.Compiler.Settings.VerifyClsCompliance)
1118 // Here we are testing attribute arguments for array usage (error 3016)
1119 if (Owner.IsClsComplianceRequired ()) {
1120 if (pos_args != null)
1121 pos_args.CheckArrayAsAttribute (context.Module.Compiler);
1123 if (NamedArguments == null)
1126 NamedArguments.CheckArrayAsAttribute (context.Module.Compiler);
1130 private Expression GetValue ()
1132 if (pos_args == null || pos_args.Count < 1)
1135 return pos_args[0].Expr;
1138 public string GetString ()
1140 Expression e = GetValue ();
1141 if (e is StringConstant)
1142 return ((StringConstant)e).Value;
1146 public bool GetBoolean ()
1148 Expression e = GetValue ();
1149 if (e is BoolConstant)
1150 return ((BoolConstant)e).Value;
1154 public TypeSpec GetArgumentType ()
1156 TypeOf e = GetValue () as TypeOf;
1159 return e.TypeArgument;
1163 public class Attributes
1165 public readonly List<Attribute> Attrs;
1167 public Attributes (Attribute a)
1169 Attrs = new List<Attribute> ();
1173 public Attributes (List<Attribute> attrs)
1175 Attrs = attrs ?? new List<Attribute> ();
1178 public void AddAttribute (Attribute attr)
1183 public void AddAttributes (List<Attribute> attrs)
1185 Attrs.AddRange (attrs);
1188 public void AttachTo (Attributable attributable, IMemberContext context)
1190 foreach (Attribute a in Attrs)
1191 a.AttachTo (attributable, context);
1194 public Attributes Clone ()
1196 var al = new List<Attribute> (Attrs.Count);
1197 foreach (Attribute a in Attrs)
1198 al.Add (a.Clone ());
1200 return new Attributes (al);
1204 /// Checks whether attribute target is valid for the current element
1206 public bool CheckTargets ()
1208 for (int i = 0; i < Attrs.Count; ++i) {
1209 if (!Attrs [i].CheckTarget ())
1210 Attrs.RemoveAt (i--);
1216 public void ConvertGlobalAttributes (TypeContainer member, NamespaceContainer currentNamespace, bool isGlobal)
1218 var member_explicit_targets = member.ValidAttributeTargets;
1219 for (int i = 0; i < Attrs.Count; ++i) {
1220 var attr = Attrs[0];
1221 if (attr.ExplicitTarget == null)
1225 for (ii = 0; ii < member_explicit_targets.Length; ++ii) {
1226 if (attr.ExplicitTarget == member_explicit_targets[ii]) {
1232 if (ii < 0 || !isGlobal)
1235 member.Module.AddAttribute (attr, currentNamespace);
1241 public bool HasResolveError()
1243 foreach (var a in Attrs) {
1251 public Attribute Search (PredefinedAttribute t)
1253 return Search (null, t);
1256 public Attribute Search (string explicitTarget, PredefinedAttribute t)
1258 foreach (Attribute a in Attrs) {
1259 if (explicitTarget != null && a.ExplicitTarget != explicitTarget)
1262 if (a.ResolveTypeForComparison () == t)
1269 /// Returns all attributes of type 't'. Use it when attribute is AllowMultiple = true
1271 public Attribute[] SearchMulti (PredefinedAttribute t)
1273 List<Attribute> ar = null;
1275 foreach (Attribute a in Attrs) {
1276 if (a.ResolveTypeForComparison () == t) {
1278 ar = new List<Attribute> (Attrs.Count);
1283 return ar == null ? null : ar.ToArray ();
1290 Dictionary<Attribute, List<Attribute>> ld = Attrs.Count > 1 ? new Dictionary<Attribute, List<Attribute>> () : null;
1292 foreach (Attribute a in Attrs)
1295 if (ld == null || ld.Count == 0)
1298 foreach (var d in ld) {
1299 if (d.Value == null)
1302 Attribute a = d.Key;
1304 foreach (Attribute collision in d.Value)
1305 a.Report.SymbolRelatedToPreviousError (collision.Location, "");
1307 a.Report.Error (579, a.Location, "The attribute `{0}' cannot be applied multiple times",
1308 a.GetSignatureForError ());
1312 public bool Contains (PredefinedAttribute t)
1314 return Search (t) != null;
1318 public sealed class AttributeEncoder
1321 public enum EncodedTypeProperties
1325 TypeParameter = 1 << 1
1328 public static readonly byte[] Empty;
1332 const ushort Version = 1;
1334 static AttributeEncoder ()
1336 Empty = new byte[4];
1337 Empty[0] = (byte) Version;
1340 public AttributeEncoder ()
1342 buffer = new byte[32];
1346 public void Encode (bool value)
1348 Encode (value ? (byte) 1 : (byte) 0);
1351 public void Encode (byte value)
1353 if (pos == buffer.Length)
1356 buffer [pos++] = value;
1359 public void Encode (sbyte value)
1361 Encode ((byte) value);
1364 public void Encode (short value)
1366 if (pos + 2 > buffer.Length)
1369 buffer[pos++] = (byte) value;
1370 buffer[pos++] = (byte) (value >> 8);
1373 public void Encode (ushort value)
1375 Encode ((short) value);
1378 public void Encode (int value)
1380 if (pos + 4 > buffer.Length)
1383 buffer[pos++] = (byte) value;
1384 buffer[pos++] = (byte) (value >> 8);
1385 buffer[pos++] = (byte) (value >> 16);
1386 buffer[pos++] = (byte) (value >> 24);
1389 public void Encode (uint value)
1391 Encode ((int) value);
1394 public void Encode (long value)
1396 if (pos + 8 > buffer.Length)
1399 buffer[pos++] = (byte) value;
1400 buffer[pos++] = (byte) (value >> 8);
1401 buffer[pos++] = (byte) (value >> 16);
1402 buffer[pos++] = (byte) (value >> 24);
1403 buffer[pos++] = (byte) (value >> 32);
1404 buffer[pos++] = (byte) (value >> 40);
1405 buffer[pos++] = (byte) (value >> 48);
1406 buffer[pos++] = (byte) (value >> 56);
1409 public void Encode (ulong value)
1411 Encode ((long) value);
1414 public void Encode (float value)
1416 Encode (SingleConverter.SingleToInt32Bits (value));
1419 public void Encode (double value)
1421 Encode (BitConverter.DoubleToInt64Bits (value));
1424 public void Encode (string value)
1426 if (value == null) {
1427 Encode ((byte) 0xFF);
1431 var buf = Encoding.UTF8.GetBytes(value);
1432 WriteCompressedValue (buf.Length);
1434 if (pos + buf.Length > buffer.Length)
1437 Buffer.BlockCopy (buf, 0, buffer, pos, buf.Length);
1441 public EncodedTypeProperties Encode (TypeSpec type)
1443 switch (type.BuiltinType) {
1444 case BuiltinTypeSpec.Type.Bool:
1445 Encode ((byte) 0x02);
1447 case BuiltinTypeSpec.Type.Char:
1448 Encode ((byte) 0x03);
1450 case BuiltinTypeSpec.Type.SByte:
1451 Encode ((byte) 0x04);
1453 case BuiltinTypeSpec.Type.Byte:
1454 Encode ((byte) 0x05);
1456 case BuiltinTypeSpec.Type.Short:
1457 Encode ((byte) 0x06);
1459 case BuiltinTypeSpec.Type.UShort:
1460 Encode ((byte) 0x07);
1462 case BuiltinTypeSpec.Type.Int:
1463 Encode ((byte) 0x08);
1465 case BuiltinTypeSpec.Type.UInt:
1466 Encode ((byte) 0x09);
1468 case BuiltinTypeSpec.Type.Long:
1469 Encode ((byte) 0x0A);
1471 case BuiltinTypeSpec.Type.ULong:
1472 Encode ((byte) 0x0B);
1474 case BuiltinTypeSpec.Type.Float:
1475 Encode ((byte) 0x0C);
1477 case BuiltinTypeSpec.Type.Double:
1478 Encode ((byte) 0x0D);
1480 case BuiltinTypeSpec.Type.String:
1481 Encode ((byte) 0x0E);
1483 case BuiltinTypeSpec.Type.Type:
1484 Encode ((byte) 0x50);
1486 case BuiltinTypeSpec.Type.Object:
1487 Encode ((byte) 0x51);
1489 case BuiltinTypeSpec.Type.Dynamic:
1490 Encode ((byte) 0x51);
1491 return EncodedTypeProperties.DynamicType;
1494 Encode ((byte) 0x1D);
1495 return Encode (TypeManager.GetElementType (type));
1498 if (type.Kind == MemberKind.Enum) {
1499 Encode ((byte) 0x55);
1500 EncodeTypeName (type);
1506 return EncodedTypeProperties.None;
1509 public void EncodeTypeName (TypeSpec type)
1511 var old_type = type.GetMetaInfo ();
1512 Encode (type.MemberDefinition.IsImported ? old_type.AssemblyQualifiedName : old_type.FullName);
1515 public void EncodeTypeName (TypeContainer type)
1517 Encode (type.GetSignatureForMetadata ());
1522 // Encodes single property named argument per call
1524 public void EncodeNamedPropertyArgument (PropertySpec property, Constant value)
1526 Encode ((ushort) 1); // length
1527 Encode ((byte) 0x54); // property
1528 Encode (property.MemberType);
1529 Encode (property.Name);
1530 value.EncodeAttributeValue (null, this, property.MemberType);
1534 // Encodes single field named argument per call
1536 public void EncodeNamedFieldArgument (FieldSpec field, Constant value)
1538 Encode ((ushort) 1); // length
1539 Encode ((byte) 0x53); // field
1540 Encode (field.MemberType);
1541 Encode (field.Name);
1542 value.EncodeAttributeValue (null, this, field.MemberType);
1545 public void EncodeNamedArguments<T> (T[] members, Constant[] values) where T : MemberSpec, IInterfaceMemberSpec
1547 Encode ((ushort) members.Length);
1549 for (int i = 0; i < members.Length; ++i)
1551 var member = members[i];
1553 if (member.Kind == MemberKind.Field)
1554 Encode ((byte) 0x53);
1555 else if (member.Kind == MemberKind.Property)
1556 Encode ((byte) 0x54);
1558 throw new NotImplementedException (member.Kind.ToString ());
1560 Encode (member.MemberType);
1561 Encode (member.Name);
1562 values [i].EncodeAttributeValue (null, this, member.MemberType);
1566 public void EncodeEmptyNamedArguments ()
1568 Encode ((ushort) 0);
1573 int size = System.Math.Max (pos * 4, pos + inc + 2);
1574 Array.Resize (ref buffer, size);
1577 void WriteCompressedValue (int value)
1580 Encode ((byte) value);
1584 if (value < 0x4000) {
1585 Encode ((byte) (0x80 | (value >> 8)));
1586 Encode ((byte) value);
1593 public byte[] ToArray ()
1595 byte[] buf = new byte[pos];
1596 Array.Copy (buffer, buf, pos);
1603 /// Helper class for attribute verification routine.
1605 static class AttributeTester
1608 /// Common method for Obsolete error/warning reporting.
1610 public static void Report_ObsoleteMessage (ObsoleteAttribute oa, string member, Location loc, Report Report)
1613 Report.Error (619, loc, "`{0}' is obsolete: `{1}'", member, oa.Message);
1617 if (oa.Message == null || oa.Message.Length == 0) {
1618 Report.Warning (612, 1, loc, "`{0}' is obsolete", member);
1621 Report.Warning (618, 2, loc, "`{0}' is obsolete: `{1}'", member, oa.Message);
1626 // Predefined attribute types
1628 public class PredefinedAttributes
1630 // Build-in attributes
1631 public readonly PredefinedAttribute ParamArray;
1632 public readonly PredefinedAttribute Out;
1634 // Optional attributes
1635 public readonly PredefinedAttribute Obsolete;
1636 public readonly PredefinedAttribute DllImport;
1637 public readonly PredefinedAttribute MethodImpl;
1638 public readonly PredefinedAttribute MarshalAs;
1639 public readonly PredefinedAttribute In;
1640 public readonly PredefinedAttribute IndexerName;
1641 public readonly PredefinedAttribute Conditional;
1642 public readonly PredefinedAttribute CLSCompliant;
1643 public readonly PredefinedAttribute Security;
1644 public readonly PredefinedAttribute Required;
1645 public readonly PredefinedAttribute Guid;
1646 public readonly PredefinedAttribute AssemblyCulture;
1647 public readonly PredefinedAttribute AssemblyVersion;
1648 public readonly PredefinedAttribute AssemblyAlgorithmId;
1649 public readonly PredefinedAttribute AssemblyFlags;
1650 public readonly PredefinedAttribute AssemblyFileVersion;
1651 public readonly PredefinedAttribute ComImport;
1652 public readonly PredefinedAttribute CoClass;
1653 public readonly PredefinedAttribute AttributeUsage;
1654 public readonly PredefinedAttribute DefaultParameterValue;
1655 public readonly PredefinedAttribute OptionalParameter;
1656 public readonly PredefinedAttribute UnverifiableCode;
1657 public readonly PredefinedAttribute DefaultCharset;
1658 public readonly PredefinedAttribute TypeForwarder;
1659 public readonly PredefinedAttribute FixedBuffer;
1660 public readonly PredefinedAttribute CompilerGenerated;
1661 public readonly PredefinedAttribute InternalsVisibleTo;
1662 public readonly PredefinedAttribute RuntimeCompatibility;
1663 public readonly PredefinedAttribute DebuggerHidden;
1664 public readonly PredefinedAttribute UnsafeValueType;
1665 public readonly PredefinedAttribute UnmanagedFunctionPointer;
1666 public readonly PredefinedDebuggerBrowsableAttribute DebuggerBrowsable;
1667 public readonly PredefinedAttribute DebuggerStepThrough;
1668 public readonly PredefinedDebuggableAttribute Debuggable;
1671 public readonly PredefinedAttribute Extension;
1674 public readonly PredefinedDynamicAttribute Dynamic;
1677 public readonly PredefinedStateMachineAttribute AsyncStateMachine;
1680 // Optional types which are used as types and for member lookup
1682 public readonly PredefinedAttribute DefaultMember;
1683 public readonly PredefinedDecimalAttribute DecimalConstant;
1684 public readonly PredefinedAttribute StructLayout;
1685 public readonly PredefinedAttribute FieldOffset;
1686 public readonly PredefinedAttribute AssemblyProduct;
1687 public readonly PredefinedAttribute AssemblyCompany;
1688 public readonly PredefinedAttribute AssemblyDescription;
1689 public readonly PredefinedAttribute AssemblyCopyright;
1690 public readonly PredefinedAttribute AssemblyTrademark;
1691 public readonly PredefinedAttribute CallerMemberNameAttribute;
1692 public readonly PredefinedAttribute CallerLineNumberAttribute;
1693 public readonly PredefinedAttribute CallerFilePathAttribute;
1695 public PredefinedAttributes (ModuleContainer module)
1697 ParamArray = new PredefinedAttribute (module, "System", "ParamArrayAttribute");
1698 Out = new PredefinedAttribute (module, "System.Runtime.InteropServices", "OutAttribute");
1699 ParamArray.Resolve ();
1702 Obsolete = new PredefinedAttribute (module, "System", "ObsoleteAttribute");
1703 DllImport = new PredefinedAttribute (module, "System.Runtime.InteropServices", "DllImportAttribute");
1704 MethodImpl = new PredefinedAttribute (module, "System.Runtime.CompilerServices", "MethodImplAttribute");
1705 MarshalAs = new PredefinedAttribute (module, "System.Runtime.InteropServices", "MarshalAsAttribute");
1706 In = new PredefinedAttribute (module, "System.Runtime.InteropServices", "InAttribute");
1707 IndexerName = new PredefinedAttribute (module, "System.Runtime.CompilerServices", "IndexerNameAttribute");
1708 Conditional = new PredefinedAttribute (module, "System.Diagnostics", "ConditionalAttribute");
1709 CLSCompliant = new PredefinedAttribute (module, "System", "CLSCompliantAttribute");
1710 Security = new PredefinedAttribute (module, "System.Security.Permissions", "SecurityAttribute");
1711 Required = new PredefinedAttribute (module, "System.Runtime.CompilerServices", "RequiredAttributeAttribute");
1712 Guid = new PredefinedAttribute (module, "System.Runtime.InteropServices", "GuidAttribute");
1713 AssemblyCulture = new PredefinedAttribute (module, "System.Reflection", "AssemblyCultureAttribute");
1714 AssemblyVersion = new PredefinedAttribute (module, "System.Reflection", "AssemblyVersionAttribute");
1715 AssemblyAlgorithmId = new PredefinedAttribute (module, "System.Reflection", "AssemblyAlgorithmIdAttribute");
1716 AssemblyFlags = new PredefinedAttribute (module, "System.Reflection", "AssemblyFlagsAttribute");
1717 AssemblyFileVersion = new PredefinedAttribute (module, "System.Reflection", "AssemblyFileVersionAttribute");
1718 ComImport = new PredefinedAttribute (module, "System.Runtime.InteropServices", "ComImportAttribute");
1719 CoClass = new PredefinedAttribute (module, "System.Runtime.InteropServices", "CoClassAttribute");
1720 AttributeUsage = new PredefinedAttribute (module, "System", "AttributeUsageAttribute");
1721 DefaultParameterValue = new PredefinedAttribute (module, "System.Runtime.InteropServices", "DefaultParameterValueAttribute");
1722 OptionalParameter = new PredefinedAttribute (module, "System.Runtime.InteropServices", "OptionalAttribute");
1723 UnverifiableCode = new PredefinedAttribute (module, "System.Security", "UnverifiableCodeAttribute");
1725 DefaultCharset = new PredefinedAttribute (module, "System.Runtime.InteropServices", "DefaultCharSetAttribute");
1726 TypeForwarder = new PredefinedAttribute (module, "System.Runtime.CompilerServices", "TypeForwardedToAttribute");
1727 FixedBuffer = new PredefinedAttribute (module, "System.Runtime.CompilerServices", "FixedBufferAttribute");
1728 CompilerGenerated = new PredefinedAttribute (module, "System.Runtime.CompilerServices", "CompilerGeneratedAttribute");
1729 InternalsVisibleTo = new PredefinedAttribute (module, "System.Runtime.CompilerServices", "InternalsVisibleToAttribute");
1730 RuntimeCompatibility = new PredefinedAttribute (module, "System.Runtime.CompilerServices", "RuntimeCompatibilityAttribute");
1731 DebuggerHidden = new PredefinedAttribute (module, "System.Diagnostics", "DebuggerHiddenAttribute");
1732 UnsafeValueType = new PredefinedAttribute (module, "System.Runtime.CompilerServices", "UnsafeValueTypeAttribute");
1733 UnmanagedFunctionPointer = new PredefinedAttribute (module, "System.Runtime.InteropServices", "UnmanagedFunctionPointerAttribute");
1734 DebuggerBrowsable = new PredefinedDebuggerBrowsableAttribute (module, "System.Diagnostics", "DebuggerBrowsableAttribute");
1735 DebuggerStepThrough = new PredefinedAttribute (module, "System.Diagnostics", "DebuggerStepThroughAttribute");
1736 Debuggable = new PredefinedDebuggableAttribute (module, "System.Diagnostics", "DebuggableAttribute");
1738 Extension = new PredefinedAttribute (module, "System.Runtime.CompilerServices", "ExtensionAttribute");
1740 Dynamic = new PredefinedDynamicAttribute (module, "System.Runtime.CompilerServices", "DynamicAttribute");
1742 DefaultMember = new PredefinedAttribute (module, "System.Reflection", "DefaultMemberAttribute");
1743 DecimalConstant = new PredefinedDecimalAttribute (module, "System.Runtime.CompilerServices", "DecimalConstantAttribute");
1744 StructLayout = new PredefinedAttribute (module, "System.Runtime.InteropServices", "StructLayoutAttribute");
1745 FieldOffset = new PredefinedAttribute (module, "System.Runtime.InteropServices", "FieldOffsetAttribute");
1746 AssemblyProduct = new PredefinedAttribute (module, "System.Reflection", "AssemblyProductAttribute");
1747 AssemblyCompany = new PredefinedAttribute (module, "System.Reflection", "AssemblyCompanyAttribute");
1748 AssemblyDescription = new PredefinedAttribute (module, "System.Reflection", "AssemblyDescriptionAttribute");
1749 AssemblyCopyright = new PredefinedAttribute (module, "System.Reflection", "AssemblyCopyrightAttribute");
1750 AssemblyTrademark = new PredefinedAttribute (module, "System.Reflection", "AssemblyTrademarkAttribute");
1752 AsyncStateMachine = new PredefinedStateMachineAttribute (module, "System.Runtime.CompilerServices", "AsyncStateMachineAttribute");
1754 CallerMemberNameAttribute = new PredefinedAttribute (module, "System.Runtime.CompilerServices", "CallerMemberNameAttribute");
1755 CallerLineNumberAttribute = new PredefinedAttribute (module, "System.Runtime.CompilerServices", "CallerLineNumberAttribute");
1756 CallerFilePathAttribute = new PredefinedAttribute (module, "System.Runtime.CompilerServices", "CallerFilePathAttribute");
1758 // TODO: Should define only attributes which are used for comparison
1759 const System.Reflection.BindingFlags all_fields = System.Reflection.BindingFlags.Public |
1760 System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.DeclaredOnly;
1762 foreach (var fi in GetType ().GetFields (all_fields)) {
1763 ((PredefinedAttribute) fi.GetValue (this)).Define ();
1768 public class PredefinedAttribute : PredefinedType
1770 protected MethodSpec ctor;
1772 public PredefinedAttribute (ModuleContainer module, string ns, string name)
1773 : base (module, MemberKind.Class, ns, name)
1779 public MethodSpec Constructor {
1787 public static bool operator == (TypeSpec type, PredefinedAttribute pa)
1789 return type == pa.type && pa.type != null;
1792 public static bool operator != (TypeSpec type, PredefinedAttribute pa)
1794 return type != pa.type;
1797 public override int GetHashCode ()
1799 return base.GetHashCode ();
1802 public override bool Equals (object obj)
1804 throw new NotSupportedException ();
1807 public void EmitAttribute (ConstructorBuilder builder)
1809 if (ResolveBuilder ())
1810 builder.SetCustomAttribute (GetCtorMetaInfo (), AttributeEncoder.Empty);
1813 public void EmitAttribute (MethodBuilder builder)
1815 if (ResolveBuilder ())
1816 builder.SetCustomAttribute (GetCtorMetaInfo (), AttributeEncoder.Empty);
1819 public void EmitAttribute (PropertyBuilder builder)
1821 if (ResolveBuilder ())
1822 builder.SetCustomAttribute (GetCtorMetaInfo (), AttributeEncoder.Empty);
1825 public void EmitAttribute (FieldBuilder builder)
1827 if (ResolveBuilder ())
1828 builder.SetCustomAttribute (GetCtorMetaInfo (), AttributeEncoder.Empty);
1831 public void EmitAttribute (TypeBuilder builder)
1833 if (ResolveBuilder ())
1834 builder.SetCustomAttribute (GetCtorMetaInfo (), AttributeEncoder.Empty);
1837 public void EmitAttribute (AssemblyBuilder builder)
1839 if (ResolveBuilder ())
1840 builder.SetCustomAttribute (GetCtorMetaInfo (), AttributeEncoder.Empty);
1843 public void EmitAttribute (ModuleBuilder builder)
1845 if (ResolveBuilder ())
1846 builder.SetCustomAttribute (GetCtorMetaInfo (), AttributeEncoder.Empty);
1849 public void EmitAttribute (ParameterBuilder builder)
1851 if (ResolveBuilder ())
1852 builder.SetCustomAttribute (GetCtorMetaInfo (), AttributeEncoder.Empty);
1855 ConstructorInfo GetCtorMetaInfo ()
1857 return (ConstructorInfo) ctor.GetMetaInfo ();
1860 public bool ResolveBuilder ()
1866 // Handle all parameter-less attributes as optional
1871 ctor = (MethodSpec) MemberCache.FindMember (type, MemberFilter.Constructor (ParametersCompiled.EmptyReadOnlyParameters), BindingRestriction.DeclaredOnly);
1872 return ctor != null;
1876 public class PredefinedDebuggerBrowsableAttribute : PredefinedAttribute
1878 public PredefinedDebuggerBrowsableAttribute (ModuleContainer module, string ns, string name)
1879 : base (module, ns, name)
1883 public void EmitAttribute (FieldBuilder builder, System.Diagnostics.DebuggerBrowsableState state)
1885 var ctor = module.PredefinedMembers.DebuggerBrowsableAttributeCtor.Get ();
1889 AttributeEncoder encoder = new AttributeEncoder ();
1890 encoder.Encode ((int) state);
1891 encoder.EncodeEmptyNamedArguments ();
1893 builder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), encoder.ToArray ());
1897 public class PredefinedDebuggableAttribute : PredefinedAttribute
1899 public PredefinedDebuggableAttribute (ModuleContainer module, string ns, string name)
1900 : base (module, ns, name)
1904 public void EmitAttribute (AssemblyBuilder builder, System.Diagnostics.DebuggableAttribute.DebuggingModes modes)
1906 var atype = module.PredefinedAttributes.Debuggable;
1907 if (!atype.Define ())
1910 MethodSpec ctor = null;
1911 foreach (MethodSpec m in MemberCache.FindMembers (atype.TypeSpec, CSharp.Constructor.ConstructorName, true)) {
1912 if (m.Parameters.Count != 1)
1915 if (m.Parameters.Types[0].Kind == MemberKind.Enum) {
1923 AttributeEncoder encoder = new AttributeEncoder ();
1924 encoder.Encode ((int) modes);
1925 encoder.EncodeEmptyNamedArguments ();
1927 builder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), encoder.ToArray ());
1931 public class PredefinedDecimalAttribute : PredefinedAttribute
1933 public PredefinedDecimalAttribute (ModuleContainer module, string ns, string name)
1934 : base (module, ns, name)
1938 public void EmitAttribute (ParameterBuilder builder, decimal value, Location loc)
1940 var ctor = module.PredefinedMembers.DecimalConstantAttributeCtor.Resolve (loc);
1944 int[] bits = decimal.GetBits (value);
1945 AttributeEncoder encoder = new AttributeEncoder ();
1946 encoder.Encode ((byte) (bits[3] >> 16));
1947 encoder.Encode ((byte) (bits[3] >> 31));
1948 encoder.Encode ((uint) bits[2]);
1949 encoder.Encode ((uint) bits[1]);
1950 encoder.Encode ((uint) bits[0]);
1951 encoder.EncodeEmptyNamedArguments ();
1953 builder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), encoder.ToArray ());
1956 public void EmitAttribute (FieldBuilder builder, decimal value, Location loc)
1958 var ctor = module.PredefinedMembers.DecimalConstantAttributeCtor.Resolve (loc);
1962 int[] bits = decimal.GetBits (value);
1963 AttributeEncoder encoder = new AttributeEncoder ();
1964 encoder.Encode ((byte) (bits[3] >> 16));
1965 encoder.Encode ((byte) (bits[3] >> 31));
1966 encoder.Encode ((uint) bits[2]);
1967 encoder.Encode ((uint) bits[1]);
1968 encoder.Encode ((uint) bits[0]);
1969 encoder.EncodeEmptyNamedArguments ();
1971 builder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), encoder.ToArray ());
1975 public class PredefinedStateMachineAttribute : PredefinedAttribute
1977 public PredefinedStateMachineAttribute (ModuleContainer module, string ns, string name)
1978 : base (module, ns, name)
1982 public void EmitAttribute (MethodBuilder builder, StateMachine type)
1984 var predefined_ctor = module.PredefinedMembers.AsyncStateMachineAttributeCtor;
1986 var ctor = predefined_ctor.Get ();
1991 AttributeEncoder encoder = new AttributeEncoder ();
1992 encoder.EncodeTypeName (type);
1993 encoder.EncodeEmptyNamedArguments ();
1995 builder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), encoder.ToArray ());
1999 public class PredefinedDynamicAttribute : PredefinedAttribute
2003 public PredefinedDynamicAttribute (ModuleContainer module, string ns, string name)
2004 : base (module, ns, name)
2008 public void EmitAttribute (FieldBuilder builder, TypeSpec type, Location loc)
2010 if (ResolveTransformationCtor (loc)) {
2011 var cab = new CustomAttributeBuilder ((ConstructorInfo) tctor.GetMetaInfo (), new object[] { GetTransformationFlags (type) });
2012 builder.SetCustomAttribute (cab);
2016 public void EmitAttribute (ParameterBuilder builder, TypeSpec type, Location loc)
2018 if (ResolveTransformationCtor (loc)) {
2019 var cab = new CustomAttributeBuilder ((ConstructorInfo) tctor.GetMetaInfo (), new object[] { GetTransformationFlags (type) });
2020 builder.SetCustomAttribute (cab);
2024 public void EmitAttribute (PropertyBuilder builder, TypeSpec type, Location loc)
2026 if (ResolveTransformationCtor (loc)) {
2027 var cab = new CustomAttributeBuilder ((ConstructorInfo) tctor.GetMetaInfo (), new object[] { GetTransformationFlags (type) });
2028 builder.SetCustomAttribute (cab);
2032 public void EmitAttribute (TypeBuilder builder, TypeSpec type, Location loc)
2034 if (ResolveTransformationCtor (loc)) {
2035 var cab = new CustomAttributeBuilder ((ConstructorInfo) tctor.GetMetaInfo (), new object[] { GetTransformationFlags (type) });
2036 builder.SetCustomAttribute (cab);
2041 // When any element of the type is a dynamic type
2043 // This method builds a transformation array for dynamic types
2044 // used in places where DynamicAttribute cannot be applied to.
2045 // It uses bool flag when type is of dynamic type and each
2046 // section always starts with "false" for some reason.
2048 // LAMESPEC: This should be part of C# specification
2050 // Example: Func<dynamic, int, dynamic[]>
2051 // Transformation: { false, true, false, false, true }
2053 static bool[] GetTransformationFlags (TypeSpec t)
2056 var ac = t as ArrayContainer;
2058 element = GetTransformationFlags (ac.Element);
2059 if (element == null)
2060 return new bool[] { false, false };
2062 bool[] res = new bool[element.Length + 1];
2064 Array.Copy (element, 0, res, 1, element.Length);
2072 List<bool> transform = null;
2073 var targs = t.TypeArguments;
2074 for (int i = 0; i < targs.Length; ++i) {
2075 element = GetTransformationFlags (targs[i]);
2076 if (element != null) {
2077 if (transform == null) {
2078 transform = new List<bool> ();
2079 for (int ii = 0; ii <= i; ++ii)
2080 transform.Add (false);
2083 transform.AddRange (element);
2084 } else if (transform != null) {
2085 transform.Add (false);
2089 if (transform != null)
2090 return transform.ToArray ();
2093 if (t.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
2094 return new bool[] { true };
2099 bool ResolveTransformationCtor (Location loc)
2104 tctor = module.PredefinedMembers.DynamicAttributeCtor.Resolve (loc);
2105 return tctor != null;