2 // attribute.cs: Attribute Handler
4 // Author: Ravi Pratap (ravi@ximian.com)
5 // Marek Safar (marek.safar@seznam.cz)
7 // Dual licensed under the terms of the MIT X11 or GNU GPL
9 // Copyright 2001-2003 Ximian, Inc (http://www.ximian.com)
10 // Copyright 2003-2008 Novell, Inc.
14 using System.Collections.Generic;
15 using System.Runtime.InteropServices;
16 using System.Runtime.CompilerServices;
17 using System.Security;
18 using System.Security.Permissions;
23 using SecurityType = System.Collections.Generic.List<IKVM.Reflection.Emit.CustomAttributeBuilder>;
24 using IKVM.Reflection;
25 using IKVM.Reflection.Emit;
27 using SecurityType = System.Collections.Generic.Dictionary<System.Security.Permissions.SecurityAction, System.Security.PermissionSet>;
28 using System.Reflection;
29 using System.Reflection.Emit;
32 namespace Mono.CSharp {
35 /// Base class for objects that can have Attributes applied to them.
37 public abstract class Attributable {
39 // Holds all attributes attached to this element
41 protected Attributes attributes;
43 public void AddAttributes (Attributes attrs, IMemberContext context)
48 if (attributes == null)
51 throw new NotImplementedException ();
53 attributes.AttachTo (this, context);
56 public Attributes OptAttributes {
66 /// Use member-specific procedure to apply attribute @a in @cb to the entity being built in @builder
68 public abstract void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa);
71 /// Returns one AttributeTarget for this element.
73 public abstract AttributeTargets AttributeTargets { get; }
75 public abstract bool IsClsComplianceRequired ();
78 /// Gets list of valid attribute targets for explicit target declaration.
79 /// The first array item is default target. Don't break this rule.
81 public abstract string[] ValidAttributeTargets { get; }
84 public class Attribute : Expression
86 public readonly string ExplicitTarget;
87 public AttributeTargets Target;
88 readonly ATypeNameExpression expression;
90 Arguments PosArguments;
91 Arguments NamedArguments;
95 readonly bool nameEscaped;
98 // An attribute can be attached to multiple targets (e.g. multiple fields)
100 protected Attributable[] targets;
103 // A member context for the attribute, it's much easier to hold it here
104 // than trying to pull it during resolve
106 IMemberContext context;
108 public static readonly AttributeUsageAttribute DefaultUsageAttribute = new AttributeUsageAttribute (AttributeTargets.All);
109 static Assembly orig_sec_assembly;
110 public static readonly object[] EmptyObject = new object [0];
112 List<KeyValuePair<MemberExpr, NamedArgument>> named_values;
114 // Cache for parameter-less attributes
115 static Dictionary<TypeSpec, MethodSpec> att_cache;
117 public Attribute (string target, ATypeNameExpression expr, Arguments[] args, Location loc, bool nameEscaped)
119 this.expression = expr;
121 PosArguments = args [0];
122 NamedArguments = args [1];
125 ExplicitTarget = target;
126 this.nameEscaped = nameEscaped;
129 void AddModuleCharSet (ResolveContext rc)
131 const string dll_import_char_set = "CharSet";
134 // Only when not customized by user
136 if (HasField (dll_import_char_set))
139 if (!rc.Module.PredefinedTypes.CharSet.IsDefined) {
143 if (NamedArguments == null)
144 NamedArguments = new Arguments (1);
146 var value = Constant.CreateConstant (rc, rc.Module.PredefinedTypes.CharSet.TypeSpec, rc.Module.DefaultCharSet, Location);
147 NamedArguments.Add (new NamedArgument (dll_import_char_set, loc, value));
150 public Attribute Clone ()
152 Attribute a = new Attribute (ExplicitTarget, expression, null, loc, nameEscaped);
153 a.PosArguments = PosArguments;
154 a.NamedArguments = NamedArguments;
163 public static void Reset ()
165 att_cache = new Dictionary<TypeSpec, MethodSpec> ();
169 // When the same attribute is attached to multiple fiels
170 // we use @target field as a list of targets. The attribute
171 // has to be resolved only once but emitted for each target.
173 public void AttachTo (Attributable target, IMemberContext context)
175 if (this.targets == null) {
176 this.targets = new Attributable[] { target };
177 this.context = context;
181 // Resize target array
182 Attributable[] new_array = new Attributable [this.targets.Length + 1];
183 targets.CopyTo (new_array, 0);
184 new_array [targets.Length] = target;
185 this.targets = new_array;
187 // No need to update context, different targets cannot have
188 // different contexts, it's enough to remove same attributes
189 // from secondary members.
191 target.OptAttributes = null;
194 public ResolveContext CreateResolveContext ()
196 return new ResolveContext (context, ResolveContext.Options.ConstantScope);
199 static void Error_InvalidNamedArgument (ResolveContext rc, NamedArgument name)
201 rc.Report.Error (617, name.Location, "`{0}' is not a valid named attribute argument. Named attribute arguments " +
202 "must be fields which are not readonly, static, const or read-write properties which are " +
203 "public and not static",
207 static void Error_InvalidNamedArgumentType (ResolveContext rc, NamedArgument name)
209 rc.Report.Error (655, name.Location,
210 "`{0}' is not a valid named attribute argument because it is not a valid attribute parameter type",
214 public static void Error_AttributeArgumentIsDynamic (IMemberContext context, Location loc)
216 context.Module.Compiler.Report.Error (1982, loc, "An attribute argument cannot be dynamic expression");
219 public void Error_MissingGuidAttribute ()
221 Report.Error (596, Location, "The Guid attribute must be specified with the ComImport attribute");
224 public void Error_MisusedExtensionAttribute ()
226 Report.Error (1112, Location, "Do not use `{0}' directly. Use parameter modifier `this' instead", GetSignatureForError ());
229 public void Error_MisusedDynamicAttribute ()
231 Report.Error (1970, loc, "Do not use `{0}' directly. Use `dynamic' keyword instead", GetSignatureForError ());
235 /// This is rather hack. We report many emit attribute error with same error to be compatible with
236 /// csc. But because csc has to report them this way because error came from ilasm we needn't.
238 public void Error_AttributeEmitError (string inner)
240 Report.Error (647, Location, "Error during emitting `{0}' attribute. The reason is `{1}'",
241 TypeManager.CSharpName (Type), inner);
244 public void Error_InvalidSecurityParent ()
246 Error_AttributeEmitError ("it is attached to invalid parent");
255 protected virtual TypeExpr ResolveAsTypeTerminal (Expression expr, IMemberContext ec)
257 return expr.ResolveAsTypeTerminal (ec, false);
260 TypeSpec ResolvePossibleAttributeType (ATypeNameExpression expr, ref bool is_attr)
262 TypeExpr te = ResolveAsTypeTerminal (expr, context);
266 TypeSpec t = te.Type;
270 Report.SymbolRelatedToPreviousError (t);
271 Report.Error (616, Location, "`{0}': is not an attribute class", TypeManager.CSharpName (t));
277 /// Tries to resolve the type of the attribute. Flags an error if it can't, and complain is true.
279 void ResolveAttributeType ()
281 SessionReportPrinter resolve_printer = new SessionReportPrinter ();
282 ReportPrinter prev_recorder = context.Module.Compiler.Report.SetPrinter (resolve_printer);
284 bool t1_is_attr = false;
285 bool t2_is_attr = false;
287 ATypeNameExpression expanded = null;
290 t1 = ResolvePossibleAttributeType (expression, ref t1_is_attr);
295 expanded = (ATypeNameExpression) expression.Clone (null);
296 expanded.Name += "Attribute";
298 t2 = ResolvePossibleAttributeType (expanded, ref t2_is_attr);
301 resolve_printer.EndSession ();
303 context.Module.Compiler.Report.SetPrinter (prev_recorder);
306 if (t1_is_attr && t2_is_attr) {
307 Report.Error (1614, Location, "`{0}' is ambiguous between `{1}' and `{2}'. Use either `@{0}' or `{0}Attribute'",
308 GetSignatureForError (), expression.GetSignatureForError (), expanded.GetSignatureForError ());
309 resolve_error = true;
323 resolve_printer.Merge (prev_recorder);
324 resolve_error = true;
327 public virtual TypeSpec ResolveType ()
329 if (Type == null && !resolve_error)
330 ResolveAttributeType ();
334 public override string GetSignatureForError ()
337 return TypeManager.CSharpName (Type);
339 return expression.GetSignatureForError ();
342 public bool HasSecurityAttribute {
344 PredefinedAttribute pa = context.Module.PredefinedAttributes.Security;
345 return pa.IsDefined && TypeSpec.IsBaseClass (type, pa.TypeSpec, false);
349 public bool IsValidSecurityAttribute ()
351 return HasSecurityAttribute && IsSecurityActionValid (false);
354 static bool IsValidArgumentType (TypeSpec t)
357 t = TypeManager.GetElementType (t);
359 return t == TypeManager.string_type ||
360 TypeManager.IsPrimitiveType (t) ||
361 TypeManager.IsEnumType (t) ||
362 t == TypeManager.object_type ||
363 t == TypeManager.type_type;
366 // TODO: Don't use this ambiguous value
368 get { return expression.Name; }
371 public Report Report {
372 get { return context.Module.Compiler.Report; }
375 public MethodSpec Resolve ()
380 resolve_error = true;
384 ResolveAttributeType ();
389 if (Type.IsAbstract) {
390 Report.Error (653, Location, "Cannot apply attribute class `{0}' because it is abstract", GetSignatureForError ());
394 ObsoleteAttribute obsolete_attr = Type.GetAttributeObsolete ();
395 if (obsolete_attr != null) {
396 AttributeTester.Report_ObsoleteMessage (obsolete_attr, TypeManager.CSharpName (Type), Location, Report);
400 // Try if the attribute is simple has been resolved before
401 if (PosArguments == null && NamedArguments == null) {
402 if (att_cache.TryGetValue (Type, out ctor)) {
403 resolve_error = false;
408 ResolveContext rc = CreateResolveContext ();
409 ctor = ResolveConstructor (rc);
415 // Add [module: DefaultCharSet] to all DllImport import attributes
417 var module = context.Module;
418 if (Type == module.PredefinedAttributes.DllImport && module.HasDefaultCharSet) {
419 AddModuleCharSet (rc);
422 if (NamedArguments != null && !ResolveNamedArguments (rc)) {
426 resolve_error = false;
430 protected virtual MethodSpec ResolveConstructor (ResolveContext ec)
432 if (PosArguments != null) {
434 PosArguments.Resolve (ec, out dynamic);
436 Error_AttributeArgumentIsDynamic (ec.MemberContext, loc);
441 return ConstructorLookup (ec, Type, ref PosArguments, loc);
444 protected virtual bool ResolveNamedArguments (ResolveContext ec)
446 int named_arg_count = NamedArguments.Count;
447 var seen_names = new List<string> (named_arg_count);
449 named_values = new List<KeyValuePair<MemberExpr, NamedArgument>> (named_arg_count);
451 foreach (NamedArgument a in NamedArguments) {
452 string name = a.Name;
453 if (seen_names.Contains (name)) {
454 ec.Report.Error (643, a.Location, "Duplicate named attribute `{0}' argument", name);
458 seen_names.Add (name);
462 Expression member = Expression.MemberLookup (ec, ec.CurrentType, Type, name, 0, MemberLookupRestrictions.ExactArity, loc);
464 if (member == null) {
465 member = Expression.MemberLookup (null, ec.CurrentType, Type, name, 0, MemberLookupRestrictions.ExactArity, loc);
467 if (member != null) {
468 // TODO: ec.Report.SymbolRelatedToPreviousError (member);
469 Expression.ErrorIsInaccesible (ec, member.GetSignatureForError (), loc);
475 Expression.Error_TypeDoesNotContainDefinition (ec, Location, Type, name);
479 if (!(member is PropertyExpr || member is FieldExpr)) {
480 Error_InvalidNamedArgument (ec, a);
484 ObsoleteAttribute obsolete_attr;
486 if (member is PropertyExpr) {
487 var pi = ((PropertyExpr) member).PropertyInfo;
489 if (!pi.HasSet || !pi.HasGet || pi.IsStatic || !pi.Get.IsPublic || !pi.Set.IsPublic) {
490 ec.Report.SymbolRelatedToPreviousError (pi);
491 Error_InvalidNamedArgument (ec, a);
495 if (!IsValidArgumentType (member.Type)) {
496 ec.Report.SymbolRelatedToPreviousError (pi);
497 Error_InvalidNamedArgumentType (ec, a);
501 obsolete_attr = pi.GetAttributeObsolete ();
502 pi.MemberDefinition.SetIsAssigned ();
504 var fi = ((FieldExpr) member).Spec;
506 if (fi.IsReadOnly || fi.IsStatic || !fi.IsPublic) {
507 Error_InvalidNamedArgument (ec, a);
511 if (!IsValidArgumentType (member.Type)) {
512 ec.Report.SymbolRelatedToPreviousError (fi);
513 Error_InvalidNamedArgumentType (ec, a);
517 obsolete_attr = fi.GetAttributeObsolete ();
518 fi.MemberDefinition.SetIsAssigned ();
521 if (obsolete_attr != null && !context.IsObsolete)
522 AttributeTester.Report_ObsoleteMessage (obsolete_attr, member.GetSignatureForError (), member.Location, Report);
524 if (a.Type != member.Type) {
525 a.Expr = Convert.ImplicitConversionRequired (ec, a.Expr, member.Type, a.Expr.Location);
529 named_values.Add (new KeyValuePair<MemberExpr, NamedArgument> ((MemberExpr) member, a));
536 /// Get a string containing a list of valid targets for the attribute 'attr'
538 public string GetValidTargets ()
540 StringBuilder sb = new StringBuilder ();
541 AttributeTargets targets = Type.GetAttributeUsage (context.Module.PredefinedAttributes.AttributeUsage).ValidOn;
543 if ((targets & AttributeTargets.Assembly) != 0)
544 sb.Append ("assembly, ");
546 if ((targets & AttributeTargets.Module) != 0)
547 sb.Append ("module, ");
549 if ((targets & AttributeTargets.Class) != 0)
550 sb.Append ("class, ");
552 if ((targets & AttributeTargets.Struct) != 0)
553 sb.Append ("struct, ");
555 if ((targets & AttributeTargets.Enum) != 0)
556 sb.Append ("enum, ");
558 if ((targets & AttributeTargets.Constructor) != 0)
559 sb.Append ("constructor, ");
561 if ((targets & AttributeTargets.Method) != 0)
562 sb.Append ("method, ");
564 if ((targets & AttributeTargets.Property) != 0)
565 sb.Append ("property, indexer, ");
567 if ((targets & AttributeTargets.Field) != 0)
568 sb.Append ("field, ");
570 if ((targets & AttributeTargets.Event) != 0)
571 sb.Append ("event, ");
573 if ((targets & AttributeTargets.Interface) != 0)
574 sb.Append ("interface, ");
576 if ((targets & AttributeTargets.Parameter) != 0)
577 sb.Append ("parameter, ");
579 if ((targets & AttributeTargets.Delegate) != 0)
580 sb.Append ("delegate, ");
582 if ((targets & AttributeTargets.ReturnValue) != 0)
583 sb.Append ("return, ");
585 if ((targets & AttributeTargets.GenericParameter) != 0)
586 sb.Append ("type parameter, ");
588 return sb.Remove (sb.Length - 2, 2).ToString ();
591 public AttributeUsageAttribute GetAttributeUsageAttribute ()
594 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
595 // But because a lot of attribute class code must be rewritten will be better to wait...
599 return DefaultUsageAttribute;
601 AttributeUsageAttribute usage_attribute = new AttributeUsageAttribute ((AttributeTargets)((Constant) PosArguments [0].Expr).GetValue ());
603 var field = GetNamedValue ("AllowMultiple") as BoolConstant;
605 usage_attribute.AllowMultiple = field.Value;
607 field = GetNamedValue ("Inherited") as BoolConstant;
609 usage_attribute.Inherited = field.Value;
611 return usage_attribute;
615 /// Returns custom name of indexer
617 public string GetIndexerAttributeValue ()
620 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
621 // But because a lot of attribute class code must be rewritten will be better to wait...
627 return ((Constant) PosArguments [0].Expr).GetValue () as string;
631 /// Returns condition of ConditionalAttribute
633 public string GetConditionalAttributeValue ()
636 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
637 // But because a lot of attribute class code must be rewritten will be better to wait...
643 return ((Constant) PosArguments[0].Expr).GetValue () as string;
647 /// Creates the instance of ObsoleteAttribute from this attribute instance
649 public ObsoleteAttribute GetObsoleteAttribute ()
652 // corlib only case when obsolete is used before is resolved
653 var c = type.MemberDefinition as Class;
654 if (c != null && !c.HasMembersDefined)
657 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
658 // But because a lot of attribute class code must be rewritten will be better to wait...
665 if (PosArguments == null)
666 return new ObsoleteAttribute ();
668 string msg = ((Constant) PosArguments[0].Expr).GetValue () as string;
669 if (PosArguments.Count == 1)
670 return new ObsoleteAttribute (msg);
672 return new ObsoleteAttribute (msg, ((BoolConstant) PosArguments[1].Expr).Value);
676 /// Returns value of CLSCompliantAttribute contructor parameter but because the method can be called
677 /// before ApplyAttribute. We need to resolve the arguments.
678 /// This situation occurs when class deps is differs from Emit order.
680 public bool GetClsCompliantAttributeValue ()
683 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
684 // But because a lot of attribute class code must be rewritten will be better to wait...
690 return ((BoolConstant) PosArguments[0].Expr).Value;
693 public TypeSpec GetCoClassAttributeValue ()
701 return GetArgumentType ();
704 public bool CheckTarget ()
706 string[] valid_targets = Owner.ValidAttributeTargets;
707 if (ExplicitTarget == null || ExplicitTarget == valid_targets [0]) {
708 Target = Owner.AttributeTargets;
712 // TODO: we can skip the first item
713 if (Array.Exists (valid_targets, i => i == ExplicitTarget)) {
714 switch (ExplicitTarget) {
715 case "return": Target = AttributeTargets.ReturnValue; return true;
716 case "param": Target = AttributeTargets.Parameter; return true;
717 case "field": Target = AttributeTargets.Field; return true;
718 case "method": Target = AttributeTargets.Method; return true;
719 case "property": Target = AttributeTargets.Property; return true;
720 case "module": Target = AttributeTargets.Module; return true;
722 throw new InternalErrorException ("Unknown explicit target: " + ExplicitTarget);
725 StringBuilder sb = new StringBuilder ();
726 foreach (string s in valid_targets) {
730 sb.Remove (sb.Length - 2, 2);
731 Report.Error (657, Location, "`{0}' is not a valid attribute location for this declaration. " +
732 "Valid attribute locations for this declaration are `{1}'", ExplicitTarget, sb.ToString ());
737 /// Tests permitted SecurityAction for assembly or other types
739 protected virtual bool IsSecurityActionValid (bool for_assembly)
741 SecurityAction action = GetSecurityActionValue ();
744 #pragma warning disable 618
745 case SecurityAction.Demand:
746 case SecurityAction.Assert:
747 case SecurityAction.Deny:
748 case SecurityAction.PermitOnly:
749 case SecurityAction.LinkDemand:
750 case SecurityAction.InheritanceDemand:
755 case SecurityAction.RequestMinimum:
756 case SecurityAction.RequestOptional:
757 case SecurityAction.RequestRefuse:
761 #pragma warning restore 618
764 Error_AttributeEmitError ("SecurityAction is out of range");
768 Error_AttributeEmitError (String.Concat ("SecurityAction `", action, "' is not valid for this declaration"));
772 System.Security.Permissions.SecurityAction GetSecurityActionValue ()
774 return (SecurityAction) ((Constant) PosArguments[0].Expr).GetValue ();
778 /// Creates instance of SecurityAttribute class and add result of CreatePermission method to permission table.
780 /// <returns></returns>
781 public void ExtractSecurityPermissionSet (MethodSpec ctor, ref SecurityType permissions)
784 object[] values = new object [PosArguments.Count];
785 for (int i = 0; i < values.Length; ++i)
786 values [i] = ((Constant) PosArguments [i].Expr).GetValue ();
789 object[] prop_values;
790 if (named_values == null) {
794 prop = new PropertyInfo[named_values.Count];
795 prop_values = new object [named_values.Count];
796 for (int i = 0; i < prop.Length; ++i) {
797 prop [i] = ((PropertyExpr) named_values [i].Key).PropertyInfo.MetaInfo;
798 prop_values [i] = ((Constant) named_values [i].Value.Expr).GetValue ();
802 if (permissions == null)
803 permissions = new SecurityType ();
805 var cab = new CustomAttributeBuilder ((ConstructorInfo) ctor.GetMetaInfo (), values, prop, prop_values);
806 permissions.Add (cab);
808 throw new NotSupportedException ();
812 public Constant GetNamedValue (string name)
814 if (named_values == null)
817 for (int i = 0; i < named_values.Count; ++i) {
818 if (named_values [i].Value.Name == name)
819 return named_values [i].Value.Expr as Constant;
825 public CharSet GetCharSetValue ()
827 return (CharSet)System.Enum.Parse (typeof (CharSet), ((Constant) PosArguments [0].Expr).GetValue ().ToString ());
830 public bool HasField (string fieldName)
832 if (named_values == null)
835 foreach (var na in named_values) {
836 if (na.Value.Name == fieldName)
844 // Returns true for MethodImplAttribute with MethodImplOptions.InternalCall value
846 public bool IsInternalCall ()
848 MethodImplOptions options = 0;
849 if (PosArguments.Count == 1) {
850 options = (MethodImplOptions) System.Enum.Parse (typeof (MethodImplOptions), ((Constant) PosArguments[0].Expr).GetValue ().ToString ());
851 } else if (HasField ("Value")) {
852 var named = GetNamedValue ("Value");
853 options = (MethodImplOptions) System.Enum.Parse (typeof (MethodImplOptions), named.GetValue ().ToString ());
856 return (options & MethodImplOptions.InternalCall) != 0;
860 // Returns true for StructLayoutAttribute with LayoutKind.Explicit value
862 public bool IsExplicitLayoutKind ()
864 if (PosArguments == null || PosArguments.Count != 1)
867 var value = (LayoutKind) System.Enum.Parse (typeof (LayoutKind), ((Constant) PosArguments[0].Expr).GetValue ().ToString ());
868 return value == LayoutKind.Explicit;
871 public Expression GetParameterDefaultValue ()
873 if (PosArguments == null)
876 return PosArguments[0].Expr;
879 public override bool Equals (object obj)
881 Attribute a = obj as Attribute;
885 return Type == a.Type && Target == a.Target;
888 public override int GetHashCode ()
890 return type.GetHashCode () ^ Target.GetHashCode ();
894 /// Emit attribute for Attributable symbol
896 public void Emit (Dictionary<Attribute, List<Attribute>> allEmitted)
898 var ctor = Resolve ();
902 var predefined = context.Module.PredefinedAttributes;
904 AttributeUsageAttribute usage_attr = Type.GetAttributeUsage (predefined.AttributeUsage);
905 if ((usage_attr.ValidOn & Target) == 0) {
906 Report.Error (592, Location, "The attribute `{0}' is not valid on this declaration type. " +
907 "It is valid on `{1}' declarations only",
908 GetSignatureForError (), GetValidTargets ());
913 if (PosArguments == null && named_values == null) {
914 cdata = AttributeEncoder.Empty;
916 AttributeEncoder encoder = new AttributeEncoder ();
918 if (PosArguments != null) {
919 var param_types = ctor.Parameters.Types;
920 for (int j = 0; j < PosArguments.Count; ++j) {
921 var pt = param_types[j];
922 var arg_expr = PosArguments[j].Expr;
924 if (Type == predefined.IndexerName || Type == predefined.Conditional) {
925 string v = ((StringConstant) arg_expr).Value;
926 if (!Tokenizer.IsValidIdentifier (v) || Tokenizer.IsKeyword (v)) {
927 context.Module.Compiler.Report.Error (633, arg_expr.Location,
928 "The argument to the `{0}' attribute must be a valid identifier", GetSignatureForError ());
930 } else if (Type == predefined.Guid) {
932 string v = ((StringConstant) arg_expr).Value;
934 } catch (Exception e) {
935 Error_AttributeEmitError (e.Message);
938 } else if (Type == predefined.AttributeUsage) {
939 int v = ((IntConstant) ((EnumConstant) arg_expr).Child).Value;
941 context.Module.Compiler.Report.Error (591, Location, "Invalid value for argument to `{0}' attribute",
942 "System.AttributeUsage");
944 } else if (Type == predefined.MarshalAs) {
945 if (PosArguments.Count == 1) {
946 var u_type = (UnmanagedType) System.Enum.Parse (typeof (UnmanagedType), ((Constant) PosArguments[0].Expr).GetValue ().ToString ());
947 if (u_type == UnmanagedType.ByValArray && !(Owner is FieldBase)) {
948 Error_AttributeEmitError ("Specified unmanaged type is only valid on fields");
951 } else if (Type == predefined.DllImport) {
952 if (PosArguments.Count == 1) {
953 var value = ((Constant) PosArguments[0].Expr).GetValue () as string;
954 if (string.IsNullOrEmpty (value))
955 Error_AttributeEmitError ("DllName cannot be empty");
957 } else if (Type == predefined.MethodImpl && pt == TypeManager.short_type &&
958 !System.Enum.IsDefined (typeof (MethodImplOptions), ((Constant) arg_expr).GetValue ().ToString ())) {
959 Error_AttributeEmitError ("Incorrect argument value.");
964 arg_expr.EncodeAttributeValue (context, encoder, pt);
968 if (named_values != null) {
969 encoder.Encode ((ushort) named_values.Count);
970 foreach (var na in named_values) {
971 if (na.Key is FieldExpr)
972 encoder.Encode ((byte) 0x53);
974 encoder.Encode ((byte) 0x54);
976 encoder.Encode (na.Key.Type);
977 encoder.Encode (na.Value.Name);
978 na.Value.Expr.EncodeAttributeValue (context, encoder, na.Key.Type);
981 encoder.EncodeEmptyNamedArguments ();
984 cdata = encoder.ToArray ();
988 foreach (Attributable target in targets)
989 target.ApplyAttributeBuilder (this, ctor, cdata, predefined);
990 } catch (Exception e) {
991 Error_AttributeEmitError (e.Message);
995 if (!usage_attr.AllowMultiple && allEmitted != null) {
996 if (allEmitted.ContainsKey (this)) {
997 var a = allEmitted [this];
999 a = new List<Attribute> (2);
1000 allEmitted [this] = a;
1004 allEmitted.Add (this, null);
1008 if (!context.Module.Compiler.Settings.VerifyClsCompliance)
1011 // Here we are testing attribute arguments for array usage (error 3016)
1012 if (Owner.IsClsComplianceRequired ()) {
1013 if (PosArguments != null)
1014 PosArguments.CheckArrayAsAttribute (context.Module.Compiler);
1016 if (NamedArguments == null)
1019 NamedArguments.CheckArrayAsAttribute (context.Module.Compiler);
1023 private Expression GetValue ()
1025 if (PosArguments == null || PosArguments.Count < 1)
1028 return PosArguments [0].Expr;
1031 public string GetString ()
1033 Expression e = GetValue ();
1034 if (e is StringConstant)
1035 return ((StringConstant)e).Value;
1039 public bool GetBoolean ()
1041 Expression e = GetValue ();
1042 if (e is BoolConstant)
1043 return ((BoolConstant)e).Value;
1047 public TypeSpec GetArgumentType ()
1049 TypeOf e = GetValue () as TypeOf;
1052 return e.TypeArgument;
1055 public override Expression CreateExpressionTree (ResolveContext ec)
1057 throw new NotSupportedException ("ET");
1060 protected override Expression DoResolve (ResolveContext ec)
1062 throw new NotImplementedException ();
1065 public override void Emit (EmitContext ec)
1067 throw new NotImplementedException ();
1073 /// For global attributes (assembly, module) we need special handling.
1074 /// Attributes can be located in the several files
1076 public class GlobalAttribute : Attribute
1078 public readonly NamespaceEntry ns;
1080 public GlobalAttribute (NamespaceEntry ns, string target, ATypeNameExpression expression,
1081 Arguments[] args, Location loc, bool nameEscaped):
1082 base (target, expression, args, loc, nameEscaped)
1089 // RootContext.ToplevelTypes has a single NamespaceEntry which gets overwritten
1090 // each time a new file is parsed. However, we need to use the NamespaceEntry
1091 // in effect where the attribute was used. Since code elsewhere cannot assume
1092 // that the NamespaceEntry is right, just overwrite it.
1094 // Precondition: RootContext.ToplevelTypes == null
1096 if (RootContext.ToplevelTypes.NamespaceEntry != null)
1097 throw new InternalErrorException (Location + " non-null NamespaceEntry");
1099 RootContext.ToplevelTypes.NamespaceEntry = ns;
1102 protected override bool IsSecurityActionValid (bool for_assembly)
1104 return base.IsSecurityActionValid (true);
1109 RootContext.ToplevelTypes.NamespaceEntry = null;
1112 protected override TypeExpr ResolveAsTypeTerminal (Expression expr, IMemberContext ec)
1116 return base.ResolveAsTypeTerminal (expr, ec);
1123 protected override MethodSpec ResolveConstructor (ResolveContext ec)
1127 return base.ResolveConstructor (ec);
1134 protected override bool ResolveNamedArguments (ResolveContext ec)
1138 return base.ResolveNamedArguments (ec);
1146 public class Attributes {
1147 public readonly List<Attribute> Attrs;
1149 public Attributes (Attribute a)
1151 Attrs = new List<Attribute> ();
1155 public Attributes (List<Attribute> attrs)
1160 public void AddAttributes (List<Attribute> attrs)
1162 Attrs.AddRange (attrs);
1165 public void AttachTo (Attributable attributable, IMemberContext context)
1167 foreach (Attribute a in Attrs)
1168 a.AttachTo (attributable, context);
1171 public Attributes Clone ()
1173 var al = new List<Attribute> (Attrs.Count);
1174 foreach (Attribute a in Attrs)
1175 al.Add (a.Clone ());
1177 return new Attributes (al);
1181 /// Checks whether attribute target is valid for the current element
1183 public bool CheckTargets ()
1185 foreach (Attribute a in Attrs) {
1186 if (!a.CheckTarget ())
1192 public Attribute Search (PredefinedAttribute t)
1194 return Search (null, t);
1197 public Attribute Search (string explicitTarget, PredefinedAttribute t)
1199 foreach (Attribute a in Attrs) {
1200 if (explicitTarget != null && a.ExplicitTarget != explicitTarget)
1203 if (a.ResolveType () == t)
1210 /// Returns all attributes of type 't'. Use it when attribute is AllowMultiple = true
1212 public Attribute[] SearchMulti (PredefinedAttribute t)
1214 List<Attribute> ar = null;
1216 foreach (Attribute a in Attrs) {
1217 if (a.ResolveType () == t) {
1219 ar = new List<Attribute> (Attrs.Count);
1224 return ar == null ? null : ar.ToArray ();
1231 Dictionary<Attribute, List<Attribute>> ld = Attrs.Count > 1 ? new Dictionary<Attribute, List<Attribute>> () : null;
1233 foreach (Attribute a in Attrs)
1236 if (ld == null || ld.Count == 0)
1239 foreach (var d in ld) {
1240 if (d.Value == null)
1243 Attribute a = d.Key;
1245 foreach (Attribute collision in d.Value)
1246 a.Report.SymbolRelatedToPreviousError (collision.Location, "");
1248 a.Report.Error (579, a.Location, "The attribute `{0}' cannot be applied multiple times",
1249 a.GetSignatureForError ());
1253 public bool Contains (PredefinedAttribute t)
1255 return Search (t) != null;
1259 public sealed class AttributeEncoder
1262 public enum EncodedTypeProperties
1266 TypeParameter = 1 << 1
1269 public static readonly byte[] Empty;
1273 const ushort Version = 1;
1275 static AttributeEncoder ()
1277 Empty = new byte[4];
1278 Empty[0] = (byte) Version;
1281 public AttributeEncoder ()
1283 buffer = new byte[32];
1287 public void Encode (bool value)
1289 Encode (value ? (byte) 1 : (byte) 0);
1292 public void Encode (byte value)
1294 if (pos == buffer.Length)
1297 buffer [pos++] = value;
1300 public void Encode (sbyte value)
1302 Encode ((byte) value);
1305 public void Encode (short value)
1307 if (pos + 2 > buffer.Length)
1310 buffer[pos++] = (byte) value;
1311 buffer[pos++] = (byte) (value >> 8);
1314 public void Encode (ushort value)
1316 Encode ((short) value);
1319 public void Encode (int value)
1321 if (pos + 4 > buffer.Length)
1324 buffer[pos++] = (byte) value;
1325 buffer[pos++] = (byte) (value >> 8);
1326 buffer[pos++] = (byte) (value >> 16);
1327 buffer[pos++] = (byte) (value >> 24);
1330 public void Encode (uint value)
1332 Encode ((int) value);
1335 public void Encode (long value)
1337 if (pos + 8 > buffer.Length)
1340 buffer[pos++] = (byte) value;
1341 buffer[pos++] = (byte) (value >> 8);
1342 buffer[pos++] = (byte) (value >> 16);
1343 buffer[pos++] = (byte) (value >> 24);
1344 buffer[pos++] = (byte) (value >> 32);
1345 buffer[pos++] = (byte) (value >> 40);
1346 buffer[pos++] = (byte) (value >> 48);
1347 buffer[pos++] = (byte) (value >> 56);
1350 public void Encode (ulong value)
1352 Encode ((long) value);
1355 public void Encode (float value)
1357 Encode (SingleConverter.SingleToInt32Bits (value));
1360 public void Encode (double value)
1362 Encode (BitConverter.DoubleToInt64Bits (value));
1365 public void Encode (string value)
1367 if (value == null) {
1368 Encode ((byte) 0xFF);
1372 var buf = Encoding.UTF8.GetBytes(value);
1373 WriteCompressedValue (buf.Length);
1375 if (pos + buf.Length > buffer.Length)
1378 Buffer.BlockCopy (buf, 0, buffer, pos, buf.Length);
1382 public EncodedTypeProperties Encode (TypeSpec type)
1384 switch (type.BuildinType) {
1385 case BuildinTypeSpec.Type.Bool:
1386 Encode ((byte) 0x02);
1388 case BuildinTypeSpec.Type.Char:
1389 Encode ((byte) 0x03);
1391 case BuildinTypeSpec.Type.SByte:
1392 Encode ((byte) 0x04);
1394 case BuildinTypeSpec.Type.Byte:
1395 Encode ((byte) 0x05);
1397 case BuildinTypeSpec.Type.Short:
1398 Encode ((byte) 0x06);
1400 case BuildinTypeSpec.Type.UShort:
1401 Encode ((byte) 0x07);
1403 case BuildinTypeSpec.Type.Int:
1404 Encode ((byte) 0x08);
1406 case BuildinTypeSpec.Type.UInt:
1407 Encode ((byte) 0x09);
1409 case BuildinTypeSpec.Type.Long:
1410 Encode ((byte) 0x0A);
1412 case BuildinTypeSpec.Type.ULong:
1413 Encode ((byte) 0x0B);
1415 case BuildinTypeSpec.Type.Float:
1416 Encode ((byte) 0x0C);
1418 case BuildinTypeSpec.Type.Double:
1419 Encode ((byte) 0x0D);
1421 case BuildinTypeSpec.Type.String:
1422 Encode ((byte) 0x0E);
1424 case BuildinTypeSpec.Type.Type:
1425 Encode ((byte) 0x50);
1427 case BuildinTypeSpec.Type.Object:
1428 Encode ((byte) 0x51);
1430 case BuildinTypeSpec.Type.Dynamic:
1431 Encode ((byte) 0x51);
1432 return EncodedTypeProperties.DynamicType;
1435 Encode ((byte) 0x1D);
1436 return Encode (TypeManager.GetElementType (type));
1439 if (type.Kind == MemberKind.Enum) {
1440 Encode ((byte) 0x55);
1441 EncodeTypeName (type);
1447 return EncodedTypeProperties.None;
1450 public void EncodeTypeName (TypeSpec type)
1452 var old_type = type.GetMetaInfo ();
1453 Encode (type.MemberDefinition.IsImported ? old_type.AssemblyQualifiedName : old_type.FullName);
1457 // Encodes single property named argument per call
1459 public void EncodeNamedPropertyArgument (PropertySpec property, Constant value)
1461 Encode ((ushort) 1); // length
1462 Encode ((byte) 0x54); // property
1463 Encode (property.MemberType);
1464 Encode (property.Name);
1465 value.EncodeAttributeValue (null, this, property.MemberType);
1469 // Encodes single field named argument per call
1471 public void EncodeNamedFieldArgument (FieldSpec field, Constant value)
1473 Encode ((ushort) 1); // length
1474 Encode ((byte) 0x53); // field
1475 Encode (field.MemberType);
1476 Encode (field.Name);
1477 value.EncodeAttributeValue (null, this, field.MemberType);
1480 public void EncodeNamedArguments<T> (T[] members, Constant[] values) where T : MemberSpec, IInterfaceMemberSpec
1482 Encode ((ushort) members.Length);
1484 for (int i = 0; i < members.Length; ++i)
1486 var member = members[i];
1488 if (member.Kind == MemberKind.Field)
1489 Encode ((byte) 0x53);
1490 else if (member.Kind == MemberKind.Property)
1491 Encode ((byte) 0x54);
1493 throw new NotImplementedException (member.Kind.ToString ());
1495 Encode (member.MemberType);
1496 Encode (member.Name);
1497 values [i].EncodeAttributeValue (null, this, member.MemberType);
1501 public void EncodeEmptyNamedArguments ()
1503 Encode ((ushort) 0);
1508 int size = System.Math.Max (pos * 4, pos + inc + 2);
1509 Array.Resize (ref buffer, size);
1512 void WriteCompressedValue (int value)
1515 Encode ((byte) value);
1519 if (value < 0x4000) {
1520 Encode ((byte) (0x80 | (value >> 8)));
1521 Encode ((byte) value);
1528 public byte[] ToArray ()
1530 byte[] buf = new byte[pos];
1531 Array.Copy (buffer, buf, pos);
1538 /// Helper class for attribute verification routine.
1540 static class AttributeTester
1542 public enum Result {
1549 /// Returns true if parameters of two compared methods are CLS-Compliant.
1550 /// It tests differing only in ref or out, or in array rank.
1552 public static Result AreOverloadedMethodParamsClsCompliant (AParametersCollection pa, AParametersCollection pb)
1554 TypeSpec [] types_a = pa.Types;
1555 TypeSpec [] types_b = pb.Types;
1556 if (types_a == null || types_b == null)
1559 if (types_a.Length != types_b.Length)
1562 Result result = Result.Ok;
1563 for (int i = 0; i < types_b.Length; ++i) {
1564 TypeSpec aType = types_a [i];
1565 TypeSpec bType = types_b [i];
1567 var ac_a = aType as ArrayContainer;
1568 var ac_b = aType as ArrayContainer;
1570 if (ac_a != null && ac_b != null) {
1571 if (ac_a.Rank != ac_b.Rank && ac_a.Element == ac_b.Element) {
1572 result = Result.RefOutArrayError;
1576 if (ac_a.Element.IsArray || ac_b.Element.IsArray) {
1577 result = Result.ArrayArrayError;
1585 const Parameter.Modifier out_ref_mod = (Parameter.Modifier.OUTMASK | Parameter.Modifier.REFMASK);
1586 if ((pa.FixedParameters[i].ModFlags & out_ref_mod) != (pb.FixedParameters[i].ModFlags & out_ref_mod))
1587 result = Result.RefOutArrayError;
1593 /// Common method for Obsolete error/warning reporting.
1595 public static void Report_ObsoleteMessage (ObsoleteAttribute oa, string member, Location loc, Report Report)
1598 Report.Error (619, loc, "`{0}' is obsolete: `{1}'", member, oa.Message);
1602 if (oa.Message == null || oa.Message.Length == 0) {
1603 Report.Warning (612, 1, loc, "`{0}' is obsolete", member);
1606 Report.Warning (618, 2, loc, "`{0}' is obsolete: `{1}'", member, oa.Message);
1611 // Predefined attribute types
1613 public class PredefinedAttributes
1615 // Build-in attributes
1616 public readonly PredefinedAttribute ParamArray;
1617 public readonly PredefinedAttribute Out;
1619 // Optional attributes
1620 public readonly PredefinedAttribute Obsolete;
1621 public readonly PredefinedAttribute DllImport;
1622 public readonly PredefinedAttribute MethodImpl;
1623 public readonly PredefinedAttribute MarshalAs;
1624 public readonly PredefinedAttribute In;
1625 public readonly PredefinedAttribute IndexerName;
1626 public readonly PredefinedAttribute Conditional;
1627 public readonly PredefinedAttribute CLSCompliant;
1628 public readonly PredefinedAttribute Security;
1629 public readonly PredefinedAttribute Required;
1630 public readonly PredefinedAttribute Guid;
1631 public readonly PredefinedAttribute AssemblyCulture;
1632 public readonly PredefinedAttribute AssemblyVersion;
1633 public readonly PredefinedAttribute AssemblyAlgorithmId;
1634 public readonly PredefinedAttribute AssemblyFlags;
1635 public readonly PredefinedAttribute AssemblyFileVersion;
1636 public readonly PredefinedAttribute ComImport;
1637 public readonly PredefinedAttribute CoClass;
1638 public readonly PredefinedAttribute AttributeUsage;
1639 public readonly PredefinedAttribute DefaultParameterValue;
1640 public readonly PredefinedAttribute OptionalParameter;
1641 public readonly PredefinedAttribute UnverifiableCode;
1644 public readonly PredefinedAttribute DefaultCharset;
1645 public readonly PredefinedAttribute TypeForwarder;
1646 public readonly PredefinedAttribute FixedBuffer;
1647 public readonly PredefinedAttribute CompilerGenerated;
1648 public readonly PredefinedAttribute InternalsVisibleTo;
1649 public readonly PredefinedAttribute RuntimeCompatibility;
1650 public readonly PredefinedAttribute DebuggerHidden;
1651 public readonly PredefinedAttribute UnsafeValueType;
1654 public readonly PredefinedAttribute Extension;
1657 public readonly PredefinedDynamicAttribute Dynamic;
1660 // Optional types which are used as types and for member lookup
1662 public readonly PredefinedAttribute DefaultMember;
1663 public readonly PredefinedDecimalAttribute DecimalConstant;
1664 public readonly PredefinedAttribute StructLayout;
1665 public readonly PredefinedAttribute FieldOffset;
1667 public PredefinedAttributes (ModuleContainer module)
1669 ParamArray = new PredefinedAttribute (module, "System", "ParamArrayAttribute");
1670 Out = new PredefinedAttribute (module, "System.Runtime.InteropServices", "OutAttribute");
1671 ParamArray.Resolve (Location.Null);
1672 Out.Resolve (Location.Null);
1674 Obsolete = new PredefinedAttribute (module, "System", "ObsoleteAttribute");
1675 DllImport = new PredefinedAttribute (module, "System.Runtime.InteropServices", "DllImportAttribute");
1676 MethodImpl = new PredefinedAttribute (module, "System.Runtime.CompilerServices", "MethodImplAttribute");
1677 MarshalAs = new PredefinedAttribute (module, "System.Runtime.InteropServices", "MarshalAsAttribute");
1678 In = new PredefinedAttribute (module, "System.Runtime.InteropServices", "InAttribute");
1679 IndexerName = new PredefinedAttribute (module, "System.Runtime.CompilerServices", "IndexerNameAttribute");
1680 Conditional = new PredefinedAttribute (module, "System.Diagnostics", "ConditionalAttribute");
1681 CLSCompliant = new PredefinedAttribute (module, "System", "CLSCompliantAttribute");
1682 Security = new PredefinedAttribute (module, "System.Security.Permissions", "SecurityAttribute");
1683 Required = new PredefinedAttribute (module, "System.Runtime.CompilerServices", "RequiredAttributeAttribute");
1684 Guid = new PredefinedAttribute (module, "System.Runtime.InteropServices", "GuidAttribute");
1685 AssemblyCulture = new PredefinedAttribute (module, "System.Reflection", "AssemblyCultureAttribute");
1686 AssemblyVersion = new PredefinedAttribute (module, "System.Reflection", "AssemblyVersionAttribute");
1687 AssemblyAlgorithmId = new PredefinedAttribute (module, "System.Reflection", "AssemblyAlgorithmIdAttribute");
1688 AssemblyFlags = new PredefinedAttribute (module, "System.Reflection", "AssemblyFlagsAttribute");
1689 AssemblyFileVersion = new PredefinedAttribute (module, "System.Reflection", "AssemblyFileVersionAttribute");
1690 ComImport = new PredefinedAttribute (module, "System.Runtime.InteropServices", "ComImportAttribute");
1691 CoClass = new PredefinedAttribute (module, "System.Runtime.InteropServices", "CoClassAttribute");
1692 AttributeUsage = new PredefinedAttribute (module, "System", "AttributeUsageAttribute");
1693 DefaultParameterValue = new PredefinedAttribute (module, "System.Runtime.InteropServices", "DefaultParameterValueAttribute");
1694 OptionalParameter = new PredefinedAttribute (module, "System.Runtime.InteropServices", "OptionalAttribute");
1695 UnverifiableCode = new PredefinedAttribute (module, "System.Security", "UnverifiableCodeAttribute");
1697 DefaultCharset = new PredefinedAttribute (module, "System.Runtime.InteropServices", "DefaultCharSetAttribute");
1698 TypeForwarder = new PredefinedAttribute (module, "System.Runtime.CompilerServices", "TypeForwardedToAttribute");
1699 FixedBuffer = new PredefinedAttribute (module, "System.Runtime.CompilerServices", "FixedBufferAttribute");
1700 CompilerGenerated = new PredefinedAttribute (module, "System.Runtime.CompilerServices", "CompilerGeneratedAttribute");
1701 InternalsVisibleTo = new PredefinedAttribute (module, "System.Runtime.CompilerServices", "InternalsVisibleToAttribute");
1702 RuntimeCompatibility = new PredefinedAttribute (module, "System.Runtime.CompilerServices", "RuntimeCompatibilityAttribute");
1703 DebuggerHidden = new PredefinedAttribute (module, "System.Diagnostics", "DebuggerHiddenAttribute");
1704 UnsafeValueType = new PredefinedAttribute (module, "System.Runtime.CompilerServices", "UnsafeValueTypeAttribute");
1706 Extension = new PredefinedAttribute (module, "System.Runtime.CompilerServices", "ExtensionAttribute");
1708 Dynamic = new PredefinedDynamicAttribute (module, "System.Runtime.CompilerServices", "DynamicAttribute");
1710 DefaultMember = new PredefinedAttribute (module, "System.Reflection", "DefaultMemberAttribute");
1711 DecimalConstant = new PredefinedDecimalAttribute (module, "System.Runtime.CompilerServices", "DecimalConstantAttribute");
1712 StructLayout = new PredefinedAttribute (module, "System.Runtime.InteropServices", "StructLayoutAttribute");
1713 FieldOffset = new PredefinedAttribute (module, "System.Runtime.InteropServices", "FieldOffsetAttribute");
1715 // TODO: Should define only attributes which are used for comparison
1716 const System.Reflection.BindingFlags all_fields = System.Reflection.BindingFlags.Public |
1717 System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.DeclaredOnly;
1719 foreach (var fi in GetType ().GetFields (all_fields)) {
1720 ((PredefinedAttribute) fi.GetValue (this)).Define ();
1725 public class PredefinedAttribute : PredefinedType
1727 protected MethodSpec ctor;
1728 List<PropertySpec> properties;
1730 public PredefinedAttribute (ModuleContainer module, string ns, string name)
1731 : base (module, MemberKind.Class, ns, name)
1737 public MethodSpec Constructor {
1745 public static bool operator == (TypeSpec type, PredefinedAttribute pa)
1747 return type == pa.type && pa.type != null;
1750 public static bool operator != (TypeSpec type, PredefinedAttribute pa)
1752 return type != pa.type;
1755 public override int GetHashCode ()
1757 return base.GetHashCode ();
1760 public override bool Equals (object obj)
1762 throw new NotSupportedException ();
1765 public void EmitAttribute (ConstructorBuilder builder)
1767 if (ResolveBuilder ())
1768 builder.SetCustomAttribute (GetCtorMetaInfo (), AttributeEncoder.Empty);
1771 public void EmitAttribute (MethodBuilder builder)
1773 if (ResolveBuilder ())
1774 builder.SetCustomAttribute (GetCtorMetaInfo (), AttributeEncoder.Empty);
1777 public void EmitAttribute (PropertyBuilder builder)
1779 if (ResolveBuilder ())
1780 builder.SetCustomAttribute (GetCtorMetaInfo (), AttributeEncoder.Empty);
1783 public void EmitAttribute (FieldBuilder builder)
1785 if (ResolveBuilder ())
1786 builder.SetCustomAttribute (GetCtorMetaInfo (), AttributeEncoder.Empty);
1789 public void EmitAttribute (FieldBuilder builder, AttributeEncoder argsEncoded)
1791 builder.SetCustomAttribute (GetCtorMetaInfo (), argsEncoded.ToArray ());
1794 public void EmitAttribute (TypeBuilder builder)
1796 if (ResolveBuilder ())
1797 builder.SetCustomAttribute (GetCtorMetaInfo (), AttributeEncoder.Empty);
1800 public void EmitAttribute (TypeBuilder builder, AttributeEncoder argsEncoded)
1802 builder.SetCustomAttribute (GetCtorMetaInfo (), argsEncoded.ToArray ());
1805 public void EmitAttribute (AssemblyBuilder builder)
1807 if (ResolveBuilder ())
1808 builder.SetCustomAttribute (GetCtorMetaInfo (), AttributeEncoder.Empty);
1811 public void EmitAttribute (ModuleBuilder builder)
1813 if (ResolveBuilder ())
1814 builder.SetCustomAttribute (GetCtorMetaInfo (), AttributeEncoder.Empty);
1817 public void EmitAttribute (ParameterBuilder builder)
1819 if (ResolveBuilder ())
1820 builder.SetCustomAttribute (GetCtorMetaInfo (), AttributeEncoder.Empty);
1823 public void EmitAttribute (ParameterBuilder builder, AttributeEncoder argsEncoded)
1825 builder.SetCustomAttribute (GetCtorMetaInfo (), argsEncoded.ToArray ());
1828 ConstructorInfo GetCtorMetaInfo ()
1830 return (ConstructorInfo) ctor.GetMetaInfo ();
1833 public PropertySpec GetProperty (string name, TypeSpec memberType, Location loc)
1837 if (properties != null) {
1838 spec = properties.Find (l => l.Name == name);
1844 spec = TypeManager.GetPredefinedProperty (type, name, loc, memberType);
1847 if (properties == null) {
1848 properties = new List<PropertySpec> ();
1851 properties.Add (spec);
1858 public bool ResolveBuilder ()
1864 // Handle all parameter-less attributes as optional
1869 ctor = TypeManager.GetPredefinedConstructor (type, Location.Null, TypeSpec.EmptyTypes);
1870 return ctor != null;
1873 public bool ResolveConstructor (Location loc, params TypeSpec[] argType)
1876 throw new InternalErrorException ("Predefined ctor redefined");
1878 if (Resolve (loc) == null)
1881 ctor = TypeManager.GetPredefinedConstructor (type, loc, argType);
1882 return ctor != null;
1886 public class PredefinedDecimalAttribute : PredefinedAttribute
1888 public PredefinedDecimalAttribute (ModuleContainer module, string ns, string name)
1889 : base (module, ns, name)
1893 public void EmitAttribute (ParameterBuilder builder, decimal value, Location loc)
1895 if (Resolve (loc) == null)
1898 if (ctor == null && !ResolveConstructor (loc, TypeManager.byte_type, TypeManager.byte_type, TypeManager.uint32_type, TypeManager.uint32_type, TypeManager.uint32_type))
1901 int[] bits = decimal.GetBits (value);
1902 AttributeEncoder encoder = new AttributeEncoder ();
1903 encoder.Encode ((byte) (bits[3] >> 16));
1904 encoder.Encode ((byte) (bits[3] >> 31));
1905 encoder.Encode ((uint) bits[2]);
1906 encoder.Encode ((uint) bits[1]);
1907 encoder.Encode ((uint) bits[0]);
1908 encoder.EncodeEmptyNamedArguments ();
1910 EmitAttribute (builder, encoder);
1913 public void EmitAttribute (FieldBuilder builder, decimal value, Location loc)
1915 if (Resolve (loc) == null)
1918 if (ctor == null && !ResolveConstructor (loc, TypeManager.byte_type, TypeManager.byte_type, TypeManager.uint32_type, TypeManager.uint32_type, TypeManager.uint32_type))
1921 int[] bits = decimal.GetBits (value);
1922 AttributeEncoder encoder = new AttributeEncoder ();
1923 encoder.Encode ((byte) (bits[3] >> 16));
1924 encoder.Encode ((byte) (bits[3] >> 31));
1925 encoder.Encode ((uint) bits[2]);
1926 encoder.Encode ((uint) bits[1]);
1927 encoder.Encode ((uint) bits[0]);
1928 encoder.EncodeEmptyNamedArguments ();
1930 EmitAttribute (builder, encoder);
1934 public class PredefinedDynamicAttribute : PredefinedAttribute
1938 public PredefinedDynamicAttribute (ModuleContainer module, string ns, string name)
1939 : base (module, ns, name)
1943 public void EmitAttribute (FieldBuilder builder, TypeSpec type, Location loc)
1945 if (ResolveTransformationCtor (loc)) {
1946 var cab = new CustomAttributeBuilder ((ConstructorInfo) tctor.GetMetaInfo (), new object[] { GetTransformationFlags (type) });
1947 builder.SetCustomAttribute (cab);
1951 public void EmitAttribute (ParameterBuilder builder, TypeSpec type, Location loc)
1953 if (ResolveTransformationCtor (loc)) {
1954 var cab = new CustomAttributeBuilder ((ConstructorInfo) tctor.GetMetaInfo (), new object[] { GetTransformationFlags (type) });
1955 builder.SetCustomAttribute (cab);
1959 public void EmitAttribute (PropertyBuilder builder, TypeSpec type, Location loc)
1961 if (ResolveTransformationCtor (loc)) {
1962 var cab = new CustomAttributeBuilder ((ConstructorInfo) tctor.GetMetaInfo (), new object[] { GetTransformationFlags (type) });
1963 builder.SetCustomAttribute (cab);
1967 public void EmitAttribute (TypeBuilder builder, TypeSpec type, Location loc)
1969 if (ResolveTransformationCtor (loc)) {
1970 var cab = new CustomAttributeBuilder ((ConstructorInfo) tctor.GetMetaInfo (), new object[] { GetTransformationFlags (type) });
1971 builder.SetCustomAttribute (cab);
1976 // When any element of the type is a dynamic type
1978 // This method builds a transformation array for dynamic types
1979 // used in places where DynamicAttribute cannot be applied to.
1980 // It uses bool flag when type is of dynamic type and each
1981 // section always starts with "false" for some reason.
1983 // LAMESPEC: This should be part of C# specification
1985 // Example: Func<dynamic, int, dynamic[]>
1986 // Transformation: { false, true, false, false, true }
1988 static bool[] GetTransformationFlags (TypeSpec t)
1991 var ac = t as ArrayContainer;
1993 element = GetTransformationFlags (ac.Element);
1994 if (element == null)
1997 bool[] res = new bool[element.Length + 1];
1999 Array.Copy (element, 0, res, 1, element.Length);
2007 List<bool> transform = null;
2008 var targs = t.TypeArguments;
2009 for (int i = 0; i < targs.Length; ++i) {
2010 element = GetTransformationFlags (targs[i]);
2011 if (element != null) {
2012 if (transform == null) {
2013 transform = new List<bool> ();
2014 for (int ii = 0; ii <= i; ++ii)
2015 transform.Add (false);
2018 transform.AddRange (element);
2019 } else if (transform != null) {
2020 transform.Add (false);
2024 if (transform != null)
2025 return transform.ToArray ();
2028 if (t == InternalType.Dynamic)
2029 return new bool[] { true };
2034 bool ResolveTransformationCtor (Location loc)
2039 if (Resolve (loc) == null)
2042 tctor = TypeManager.GetPredefinedConstructor (type, Location.Null, ArrayContainer.MakeType (module, TypeManager.bool_type));
2043 return tctor != null;