2
// attribute.cs: Attribute Handler
4
// Author: Ravi Pratap (ravi@ximian.com)
5
// Marek Safar (marek.safar@seznam.cz)
7
// Dual licensed under the terms of the MIT X11 or GNU GPL
9
// Copyright 2001-2003 Ximian, Inc (http://www.ximian.com)
10
// Copyright 2003-2008 Novell, Inc.
11
// Copyright 2011 Xamarin Inc
15
using System.Collections.Generic;
16
using System.Runtime.InteropServices;
17
using System.Runtime.CompilerServices;
18
using System.Security;
19
using System.Security.Permissions;
24
using SecurityType = System.Collections.Generic.List<IKVM.Reflection.Emit.CustomAttributeBuilder>;
25
using BadImageFormat = IKVM.Reflection.BadImageFormatException;
26
using IKVM.Reflection;
27
using IKVM.Reflection.Emit;
29
using SecurityType = System.Collections.Generic.Dictionary<System.Security.Permissions.SecurityAction, System.Security.PermissionSet>;
30
using BadImageFormat = System.BadImageFormatException;
31
using System.Reflection;
32
using System.Reflection.Emit;
35
namespace Mono.CSharp {
38
/// Base class for objects that can have Attributes applied to them.
40
public abstract class Attributable {
42
// Holds all attributes attached to this element
44
protected Attributes attributes;
46
public void AddAttributes (Attributes attrs, IMemberContext context)
51
if (attributes == null)
54
attributes.AddAttributes (attrs.Attrs);
55
attrs.AttachTo (this, context);
58
public Attributes OptAttributes {
68
/// Use member-specific procedure to apply attribute @a in @cb to the entity being built in @builder
70
public abstract void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa);
73
/// Returns one AttributeTarget for this element.
75
public abstract AttributeTargets AttributeTargets { get; }
77
public abstract bool IsClsComplianceRequired ();
80
/// Gets list of valid attribute targets for explicit target declaration.
81
/// The first array item is default target. Don't break this rule.
83
public abstract string[] ValidAttributeTargets { get; }
86
public class Attribute
88
public readonly string ExplicitTarget;
89
public AttributeTargets Target;
90
readonly ATypeNameExpression expression;
92
Arguments pos_args, named_args;
96
readonly bool nameEscaped;
97
readonly Location loc;
101
// An attribute can be attached to multiple targets (e.g. multiple fields)
103
Attributable[] targets;
106
// A member context for the attribute, it's much easier to hold it here
107
// than trying to pull it during resolve
109
IMemberContext context;
111
public static readonly AttributeUsageAttribute DefaultUsageAttribute = new AttributeUsageAttribute (AttributeTargets.All);
112
public static readonly object[] EmptyObject = new object [0];
114
List<KeyValuePair<MemberExpr, NamedArgument>> named_values;
116
public Attribute (string target, ATypeNameExpression expr, Arguments[] args, Location loc, bool nameEscaped)
118
this.expression = expr;
121
named_args = args[1];
124
ExplicitTarget = target;
125
this.nameEscaped = nameEscaped;
128
public Location Location {
134
public Arguments NamedArguments {
140
public Arguments PositionalArguments {
146
public ATypeNameExpression TypeExpression {
152
void AddModuleCharSet (ResolveContext rc)
154
const string dll_import_char_set = "CharSet";
157
// Only when not customized by user
159
if (HasField (dll_import_char_set))
162
if (!rc.Module.PredefinedTypes.CharSet.Define ()) {
166
if (NamedArguments == null)
167
named_args = new Arguments (1);
169
var value = Constant.CreateConstant (rc.Module.PredefinedTypes.CharSet.TypeSpec, rc.Module.DefaultCharSet, Location);
170
NamedArguments.Add (new NamedArgument (dll_import_char_set, loc, value));
173
public Attribute Clone ()
175
Attribute a = new Attribute (ExplicitTarget, expression, null, loc, nameEscaped);
176
a.pos_args = pos_args;
177
a.named_args = NamedArguments;
182
// When the same attribute is attached to multiple fiels
183
// we use @target field as a list of targets. The attribute
184
// has to be resolved only once but emitted for each target.
186
public void AttachTo (Attributable target, IMemberContext context)
188
if (this.targets == null) {
189
this.targets = new Attributable[] { target };
190
this.context = context;
194
// When re-attaching global attributes
195
if (context is NamespaceContainer) {
196
this.targets[0] = target;
197
this.context = context;
201
// Resize target array
202
Attributable[] new_array = new Attributable [this.targets.Length + 1];
203
targets.CopyTo (new_array, 0);
204
new_array [targets.Length] = target;
205
this.targets = new_array;
207
// No need to update context, different targets cannot have
208
// different contexts, it's enough to remove same attributes
209
// from secondary members.
211
target.OptAttributes = null;
214
public ResolveContext CreateResolveContext ()
216
return new ResolveContext (context, ResolveContext.Options.ConstantScope);
219
static void Error_InvalidNamedArgument (ResolveContext rc, NamedArgument name)
221
rc.Report.Error (617, name.Location, "`{0}' is not a valid named attribute argument. Named attribute arguments " +
222
"must be fields which are not readonly, static, const or read-write properties which are " +
223
"public and not static",
227
static void Error_InvalidNamedArgumentType (ResolveContext rc, NamedArgument name)
229
rc.Report.Error (655, name.Location,
230
"`{0}' is not a valid named attribute argument because it is not a valid attribute parameter type",
234
public static void Error_AttributeArgumentIsDynamic (IMemberContext context, Location loc)
236
context.Module.Compiler.Report.Error (1982, loc, "An attribute argument cannot be dynamic expression");
239
public void Error_MissingGuidAttribute ()
241
Report.Error (596, Location, "The Guid attribute must be specified with the ComImport attribute");
244
public void Error_MisusedExtensionAttribute ()
246
Report.Error (1112, Location, "Do not use `{0}' directly. Use parameter modifier `this' instead", GetSignatureForError ());
249
public void Error_MisusedDynamicAttribute ()
251
Report.Error (1970, loc, "Do not use `{0}' directly. Use `dynamic' keyword instead", GetSignatureForError ());
255
/// This is rather hack. We report many emit attribute error with same error to be compatible with
256
/// csc. But because csc has to report them this way because error came from ilasm we needn't.
258
public void Error_AttributeEmitError (string inner)
260
Report.Error (647, Location, "Error during emitting `{0}' attribute. The reason is `{1}'",
261
TypeManager.CSharpName (Type), inner);
264
public void Error_InvalidSecurityParent ()
266
Error_AttributeEmitError ("it is attached to invalid parent");
276
/// Tries to resolve the type of the attribute. Flags an error if it can't, and complain is true.
278
void ResolveAttributeType ()
280
SessionReportPrinter resolve_printer = new SessionReportPrinter ();
281
ReportPrinter prev_recorder = Report.SetPrinter (resolve_printer);
283
bool t1_is_attr = false;
284
bool t2_is_attr = false;
286
ATypeNameExpression expanded = null;
288
// TODO: Additional warnings such as CS0436 are swallowed because we don't
292
t1 = expression.ResolveAsType (context);
294
t1_is_attr = t1.IsAttribute;
296
resolve_printer.EndSession ();
301
expanded = (ATypeNameExpression) expression.Clone (null);
302
expanded.Name += "Attribute";
304
t2 = expanded.ResolveAsType (context);
306
t2_is_attr = t2.IsAttribute;
309
context.Module.Compiler.Report.SetPrinter (prev_recorder);
312
if (t1_is_attr && t2_is_attr && t1 != t2) {
313
Report.Error (1614, Location, "`{0}' is ambiguous between `{1}' and `{2}'. Use either `@{0}' or `{0}Attribute'",
314
GetSignatureForError (), expression.GetSignatureForError (), expanded.GetSignatureForError ());
315
resolve_error = true;
329
resolve_error = true;
332
resolve_printer.Merge (prev_recorder);
334
Report.SymbolRelatedToPreviousError (t1);
335
Report.Error (616, Location, "`{0}': is not an attribute class", t1.GetSignatureForError ());
340
Report.SymbolRelatedToPreviousError (t2);
341
Report.Error (616, Location, "`{0}': is not an attribute class", t2.GetSignatureForError ());
345
resolve_printer.Merge (prev_recorder);
348
public TypeSpec ResolveType ()
350
if (Type == null && !resolve_error)
351
ResolveAttributeType ();
355
public string GetSignatureForError ()
358
return TypeManager.CSharpName (Type);
360
return expression.GetSignatureForError ();
363
public bool HasSecurityAttribute {
365
PredefinedAttribute pa = context.Module.PredefinedAttributes.Security;
366
return pa.IsDefined && TypeSpec.IsBaseClass (Type, pa.TypeSpec, false);
370
public bool IsValidSecurityAttribute ()
372
return HasSecurityAttribute && IsSecurityActionValid ();
375
static bool IsValidArgumentType (TypeSpec t)
378
var ac = (ArrayContainer) t;
385
switch (t.BuiltinType) {
386
case BuiltinTypeSpec.Type.Int:
387
case BuiltinTypeSpec.Type.UInt:
388
case BuiltinTypeSpec.Type.Long:
389
case BuiltinTypeSpec.Type.ULong:
390
case BuiltinTypeSpec.Type.Float:
391
case BuiltinTypeSpec.Type.Double:
392
case BuiltinTypeSpec.Type.Char:
393
case BuiltinTypeSpec.Type.Short:
394
case BuiltinTypeSpec.Type.Bool:
395
case BuiltinTypeSpec.Type.SByte:
396
case BuiltinTypeSpec.Type.Byte:
397
case BuiltinTypeSpec.Type.UShort:
399
case BuiltinTypeSpec.Type.String:
400
case BuiltinTypeSpec.Type.Object:
401
case BuiltinTypeSpec.Type.Dynamic:
402
case BuiltinTypeSpec.Type.Type:
409
// TODO: Don't use this ambiguous value
411
get { return expression.Name; }
414
public ATypeNameExpression TypeNameExpression {
420
public Report Report {
421
get { return context.Module.Compiler.Report; }
424
public MethodSpec Resolve ()
429
resolve_error = true;
433
ResolveAttributeType ();
438
if (Type.IsAbstract) {
439
Report.Error (653, Location, "Cannot apply attribute class `{0}' because it is abstract", GetSignatureForError ());
443
ObsoleteAttribute obsolete_attr = Type.GetAttributeObsolete ();
444
if (obsolete_attr != null) {
445
AttributeTester.Report_ObsoleteMessage (obsolete_attr, TypeManager.CSharpName (Type), Location, Report);
448
ResolveContext rc = null;
451
// Try if the attribute is simple and has been resolved before
452
if (pos_args != null || !context.Module.AttributeConstructorCache.TryGetValue (Type, out ctor)) {
453
rc = CreateResolveContext ();
454
ctor = ResolveConstructor (rc);
459
if (pos_args == null && ctor.Parameters.IsEmpty)
460
context.Module.AttributeConstructorCache.Add (Type, ctor);
464
// Add [module: DefaultCharSet] to all DllImport import attributes
466
var module = context.Module;
467
if ((Type == module.PredefinedAttributes.DllImport || Type == module.PredefinedAttributes.UnmanagedFunctionPointer) && module.HasDefaultCharSet) {
469
rc = CreateResolveContext ();
471
AddModuleCharSet (rc);
474
if (NamedArguments != null) {
476
rc = CreateResolveContext ();
478
if (!ResolveNamedArguments (rc))
482
resolve_error = false;
486
MethodSpec ResolveConstructor (ResolveContext ec)
488
if (pos_args != null) {
490
pos_args.Resolve (ec, out dynamic);
492
Error_AttributeArgumentIsDynamic (ec.MemberContext, loc);
497
return Expression.ConstructorLookup (ec, Type, ref pos_args, loc);
500
bool ResolveNamedArguments (ResolveContext ec)
502
int named_arg_count = NamedArguments.Count;
503
var seen_names = new List<string> (named_arg_count);
505
named_values = new List<KeyValuePair<MemberExpr, NamedArgument>> (named_arg_count);
507
foreach (NamedArgument a in NamedArguments) {
508
string name = a.Name;
509
if (seen_names.Contains (name)) {
510
ec.Report.Error (643, a.Location, "Duplicate named attribute `{0}' argument", name);
514
seen_names.Add (name);
518
Expression member = Expression.MemberLookup (ec, false, Type, name, 0, Expression.MemberLookupRestrictions.ExactArity, loc);
520
if (member == null) {
521
member = Expression.MemberLookup (ec, true, Type, name, 0, Expression.MemberLookupRestrictions.ExactArity, loc);
523
if (member != null) {
524
// TODO: ec.Report.SymbolRelatedToPreviousError (member);
525
Expression.ErrorIsInaccesible (ec, member.GetSignatureForError (), loc);
531
Expression.Error_TypeDoesNotContainDefinition (ec, Location, Type, name);
535
if (!(member is PropertyExpr || member is FieldExpr)) {
536
Error_InvalidNamedArgument (ec, a);
540
ObsoleteAttribute obsolete_attr;
542
if (member is PropertyExpr) {
543
var pi = ((PropertyExpr) member).PropertyInfo;
545
if (!pi.HasSet || !pi.HasGet || pi.IsStatic || !pi.Get.IsPublic || !pi.Set.IsPublic) {
546
ec.Report.SymbolRelatedToPreviousError (pi);
547
Error_InvalidNamedArgument (ec, a);
551
if (!IsValidArgumentType (member.Type)) {
552
ec.Report.SymbolRelatedToPreviousError (pi);
553
Error_InvalidNamedArgumentType (ec, a);
557
obsolete_attr = pi.GetAttributeObsolete ();
558
pi.MemberDefinition.SetIsAssigned ();
560
var fi = ((FieldExpr) member).Spec;
562
if (fi.IsReadOnly || fi.IsStatic || !fi.IsPublic) {
563
Error_InvalidNamedArgument (ec, a);
567
if (!IsValidArgumentType (member.Type)) {
568
ec.Report.SymbolRelatedToPreviousError (fi);
569
Error_InvalidNamedArgumentType (ec, a);
573
obsolete_attr = fi.GetAttributeObsolete ();
574
fi.MemberDefinition.SetIsAssigned ();
577
if (obsolete_attr != null && !context.IsObsolete)
578
AttributeTester.Report_ObsoleteMessage (obsolete_attr, member.GetSignatureForError (), member.Location, Report);
580
if (a.Type != member.Type) {
581
a.Expr = Convert.ImplicitConversionRequired (ec, a.Expr, member.Type, a.Expr.Location);
585
named_values.Add (new KeyValuePair<MemberExpr, NamedArgument> ((MemberExpr) member, a));
592
/// Get a string containing a list of valid targets for the attribute 'attr'
594
public string GetValidTargets ()
596
StringBuilder sb = new StringBuilder ();
597
AttributeTargets targets = Type.GetAttributeUsage (context.Module.PredefinedAttributes.AttributeUsage).ValidOn;
599
if ((targets & AttributeTargets.Assembly) != 0)
600
sb.Append ("assembly, ");
602
if ((targets & AttributeTargets.Module) != 0)
603
sb.Append ("module, ");
605
if ((targets & AttributeTargets.Class) != 0)
606
sb.Append ("class, ");
608
if ((targets & AttributeTargets.Struct) != 0)
609
sb.Append ("struct, ");
611
if ((targets & AttributeTargets.Enum) != 0)
612
sb.Append ("enum, ");
614
if ((targets & AttributeTargets.Constructor) != 0)
615
sb.Append ("constructor, ");
617
if ((targets & AttributeTargets.Method) != 0)
618
sb.Append ("method, ");
620
if ((targets & AttributeTargets.Property) != 0)
621
sb.Append ("property, indexer, ");
623
if ((targets & AttributeTargets.Field) != 0)
624
sb.Append ("field, ");
626
if ((targets & AttributeTargets.Event) != 0)
627
sb.Append ("event, ");
629
if ((targets & AttributeTargets.Interface) != 0)
630
sb.Append ("interface, ");
632
if ((targets & AttributeTargets.Parameter) != 0)
633
sb.Append ("parameter, ");
635
if ((targets & AttributeTargets.Delegate) != 0)
636
sb.Append ("delegate, ");
638
if ((targets & AttributeTargets.ReturnValue) != 0)
639
sb.Append ("return, ");
641
if ((targets & AttributeTargets.GenericParameter) != 0)
642
sb.Append ("type parameter, ");
644
return sb.Remove (sb.Length - 2, 2).ToString ();
647
public AttributeUsageAttribute GetAttributeUsageAttribute ()
650
// TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
651
// But because a lot of attribute class code must be rewritten will be better to wait...
655
return DefaultUsageAttribute;
657
AttributeUsageAttribute usage_attribute = new AttributeUsageAttribute ((AttributeTargets) ((Constant) pos_args[0].Expr).GetValue ());
659
var field = GetNamedValue ("AllowMultiple") as BoolConstant;
661
usage_attribute.AllowMultiple = field.Value;
663
field = GetNamedValue ("Inherited") as BoolConstant;
665
usage_attribute.Inherited = field.Value;
667
return usage_attribute;
671
/// Returns custom name of indexer
673
public string GetIndexerAttributeValue ()
676
// TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
677
// But because a lot of attribute class code must be rewritten will be better to wait...
680
if (resolve_error || pos_args.Count != 1 || !(pos_args[0].Expr is Constant))
683
return ((Constant) pos_args[0].Expr).GetValue () as string;
687
/// Returns condition of ConditionalAttribute
689
public string GetConditionalAttributeValue ()
692
// TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
693
// But because a lot of attribute class code must be rewritten will be better to wait...
699
return ((Constant) pos_args[0].Expr).GetValue () as string;
703
/// Creates the instance of ObsoleteAttribute from this attribute instance
705
public ObsoleteAttribute GetObsoleteAttribute ()
708
// corlib only case when obsolete is used before is resolved
709
var c = Type.MemberDefinition as Class;
710
if (c != null && !c.HasMembersDefined)
713
// TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
714
// But because a lot of attribute class code must be rewritten will be better to wait...
721
if (pos_args == null)
722
return new ObsoleteAttribute ();
724
string msg = ((Constant) pos_args[0].Expr).GetValue () as string;
725
if (pos_args.Count == 1)
726
return new ObsoleteAttribute (msg);
728
return new ObsoleteAttribute (msg, ((BoolConstant) pos_args[1].Expr).Value);
732
/// Returns value of CLSCompliantAttribute contructor parameter but because the method can be called
733
/// before ApplyAttribute. We need to resolve the arguments.
734
/// This situation occurs when class deps is differs from Emit order.
736
public bool GetClsCompliantAttributeValue ()
739
// TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
740
// But because a lot of attribute class code must be rewritten will be better to wait...
746
return ((BoolConstant) pos_args[0].Expr).Value;
749
public TypeSpec GetCoClassAttributeValue ()
757
return GetArgumentType ();
760
public bool CheckTarget ()
762
string[] valid_targets = Owner.ValidAttributeTargets;
763
if (ExplicitTarget == null || ExplicitTarget == valid_targets [0]) {
764
Target = Owner.AttributeTargets;
768
// TODO: we can skip the first item
769
if (Array.Exists (valid_targets, i => i == ExplicitTarget)) {
770
switch (ExplicitTarget) {
771
case "return": Target = AttributeTargets.ReturnValue; return true;
772
case "param": Target = AttributeTargets.Parameter; return true;
773
case "field": Target = AttributeTargets.Field; return true;
774
case "method": Target = AttributeTargets.Method; return true;
775
case "property": Target = AttributeTargets.Property; return true;
776
case "module": Target = AttributeTargets.Module; return true;
778
throw new InternalErrorException ("Unknown explicit target: " + ExplicitTarget);
781
StringBuilder sb = new StringBuilder ();
782
foreach (string s in valid_targets) {
786
sb.Remove (sb.Length - 2, 2);
787
Report.Warning (657, 1, Location,
788
"`{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",
789
ExplicitTarget, sb.ToString ());
794
/// Tests permitted SecurityAction for assembly or other types
796
bool IsSecurityActionValid ()
798
SecurityAction action = GetSecurityActionValue ();
799
bool for_assembly = Target == AttributeTargets.Assembly || Target == AttributeTargets.Module;
802
#pragma warning disable 618
803
case SecurityAction.Demand:
804
case SecurityAction.Assert:
805
case SecurityAction.Deny:
806
case SecurityAction.PermitOnly:
807
case SecurityAction.LinkDemand:
808
case SecurityAction.InheritanceDemand:
813
case SecurityAction.RequestMinimum:
814
case SecurityAction.RequestOptional:
815
case SecurityAction.RequestRefuse:
819
#pragma warning restore 618
822
Error_AttributeEmitError ("SecurityAction is out of range");
826
Error_AttributeEmitError (String.Concat ("SecurityAction `", action, "' is not valid for this declaration"));
830
System.Security.Permissions.SecurityAction GetSecurityActionValue ()
832
return (SecurityAction) ((Constant) pos_args[0].Expr).GetValue ();
836
/// Creates instance of SecurityAttribute class and add result of CreatePermission method to permission table.
838
/// <returns></returns>
839
public void ExtractSecurityPermissionSet (MethodSpec ctor, ref SecurityType permissions)
842
object[] values = new object[pos_args.Count];
843
for (int i = 0; i < values.Length; ++i)
844
values[i] = ((Constant) pos_args[i].Expr).GetValue ();
847
object[] prop_values;
848
if (named_values == null) {
852
prop = new PropertyInfo[named_values.Count];
853
prop_values = new object [named_values.Count];
854
for (int i = 0; i < prop.Length; ++i) {
855
prop [i] = ((PropertyExpr) named_values [i].Key).PropertyInfo.MetaInfo;
856
prop_values [i] = ((Constant) named_values [i].Value.Expr).GetValue ();
860
if (permissions == null)
861
permissions = new SecurityType ();
863
var cab = new CustomAttributeBuilder ((ConstructorInfo) ctor.GetMetaInfo (), values, prop, prop_values);
864
permissions.Add (cab);
866
throw new NotSupportedException ();
870
public Constant GetNamedValue (string name)
872
if (named_values == null)
875
for (int i = 0; i < named_values.Count; ++i) {
876
if (named_values [i].Value.Name == name)
877
return named_values [i].Value.Expr as Constant;
883
public CharSet GetCharSetValue ()
885
return (CharSet) System.Enum.Parse (typeof (CharSet), ((Constant) pos_args[0].Expr).GetValue ().ToString ());
888
public bool HasField (string fieldName)
890
if (named_values == null)
893
foreach (var na in named_values) {
894
if (na.Value.Name == fieldName)
902
// Returns true for MethodImplAttribute with MethodImplOptions.InternalCall value
904
public bool IsInternalCall ()
906
return (GetMethodImplOptions () & MethodImplOptions.InternalCall) != 0;
909
public MethodImplOptions GetMethodImplOptions ()
911
MethodImplOptions options = 0;
912
if (pos_args.Count == 1) {
913
options = (MethodImplOptions) System.Enum.Parse (typeof (MethodImplOptions), ((Constant) pos_args[0].Expr).GetValue ().ToString ());
914
} else if (HasField ("Value")) {
915
var named = GetNamedValue ("Value");
916
options = (MethodImplOptions) System.Enum.Parse (typeof (MethodImplOptions), named.GetValue ().ToString ());
923
// Returns true for StructLayoutAttribute with LayoutKind.Explicit value
925
public bool IsExplicitLayoutKind ()
927
if (pos_args == null || pos_args.Count != 1)
930
var value = (LayoutKind) System.Enum.Parse (typeof (LayoutKind), ((Constant) pos_args[0].Expr).GetValue ().ToString ());
931
return value == LayoutKind.Explicit;
934
public Expression GetParameterDefaultValue ()
936
if (pos_args == null)
939
return pos_args[0].Expr;
942
public override bool Equals (object obj)
944
Attribute a = obj as Attribute;
948
return Type == a.Type && Target == a.Target;
951
public override int GetHashCode ()
953
return Type.GetHashCode () ^ Target.GetHashCode ();
957
/// Emit attribute for Attributable symbol
959
public void Emit (Dictionary<Attribute, List<Attribute>> allEmitted)
961
var ctor = Resolve ();
965
var predefined = context.Module.PredefinedAttributes;
967
AttributeUsageAttribute usage_attr = Type.GetAttributeUsage (predefined.AttributeUsage);
968
if ((usage_attr.ValidOn & Target) == 0) {
969
Report.Error (592, Location, "The attribute `{0}' is not valid on this declaration type. " +
970
"It is valid on `{1}' declarations only",
971
GetSignatureForError (), GetValidTargets ());
976
if (pos_args == null && named_values == null) {
977
cdata = AttributeEncoder.Empty;
979
AttributeEncoder encoder = new AttributeEncoder ();
981
if (pos_args != null) {
982
var param_types = ctor.Parameters.Types;
983
for (int j = 0; j < pos_args.Count; ++j) {
984
var pt = param_types[j];
985
var arg_expr = pos_args[j].Expr;
987
if ((Type == predefined.IndexerName || Type == predefined.Conditional) && arg_expr is Constant) {
988
string v = ((Constant) arg_expr).GetValue () as string;
989
if (!Tokenizer.IsValidIdentifier (v) || (Type == predefined.IndexerName && Tokenizer.IsKeyword (v))) {
990
context.Module.Compiler.Report.Error (633, arg_expr.Location,
991
"The argument to the `{0}' attribute must be a valid identifier", GetSignatureForError ());
994
} else if (Type == predefined.Guid) {
996
string v = ((StringConstant) arg_expr).Value;
998
} catch (Exception e) {
999
Error_AttributeEmitError (e.Message);
1002
} else if (Type == predefined.AttributeUsage) {
1003
int v = ((IntConstant) ((EnumConstant) arg_expr).Child).Value;
1005
context.Module.Compiler.Report.Error (591, Location, "Invalid value for argument to `{0}' attribute",
1006
"System.AttributeUsage");
1008
} else if (Type == predefined.MarshalAs) {
1009
if (pos_args.Count == 1) {
1010
var u_type = (UnmanagedType) System.Enum.Parse (typeof (UnmanagedType), ((Constant) pos_args[0].Expr).GetValue ().ToString ());
1011
if (u_type == UnmanagedType.ByValArray && !(Owner is FieldBase)) {
1012
Error_AttributeEmitError ("Specified unmanaged type is only valid on fields");
1015
} else if (Type == predefined.DllImport) {
1016
if (pos_args.Count == 1 && pos_args[0].Expr is Constant) {
1017
var value = ((Constant) pos_args[0].Expr).GetValue () as string;
1018
if (string.IsNullOrEmpty (value))
1019
Error_AttributeEmitError ("DllName cannot be empty");
1021
} else if (Type == predefined.MethodImpl && pt.BuiltinType == BuiltinTypeSpec.Type.Short &&
1022
!System.Enum.IsDefined (typeof (MethodImplOptions), ((Constant) arg_expr).GetValue ().ToString ())) {
1023
Error_AttributeEmitError ("Incorrect argument value.");
1028
arg_expr.EncodeAttributeValue (context, encoder, pt);
1032
if (named_values != null) {
1033
encoder.Encode ((ushort) named_values.Count);
1034
foreach (var na in named_values) {
1035
if (na.Key is FieldExpr)
1036
encoder.Encode ((byte) 0x53);
1038
encoder.Encode ((byte) 0x54);
1040
encoder.Encode (na.Key.Type);
1041
encoder.Encode (na.Value.Name);
1042
na.Value.Expr.EncodeAttributeValue (context, encoder, na.Key.Type);
1045
encoder.EncodeEmptyNamedArguments ();
1048
cdata = encoder.ToArray ();
1052
foreach (Attributable target in targets)
1053
target.ApplyAttributeBuilder (this, ctor, cdata, predefined);
1054
} catch (Exception e) {
1055
if (e is BadImageFormat && Report.Errors > 0)
1058
Error_AttributeEmitError (e.Message);
1062
if (!usage_attr.AllowMultiple && allEmitted != null) {
1063
if (allEmitted.ContainsKey (this)) {
1064
var a = allEmitted [this];
1066
a = new List<Attribute> (2);
1067
allEmitted [this] = a;
1071
allEmitted.Add (this, null);
1075
if (!context.Module.Compiler.Settings.VerifyClsCompliance)
1078
// Here we are testing attribute arguments for array usage (error 3016)
1079
if (Owner.IsClsComplianceRequired ()) {
1080
if (pos_args != null)
1081
pos_args.CheckArrayAsAttribute (context.Module.Compiler);
1083
if (NamedArguments == null)
1086
NamedArguments.CheckArrayAsAttribute (context.Module.Compiler);
1090
private Expression GetValue ()
1092
if (pos_args == null || pos_args.Count < 1)
1095
return pos_args[0].Expr;
1098
public string GetString ()
1100
Expression e = GetValue ();
1101
if (e is StringConstant)
1102
return ((StringConstant)e).Value;
1106
public bool GetBoolean ()
1108
Expression e = GetValue ();
1109
if (e is BoolConstant)
1110
return ((BoolConstant)e).Value;
1114
public TypeSpec GetArgumentType ()
1116
TypeOf e = GetValue () as TypeOf;
1119
return e.TypeArgument;
1123
public class Attributes
1125
public readonly List<Attribute> Attrs;
1127
public readonly List<List<Attribute>> Sections = new List<List<Attribute>> ();
1130
public Attributes (Attribute a)
1132
Attrs = new List<Attribute> ();
1136
Sections.Add (Attrs);
1140
public Attributes (List<Attribute> attrs)
1144
Sections.Add (attrs);
1148
public void AddAttribute (Attribute attr)
1153
public void AddAttributes (List<Attribute> attrs)
1156
Sections.Add (attrs);
1158
Attrs.AddRange (attrs);
1162
public void AttachTo (Attributable attributable, IMemberContext context)
1164
foreach (Attribute a in Attrs)
1165
a.AttachTo (attributable, context);
1168
public Attributes Clone ()
1170
var al = new List<Attribute> (Attrs.Count);
1171
foreach (Attribute a in Attrs)
1172
al.Add (a.Clone ());
1174
return new Attributes (al);
1178
/// Checks whether attribute target is valid for the current element
1180
public bool CheckTargets ()
1182
for (int i = 0; i < Attrs.Count; ++i) {
1183
if (!Attrs [i].CheckTarget ())
1184
Attrs.RemoveAt (i--);
1190
public void ConvertGlobalAttributes (TypeContainer member, NamespaceContainer currentNamespace, bool isGlobal)
1192
var member_explicit_targets = member.ValidAttributeTargets;
1193
for (int i = 0; i < Attrs.Count; ++i) {
1194
var attr = Attrs[0];
1195
if (attr.ExplicitTarget == null)
1199
for (ii = 0; ii < member_explicit_targets.Length; ++ii) {
1200
if (attr.ExplicitTarget == member_explicit_targets[ii]) {
1206
if (ii < 0 || !isGlobal)
1209
member.Module.AddAttribute (attr, currentNamespace);
1215
public Attribute Search (PredefinedAttribute t)
1217
return Search (null, t);
1220
public Attribute Search (string explicitTarget, PredefinedAttribute t)
1222
foreach (Attribute a in Attrs) {
1223
if (explicitTarget != null && a.ExplicitTarget != explicitTarget)
1226
if (a.ResolveType () == t)
1233
/// Returns all attributes of type 't'. Use it when attribute is AllowMultiple = true
1235
public Attribute[] SearchMulti (PredefinedAttribute t)
1237
List<Attribute> ar = null;
1239
foreach (Attribute a in Attrs) {
1240
if (a.ResolveType () == t) {
1242
ar = new List<Attribute> (Attrs.Count);
1247
return ar == null ? null : ar.ToArray ();
1254
Dictionary<Attribute, List<Attribute>> ld = Attrs.Count > 1 ? new Dictionary<Attribute, List<Attribute>> () : null;
1256
foreach (Attribute a in Attrs)
1259
if (ld == null || ld.Count == 0)
1262
foreach (var d in ld) {
1263
if (d.Value == null)
1266
Attribute a = d.Key;
1268
foreach (Attribute collision in d.Value)
1269
a.Report.SymbolRelatedToPreviousError (collision.Location, "");
1271
a.Report.Error (579, a.Location, "The attribute `{0}' cannot be applied multiple times",
1272
a.GetSignatureForError ());
1276
public bool Contains (PredefinedAttribute t)
1278
return Search (t) != null;
1282
public sealed class AttributeEncoder
1285
public enum EncodedTypeProperties
1289
TypeParameter = 1 << 1
1292
public static readonly byte[] Empty;
1296
const ushort Version = 1;
1298
static AttributeEncoder ()
1300
Empty = new byte[4];
1301
Empty[0] = (byte) Version;
1304
public AttributeEncoder ()
1306
buffer = new byte[32];
1310
public void Encode (bool value)
1312
Encode (value ? (byte) 1 : (byte) 0);
1315
public void Encode (byte value)
1317
if (pos == buffer.Length)
1320
buffer [pos++] = value;
1323
public void Encode (sbyte value)
1325
Encode ((byte) value);
1328
public void Encode (short value)
1330
if (pos + 2 > buffer.Length)
1333
buffer[pos++] = (byte) value;
1334
buffer[pos++] = (byte) (value >> 8);
1337
public void Encode (ushort value)
1339
Encode ((short) value);
1342
public void Encode (int value)
1344
if (pos + 4 > buffer.Length)
1347
buffer[pos++] = (byte) value;
1348
buffer[pos++] = (byte) (value >> 8);
1349
buffer[pos++] = (byte) (value >> 16);
1350
buffer[pos++] = (byte) (value >> 24);
1353
public void Encode (uint value)
1355
Encode ((int) value);
1358
public void Encode (long value)
1360
if (pos + 8 > buffer.Length)
1363
buffer[pos++] = (byte) value;
1364
buffer[pos++] = (byte) (value >> 8);
1365
buffer[pos++] = (byte) (value >> 16);
1366
buffer[pos++] = (byte) (value >> 24);
1367
buffer[pos++] = (byte) (value >> 32);
1368
buffer[pos++] = (byte) (value >> 40);
1369
buffer[pos++] = (byte) (value >> 48);
1370
buffer[pos++] = (byte) (value >> 56);
1373
public void Encode (ulong value)
1375
Encode ((long) value);
1378
public void Encode (float value)
1380
Encode (SingleConverter.SingleToInt32Bits (value));
1383
public void Encode (double value)
1385
Encode (BitConverter.DoubleToInt64Bits (value));
1388
public void Encode (string value)
1390
if (value == null) {
1391
Encode ((byte) 0xFF);
1395
var buf = Encoding.UTF8.GetBytes(value);
1396
WriteCompressedValue (buf.Length);
1398
if (pos + buf.Length > buffer.Length)
1401
Buffer.BlockCopy (buf, 0, buffer, pos, buf.Length);
1405
public EncodedTypeProperties Encode (TypeSpec type)
1407
switch (type.BuiltinType) {
1408
case BuiltinTypeSpec.Type.Bool:
1409
Encode ((byte) 0x02);
1411
case BuiltinTypeSpec.Type.Char:
1412
Encode ((byte) 0x03);
1414
case BuiltinTypeSpec.Type.SByte:
1415
Encode ((byte) 0x04);
1417
case BuiltinTypeSpec.Type.Byte:
1418
Encode ((byte) 0x05);
1420
case BuiltinTypeSpec.Type.Short:
1421
Encode ((byte) 0x06);
1423
case BuiltinTypeSpec.Type.UShort:
1424
Encode ((byte) 0x07);
1426
case BuiltinTypeSpec.Type.Int:
1427
Encode ((byte) 0x08);
1429
case BuiltinTypeSpec.Type.UInt:
1430
Encode ((byte) 0x09);
1432
case BuiltinTypeSpec.Type.Long:
1433
Encode ((byte) 0x0A);
1435
case BuiltinTypeSpec.Type.ULong:
1436
Encode ((byte) 0x0B);
1438
case BuiltinTypeSpec.Type.Float:
1439
Encode ((byte) 0x0C);
1441
case BuiltinTypeSpec.Type.Double:
1442
Encode ((byte) 0x0D);
1444
case BuiltinTypeSpec.Type.String:
1445
Encode ((byte) 0x0E);
1447
case BuiltinTypeSpec.Type.Type:
1448
Encode ((byte) 0x50);
1450
case BuiltinTypeSpec.Type.Object:
1451
Encode ((byte) 0x51);
1453
case BuiltinTypeSpec.Type.Dynamic:
1454
Encode ((byte) 0x51);
1455
return EncodedTypeProperties.DynamicType;
1458
Encode ((byte) 0x1D);
1459
return Encode (TypeManager.GetElementType (type));
1462
if (type.Kind == MemberKind.Enum) {
1463
Encode ((byte) 0x55);
1464
EncodeTypeName (type);
1470
return EncodedTypeProperties.None;
1473
public void EncodeTypeName (TypeSpec type)
1475
var old_type = type.GetMetaInfo ();
1476
Encode (type.MemberDefinition.IsImported ? old_type.AssemblyQualifiedName : old_type.FullName);
1480
// Encodes single property named argument per call
1482
public void EncodeNamedPropertyArgument (PropertySpec property, Constant value)
1484
Encode ((ushort) 1); // length
1485
Encode ((byte) 0x54); // property
1486
Encode (property.MemberType);
1487
Encode (property.Name);
1488
value.EncodeAttributeValue (null, this, property.MemberType);
1492
// Encodes single field named argument per call
1494
public void EncodeNamedFieldArgument (FieldSpec field, Constant value)
1496
Encode ((ushort) 1); // length
1497
Encode ((byte) 0x53); // field
1498
Encode (field.MemberType);
1499
Encode (field.Name);
1500
value.EncodeAttributeValue (null, this, field.MemberType);
1503
public void EncodeNamedArguments<T> (T[] members, Constant[] values) where T : MemberSpec, IInterfaceMemberSpec
1505
Encode ((ushort) members.Length);
1507
for (int i = 0; i < members.Length; ++i)
1509
var member = members[i];
1511
if (member.Kind == MemberKind.Field)
1512
Encode ((byte) 0x53);
1513
else if (member.Kind == MemberKind.Property)
1514
Encode ((byte) 0x54);
1516
throw new NotImplementedException (member.Kind.ToString ());
1518
Encode (member.MemberType);
1519
Encode (member.Name);
1520
values [i].EncodeAttributeValue (null, this, member.MemberType);
1524
public void EncodeEmptyNamedArguments ()
1526
Encode ((ushort) 0);
1531
int size = System.Math.Max (pos * 4, pos + inc + 2);
1532
Array.Resize (ref buffer, size);
1535
void WriteCompressedValue (int value)
1538
Encode ((byte) value);
1542
if (value < 0x4000) {
1543
Encode ((byte) (0x80 | (value >> 8)));
1544
Encode ((byte) value);
1551
public byte[] ToArray ()
1553
byte[] buf = new byte[pos];
1554
Array.Copy (buffer, buf, pos);
1561
/// Helper class for attribute verification routine.
1563
static class AttributeTester
1566
/// Common method for Obsolete error/warning reporting.
1568
public static void Report_ObsoleteMessage (ObsoleteAttribute oa, string member, Location loc, Report Report)
1571
Report.Error (619, loc, "`{0}' is obsolete: `{1}'", member, oa.Message);
1575
if (oa.Message == null || oa.Message.Length == 0) {
1576
Report.Warning (612, 1, loc, "`{0}' is obsolete", member);
1579
Report.Warning (618, 2, loc, "`{0}' is obsolete: `{1}'", member, oa.Message);
1584
// Predefined attribute types
1586
public class PredefinedAttributes
1588
// Build-in attributes
1589
public readonly PredefinedAttribute ParamArray;
1590
public readonly PredefinedAttribute Out;
1592
// Optional attributes
1593
public readonly PredefinedAttribute Obsolete;
1594
public readonly PredefinedAttribute DllImport;
1595
public readonly PredefinedAttribute MethodImpl;
1596
public readonly PredefinedAttribute MarshalAs;
1597
public readonly PredefinedAttribute In;
1598
public readonly PredefinedAttribute IndexerName;
1599
public readonly PredefinedAttribute Conditional;
1600
public readonly PredefinedAttribute CLSCompliant;
1601
public readonly PredefinedAttribute Security;
1602
public readonly PredefinedAttribute Required;
1603
public readonly PredefinedAttribute Guid;
1604
public readonly PredefinedAttribute AssemblyCulture;
1605
public readonly PredefinedAttribute AssemblyVersion;
1606
public readonly PredefinedAttribute AssemblyAlgorithmId;
1607
public readonly PredefinedAttribute AssemblyFlags;
1608
public readonly PredefinedAttribute AssemblyFileVersion;
1609
public readonly PredefinedAttribute ComImport;
1610
public readonly PredefinedAttribute CoClass;
1611
public readonly PredefinedAttribute AttributeUsage;
1612
public readonly PredefinedAttribute DefaultParameterValue;
1613
public readonly PredefinedAttribute OptionalParameter;
1614
public readonly PredefinedAttribute UnverifiableCode;
1615
public readonly PredefinedAttribute DefaultCharset;
1616
public readonly PredefinedAttribute TypeForwarder;
1617
public readonly PredefinedAttribute FixedBuffer;
1618
public readonly PredefinedAttribute CompilerGenerated;
1619
public readonly PredefinedAttribute InternalsVisibleTo;
1620
public readonly PredefinedAttribute RuntimeCompatibility;
1621
public readonly PredefinedAttribute DebuggerHidden;
1622
public readonly PredefinedAttribute UnsafeValueType;
1623
public readonly PredefinedAttribute UnmanagedFunctionPointer;
1624
public readonly PredefinedDebuggerBrowsableAttribute DebuggerBrowsable;
1627
public readonly PredefinedAttribute Extension;
1630
public readonly PredefinedDynamicAttribute Dynamic;
1633
// Optional types which are used as types and for member lookup
1635
public readonly PredefinedAttribute DefaultMember;
1636
public readonly PredefinedDecimalAttribute DecimalConstant;
1637
public readonly PredefinedAttribute StructLayout;
1638
public readonly PredefinedAttribute FieldOffset;
1639
public readonly PredefinedAttribute CallerMemberNameAttribute;
1640
public readonly PredefinedAttribute CallerLineNumberAttribute;
1641
public readonly PredefinedAttribute CallerFilePathAttribute;
1643
public PredefinedAttributes (ModuleContainer module)
1645
ParamArray = new PredefinedAttribute (module, "System", "ParamArrayAttribute");
1646
Out = new PredefinedAttribute (module, "System.Runtime.InteropServices", "OutAttribute");
1647
ParamArray.Resolve ();
1650
Obsolete = new PredefinedAttribute (module, "System", "ObsoleteAttribute");
1651
DllImport = new PredefinedAttribute (module, "System.Runtime.InteropServices", "DllImportAttribute");
1652
MethodImpl = new PredefinedAttribute (module, "System.Runtime.CompilerServices", "MethodImplAttribute");
1653
MarshalAs = new PredefinedAttribute (module, "System.Runtime.InteropServices", "MarshalAsAttribute");
1654
In = new PredefinedAttribute (module, "System.Runtime.InteropServices", "InAttribute");
1655
IndexerName = new PredefinedAttribute (module, "System.Runtime.CompilerServices", "IndexerNameAttribute");
1656
Conditional = new PredefinedAttribute (module, "System.Diagnostics", "ConditionalAttribute");
1657
CLSCompliant = new PredefinedAttribute (module, "System", "CLSCompliantAttribute");
1658
Security = new PredefinedAttribute (module, "System.Security.Permissions", "SecurityAttribute");
1659
Required = new PredefinedAttribute (module, "System.Runtime.CompilerServices", "RequiredAttributeAttribute");
1660
Guid = new PredefinedAttribute (module, "System.Runtime.InteropServices", "GuidAttribute");
1661
AssemblyCulture = new PredefinedAttribute (module, "System.Reflection", "AssemblyCultureAttribute");
1662
AssemblyVersion = new PredefinedAttribute (module, "System.Reflection", "AssemblyVersionAttribute");
1663
AssemblyAlgorithmId = new PredefinedAttribute (module, "System.Reflection", "AssemblyAlgorithmIdAttribute");
1664
AssemblyFlags = new PredefinedAttribute (module, "System.Reflection", "AssemblyFlagsAttribute");
1665
AssemblyFileVersion = new PredefinedAttribute (module, "System.Reflection", "AssemblyFileVersionAttribute");
1666
ComImport = new PredefinedAttribute (module, "System.Runtime.InteropServices", "ComImportAttribute");
1667
CoClass = new PredefinedAttribute (module, "System.Runtime.InteropServices", "CoClassAttribute");
1668
AttributeUsage = new PredefinedAttribute (module, "System", "AttributeUsageAttribute");
1669
DefaultParameterValue = new PredefinedAttribute (module, "System.Runtime.InteropServices", "DefaultParameterValueAttribute");
1670
OptionalParameter = new PredefinedAttribute (module, "System.Runtime.InteropServices", "OptionalAttribute");
1671
UnverifiableCode = new PredefinedAttribute (module, "System.Security", "UnverifiableCodeAttribute");
1673
DefaultCharset = new PredefinedAttribute (module, "System.Runtime.InteropServices", "DefaultCharSetAttribute");
1674
TypeForwarder = new PredefinedAttribute (module, "System.Runtime.CompilerServices", "TypeForwardedToAttribute");
1675
FixedBuffer = new PredefinedAttribute (module, "System.Runtime.CompilerServices", "FixedBufferAttribute");
1676
CompilerGenerated = new PredefinedAttribute (module, "System.Runtime.CompilerServices", "CompilerGeneratedAttribute");
1677
InternalsVisibleTo = new PredefinedAttribute (module, "System.Runtime.CompilerServices", "InternalsVisibleToAttribute");
1678
RuntimeCompatibility = new PredefinedAttribute (module, "System.Runtime.CompilerServices", "RuntimeCompatibilityAttribute");
1679
DebuggerHidden = new PredefinedAttribute (module, "System.Diagnostics", "DebuggerHiddenAttribute");
1680
UnsafeValueType = new PredefinedAttribute (module, "System.Runtime.CompilerServices", "UnsafeValueTypeAttribute");
1681
UnmanagedFunctionPointer = new PredefinedAttribute (module, "System.Runtime.InteropServices", "UnmanagedFunctionPointerAttribute");
1682
DebuggerBrowsable = new PredefinedDebuggerBrowsableAttribute (module, "System.Diagnostics", "DebuggerBrowsableAttribute");
1684
Extension = new PredefinedAttribute (module, "System.Runtime.CompilerServices", "ExtensionAttribute");
1686
Dynamic = new PredefinedDynamicAttribute (module, "System.Runtime.CompilerServices", "DynamicAttribute");
1688
DefaultMember = new PredefinedAttribute (module, "System.Reflection", "DefaultMemberAttribute");
1689
DecimalConstant = new PredefinedDecimalAttribute (module, "System.Runtime.CompilerServices", "DecimalConstantAttribute");
1690
StructLayout = new PredefinedAttribute (module, "System.Runtime.InteropServices", "StructLayoutAttribute");
1691
FieldOffset = new PredefinedAttribute (module, "System.Runtime.InteropServices", "FieldOffsetAttribute");
1693
CallerMemberNameAttribute = new PredefinedAttribute (module, "System.Runtime.CompilerServices", "CallerMemberNameAttribute");
1694
CallerLineNumberAttribute = new PredefinedAttribute (module, "System.Runtime.CompilerServices", "CallerLineNumberAttribute");
1695
CallerFilePathAttribute = new PredefinedAttribute (module, "System.Runtime.CompilerServices", "CallerFilePathAttribute");
1697
// TODO: Should define only attributes which are used for comparison
1698
const System.Reflection.BindingFlags all_fields = System.Reflection.BindingFlags.Public |
1699
System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.DeclaredOnly;
1701
foreach (var fi in GetType ().GetFields (all_fields)) {
1702
((PredefinedAttribute) fi.GetValue (this)).Define ();
1707
public class PredefinedAttribute : PredefinedType
1709
protected MethodSpec ctor;
1711
public PredefinedAttribute (ModuleContainer module, string ns, string name)
1712
: base (module, MemberKind.Class, ns, name)
1718
public MethodSpec Constructor {
1726
public static bool operator == (TypeSpec type, PredefinedAttribute pa)
1728
return type == pa.type && pa.type != null;
1731
public static bool operator != (TypeSpec type, PredefinedAttribute pa)
1733
return type != pa.type;
1736
public override int GetHashCode ()
1738
return base.GetHashCode ();
1741
public override bool Equals (object obj)
1743
throw new NotSupportedException ();
1746
public void EmitAttribute (ConstructorBuilder builder)
1748
if (ResolveBuilder ())
1749
builder.SetCustomAttribute (GetCtorMetaInfo (), AttributeEncoder.Empty);
1752
public void EmitAttribute (MethodBuilder builder)
1754
if (ResolveBuilder ())
1755
builder.SetCustomAttribute (GetCtorMetaInfo (), AttributeEncoder.Empty);
1758
public void EmitAttribute (PropertyBuilder builder)
1760
if (ResolveBuilder ())
1761
builder.SetCustomAttribute (GetCtorMetaInfo (), AttributeEncoder.Empty);
1764
public void EmitAttribute (FieldBuilder builder)
1766
if (ResolveBuilder ())
1767
builder.SetCustomAttribute (GetCtorMetaInfo (), AttributeEncoder.Empty);
1770
public void EmitAttribute (TypeBuilder builder)
1772
if (ResolveBuilder ())
1773
builder.SetCustomAttribute (GetCtorMetaInfo (), AttributeEncoder.Empty);
1776
public void EmitAttribute (AssemblyBuilder builder)
1778
if (ResolveBuilder ())
1779
builder.SetCustomAttribute (GetCtorMetaInfo (), AttributeEncoder.Empty);
1782
public void EmitAttribute (ModuleBuilder builder)
1784
if (ResolveBuilder ())
1785
builder.SetCustomAttribute (GetCtorMetaInfo (), AttributeEncoder.Empty);
1788
public void EmitAttribute (ParameterBuilder builder)
1790
if (ResolveBuilder ())
1791
builder.SetCustomAttribute (GetCtorMetaInfo (), AttributeEncoder.Empty);
1794
ConstructorInfo GetCtorMetaInfo ()
1796
return (ConstructorInfo) ctor.GetMetaInfo ();
1799
public bool ResolveBuilder ()
1805
// Handle all parameter-less attributes as optional
1810
ctor = (MethodSpec) MemberCache.FindMember (type, MemberFilter.Constructor (ParametersCompiled.EmptyReadOnlyParameters), BindingRestriction.DeclaredOnly);
1811
return ctor != null;
1815
public class PredefinedDebuggerBrowsableAttribute : PredefinedAttribute
1817
public PredefinedDebuggerBrowsableAttribute (ModuleContainer module, string ns, string name)
1818
: base (module, ns, name)
1822
public void EmitAttribute (FieldBuilder builder, System.Diagnostics.DebuggerBrowsableState state)
1824
var ctor = module.PredefinedMembers.DebuggerBrowsableAttributeCtor.Get ();
1828
AttributeEncoder encoder = new AttributeEncoder ();
1829
encoder.Encode ((int) state);
1830
encoder.EncodeEmptyNamedArguments ();
1832
builder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), encoder.ToArray ());
1836
public class PredefinedDecimalAttribute : PredefinedAttribute
1838
public PredefinedDecimalAttribute (ModuleContainer module, string ns, string name)
1839
: base (module, ns, name)
1843
public void EmitAttribute (ParameterBuilder builder, decimal value, Location loc)
1845
var ctor = module.PredefinedMembers.DecimalConstantAttributeCtor.Resolve (loc);
1849
int[] bits = decimal.GetBits (value);
1850
AttributeEncoder encoder = new AttributeEncoder ();
1851
encoder.Encode ((byte) (bits[3] >> 16));
1852
encoder.Encode ((byte) (bits[3] >> 31));
1853
encoder.Encode ((uint) bits[2]);
1854
encoder.Encode ((uint) bits[1]);
1855
encoder.Encode ((uint) bits[0]);
1856
encoder.EncodeEmptyNamedArguments ();
1858
builder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), encoder.ToArray ());
1861
public void EmitAttribute (FieldBuilder builder, decimal value, Location loc)
1863
var ctor = module.PredefinedMembers.DecimalConstantAttributeCtor.Resolve (loc);
1867
int[] bits = decimal.GetBits (value);
1868
AttributeEncoder encoder = new AttributeEncoder ();
1869
encoder.Encode ((byte) (bits[3] >> 16));
1870
encoder.Encode ((byte) (bits[3] >> 31));
1871
encoder.Encode ((uint) bits[2]);
1872
encoder.Encode ((uint) bits[1]);
1873
encoder.Encode ((uint) bits[0]);
1874
encoder.EncodeEmptyNamedArguments ();
1876
builder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), encoder.ToArray ());
1880
public class PredefinedDynamicAttribute : PredefinedAttribute
1884
public PredefinedDynamicAttribute (ModuleContainer module, string ns, string name)
1885
: base (module, ns, name)
1889
public void EmitAttribute (FieldBuilder builder, TypeSpec type, Location loc)
1891
if (ResolveTransformationCtor (loc)) {
1892
var cab = new CustomAttributeBuilder ((ConstructorInfo) tctor.GetMetaInfo (), new object[] { GetTransformationFlags (type) });
1893
builder.SetCustomAttribute (cab);
1897
public void EmitAttribute (ParameterBuilder builder, TypeSpec type, Location loc)
1899
if (ResolveTransformationCtor (loc)) {
1900
var cab = new CustomAttributeBuilder ((ConstructorInfo) tctor.GetMetaInfo (), new object[] { GetTransformationFlags (type) });
1901
builder.SetCustomAttribute (cab);
1905
public void EmitAttribute (PropertyBuilder builder, TypeSpec type, Location loc)
1907
if (ResolveTransformationCtor (loc)) {
1908
var cab = new CustomAttributeBuilder ((ConstructorInfo) tctor.GetMetaInfo (), new object[] { GetTransformationFlags (type) });
1909
builder.SetCustomAttribute (cab);
1913
public void EmitAttribute (TypeBuilder builder, TypeSpec type, Location loc)
1915
if (ResolveTransformationCtor (loc)) {
1916
var cab = new CustomAttributeBuilder ((ConstructorInfo) tctor.GetMetaInfo (), new object[] { GetTransformationFlags (type) });
1917
builder.SetCustomAttribute (cab);
1922
// When any element of the type is a dynamic type
1924
// This method builds a transformation array for dynamic types
1925
// used in places where DynamicAttribute cannot be applied to.
1926
// It uses bool flag when type is of dynamic type and each
1927
// section always starts with "false" for some reason.
1929
// LAMESPEC: This should be part of C# specification
1931
// Example: Func<dynamic, int, dynamic[]>
1932
// Transformation: { false, true, false, false, true }
1934
static bool[] GetTransformationFlags (TypeSpec t)
1937
var ac = t as ArrayContainer;
1939
element = GetTransformationFlags (ac.Element);
1940
if (element == null)
1943
bool[] res = new bool[element.Length + 1];
1945
Array.Copy (element, 0, res, 1, element.Length);
1953
List<bool> transform = null;
1954
var targs = t.TypeArguments;
1955
for (int i = 0; i < targs.Length; ++i) {
1956
element = GetTransformationFlags (targs[i]);
1957
if (element != null) {
1958
if (transform == null) {
1959
transform = new List<bool> ();
1960
for (int ii = 0; ii <= i; ++ii)
1961
transform.Add (false);
1964
transform.AddRange (element);
1965
} else if (transform != null) {
1966
transform.Add (false);
1970
if (transform != null)
1971
return transform.ToArray ();
1974
if (t.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
1975
return new bool[] { true };
1980
bool ResolveTransformationCtor (Location loc)
1985
tctor = module.PredefinedMembers.DynamicAttributeCtor.Resolve (loc);
1986
return tctor != null;