2
// field.cs: All field handlers
4
// Authors: Miguel de Icaza (miguel@gnu.org)
5
// Martin Baulig (martin@ximian.com)
6
// Marek Safar (marek.safar@seznam.cz)
8
// Dual licensed under the terms of the MIT X11 or GNU GPL
10
// Copyright 2001, 2002, 2003 Ximian, Inc (http://www.ximian.com)
11
// Copyright 2004-2008 Novell, Inc
12
// Copyright 2011 Xamarin Inc
16
using System.Collections.Generic;
17
using System.Runtime.InteropServices;
20
using MetaType = IKVM.Reflection.Type;
21
using IKVM.Reflection;
22
using IKVM.Reflection.Emit;
24
using MetaType = System.Type;
25
using System.Reflection;
26
using System.Reflection.Emit;
31
public class FieldDeclarator
33
public FieldDeclarator (SimpleMemberName name, Expression initializer)
36
this.Initializer = initializer;
41
public SimpleMemberName Name { get; private set; }
42
public Expression Initializer { get; private set; }
48
// Abstract class for all fields
50
abstract public class FieldBase : MemberBase
52
protected FieldBuilder FieldBuilder;
53
protected FieldSpec spec;
55
protected Expression initializer;
56
protected List<FieldDeclarator> declarators;
59
public enum Status : byte {
60
HAS_OFFSET = 4 // Used by FieldMember.
63
static readonly string[] attribute_targets = new string [] { "field" };
65
protected FieldBase (TypeDefinition parent, FullNamedExpression type, Modifiers mod, Modifiers allowed_mod, MemberName name, Attributes attrs)
66
: base (parent, type, mod, allowed_mod | Modifiers.ABSTRACT, Modifiers.PRIVATE, name, attrs)
68
if ((mod & Modifiers.ABSTRACT) != 0)
69
Report.Error (681, Location, "The modifier 'abstract' is not valid on fields. Try using a property instead");
74
public override AttributeTargets AttributeTargets {
76
return AttributeTargets.Field;
80
public Expression Initializer {
85
this.initializer = value;
91
return MemberName.Name;
95
public FieldSpec Spec {
101
public override string[] ValidAttributeTargets {
103
return attribute_targets;
107
public List<FieldDeclarator> Declarators {
109
return this.declarators;
114
public void AddDeclarator (FieldDeclarator declarator)
116
if (declarators == null)
117
declarators = new List<FieldDeclarator> (2);
119
declarators.Add (declarator);
121
Parent.AddNameToContainer (this, declarator.Name.Value);
124
public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
126
if (a.Type == pa.FieldOffset) {
127
status |= Status.HAS_OFFSET;
129
if (!Parent.PartialContainer.HasExplicitLayout) {
130
Report.Error (636, Location, "The FieldOffset attribute can only be placed on members of types marked with the StructLayout(LayoutKind.Explicit)");
134
if ((ModFlags & Modifiers.STATIC) != 0 || this is Const) {
135
Report.Error (637, Location, "The FieldOffset attribute is not allowed on static or const fields");
140
if (a.Type == pa.FixedBuffer) {
141
Report.Error (1716, Location, "Do not use 'System.Runtime.CompilerServices.FixedBuffer' attribute. Use the 'fixed' field modifier instead");
146
if (a.Type == pa.MarshalAs) {
147
UnmanagedMarshal marshal = a.GetMarshal (this);
148
if (marshal != null) {
149
FieldBuilder.SetMarshal (marshal);
154
if ((a.HasSecurityAttribute)) {
155
a.Error_InvalidSecurityParent ();
159
if (a.Type == pa.Dynamic) {
160
a.Error_MisusedDynamicAttribute ();
164
FieldBuilder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), cdata);
167
public void SetCustomAttribute (MethodSpec ctor, byte[] data)
169
FieldBuilder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), data);
172
protected override bool CheckBase ()
174
if (!base.CheckBase ())
177
MemberSpec candidate;
178
bool overrides = false;
179
var conflict_symbol = MemberCache.FindBaseMember (this, out candidate, ref overrides);
180
if (conflict_symbol == null)
181
conflict_symbol = candidate;
183
if (conflict_symbol == null) {
184
if ((ModFlags & Modifiers.NEW) != 0) {
185
Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required",
186
GetSignatureForError ());
189
if ((ModFlags & (Modifiers.NEW | Modifiers.OVERRIDE | Modifiers.BACKING_FIELD)) == 0) {
190
Report.SymbolRelatedToPreviousError (conflict_symbol);
191
Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
192
GetSignatureForError (), conflict_symbol.GetSignatureForError ());
195
if (conflict_symbol.IsAbstract) {
196
Report.SymbolRelatedToPreviousError (conflict_symbol);
197
Report.Error (533, Location, "`{0}' hides inherited abstract member `{1}'",
198
GetSignatureForError (), conflict_symbol.GetSignatureForError ());
205
public virtual Constant ConvertInitializer (ResolveContext rc, Constant expr)
207
return expr.ConvertImplicitly (MemberType);
210
protected override void DoMemberTypeDependentChecks ()
212
base.DoMemberTypeDependentChecks ();
214
if (MemberType.IsGenericParameter)
217
if (MemberType.IsStatic)
218
Error_VariableOfStaticClass (Location, GetSignatureForError (), MemberType, Report);
225
// Represents header string for documentation comment.
227
public override string DocCommentHeader {
231
public override void Emit ()
233
if (member_type.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
234
Module.PredefinedAttributes.Dynamic.EmitAttribute (FieldBuilder);
235
} else if (!Parent.IsCompilerGenerated && member_type.HasDynamicElement) {
236
Module.PredefinedAttributes.Dynamic.EmitAttribute (FieldBuilder, member_type, Location);
239
if ((ModFlags & Modifiers.COMPILER_GENERATED) != 0 && !Parent.IsCompilerGenerated)
240
Module.PredefinedAttributes.CompilerGenerated.EmitAttribute (FieldBuilder);
241
if ((ModFlags & Modifiers.DEBUGGER_HIDDEN) != 0)
242
Module.PredefinedAttributes.DebuggerBrowsable.EmitAttribute (FieldBuilder, System.Diagnostics.DebuggerBrowsableState.Never);
244
if (OptAttributes != null) {
245
OptAttributes.Emit ();
248
if (((status & Status.HAS_OFFSET) == 0) && (ModFlags & (Modifiers.STATIC | Modifiers.BACKING_FIELD)) == 0 && Parent.PartialContainer.HasExplicitLayout) {
249
Report.Error (625, Location, "`{0}': Instance field types marked with StructLayout(LayoutKind.Explicit) must have a FieldOffset attribute", GetSignatureForError ());
252
ConstraintChecker.Check (this, member_type, type_expr.Location);
257
public static void Error_VariableOfStaticClass (Location loc, string variable_name, TypeSpec static_class, Report Report)
259
Report.SymbolRelatedToPreviousError (static_class);
260
Report.Error (723, loc, "`{0}': cannot declare variables of static types",
264
protected override bool VerifyClsCompliance ()
266
if (!base.VerifyClsCompliance ())
269
if (!MemberType.IsCLSCompliant () || this is FixedField) {
270
Report.Warning (3003, 1, Location, "Type of `{0}' is not CLS-compliant",
271
GetSignatureForError ());
278
// Field specification
280
public class FieldSpec : MemberSpec, IInterfaceMemberSpec
285
public FieldSpec (TypeSpec declaringType, IMemberDefinition definition, TypeSpec memberType, FieldInfo info, Modifiers modifiers)
286
: base (MemberKind.Field, declaringType, definition, modifiers)
288
this.metaInfo = info;
289
this.memberType = memberType;
294
public bool IsReadOnly {
296
return (Modifiers & Modifiers.READONLY) != 0;
300
public TypeSpec MemberType {
308
public FieldInfo GetMetaInfo ()
310
if ((state & StateFlags.PendingMetaInflate) != 0) {
311
var decl_meta = DeclaringType.GetMetaInfo ();
312
if (DeclaringType.IsTypeBuilder) {
313
metaInfo = TypeBuilder.GetField (decl_meta, metaInfo);
315
var orig_token = metaInfo.MetadataToken;
316
metaInfo = decl_meta.GetField (Name, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static);
317
if (metaInfo.MetadataToken != orig_token)
318
throw new NotImplementedException ("Resolved to wrong meta token");
320
// What a stupid API, does not work because field handle is imported
321
// metaInfo = FieldInfo.GetFieldFromHandle (metaInfo.FieldHandle, DeclaringType.MetaInfo.TypeHandle);
324
state &= ~StateFlags.PendingMetaInflate;
330
public override MemberSpec InflateMember (TypeParameterInflator inflator)
332
var fs = (FieldSpec) base.InflateMember (inflator);
333
fs.memberType = inflator.Inflate (memberType);
337
public FieldSpec Mutate (TypeParameterMutator mutator)
339
var decl = DeclaringType;
340
if (DeclaringType.IsGenericOrParentIsGeneric)
341
decl = mutator.Mutate (decl);
343
if (decl == DeclaringType)
346
var fs = (FieldSpec) MemberwiseClone ();
347
fs.declaringType = decl;
348
fs.state |= StateFlags.PendingMetaInflate;
350
// Gets back FieldInfo in case of metaInfo was inflated
351
fs.metaInfo = MemberCache.GetMember (TypeParameterMutator.GetMemberDeclaringType (DeclaringType), this).metaInfo;
355
public override List<TypeSpec> ResolveMissingDependencies ()
357
return memberType.ResolveMissingDependencies ();
362
/// Fixed buffer implementation
364
public class FixedField : FieldBase
366
public const string FixedElementName = "FixedElementField";
367
static int GlobalCounter = 0;
369
TypeBuilder fixed_buffer_type;
371
const Modifiers AllowedModifiers =
374
Modifiers.PROTECTED |
379
public FixedField (TypeDefinition parent, FullNamedExpression type, Modifiers mod, MemberName name, Attributes attrs)
380
: base (parent, type, mod, AllowedModifiers, name, attrs)
387
// Explicit struct layout set by parent
389
public CharSet? CharSet {
395
public override Constant ConvertInitializer (ResolveContext rc, Constant expr)
397
return expr.ImplicitConversionRequired (rc, rc.BuiltinTypes.Int, Location);
400
public override bool Define ()
405
if (!BuiltinTypeSpec.IsPrimitiveType (MemberType)) {
406
Report.Error (1663, Location,
407
"`{0}': Fixed size buffers type must be one of the following: bool, byte, short, int, long, char, sbyte, ushort, uint, ulong, float or double",
408
GetSignatureForError ());
409
} else if (declarators != null) {
410
var t = new TypeExpression (MemberType, TypeExpression.Location);
411
foreach (var d in declarators) {
412
var f = new FixedField (Parent, t, ModFlags, new MemberName (d.Name.Value, d.Name.Location), OptAttributes);
413
f.initializer = d.Initializer;
414
((ConstInitializer) f.initializer).Name = d.Name.Value;
416
Parent.PartialContainer.Members.Add (f);
420
// Create nested fixed buffer container
421
string name = String.Format ("<{0}>__FixedBuffer{1}", Name, GlobalCounter++);
422
fixed_buffer_type = Parent.TypeBuilder.DefineNestedType (name,
423
TypeAttributes.NestedPublic | TypeAttributes.Sealed | TypeAttributes.BeforeFieldInit,
424
Compiler.BuiltinTypes.ValueType.GetMetaInfo ());
426
var ffield = fixed_buffer_type.DefineField (FixedElementName, MemberType.GetMetaInfo (), FieldAttributes.Public);
428
FieldBuilder = Parent.TypeBuilder.DefineField (Name, fixed_buffer_type, ModifiersExtensions.FieldAttr (ModFlags));
430
var element_spec = new FieldSpec (null, this, MemberType, ffield, ModFlags);
431
spec = new FixedFieldSpec (Module, Parent.Definition, this, FieldBuilder, element_spec, ModFlags);
433
Parent.MemberCache.AddMember (spec);
437
protected override void DoMemberTypeIndependentChecks ()
439
base.DoMemberTypeIndependentChecks ();
442
Expression.UnsafeError (Report, Location);
444
if (Parent.PartialContainer.Kind != MemberKind.Struct) {
445
Report.Error (1642, Location, "`{0}': Fixed size buffer fields may only be members of structs",
446
GetSignatureForError ());
450
public override void Accept (StructuralVisitor visitor)
452
visitor.Visit (this);
455
public override void Emit()
457
ResolveContext rc = new ResolveContext (this);
458
IntConstant buffer_size_const = initializer.Resolve (rc) as IntConstant;
459
if (buffer_size_const == null)
462
int buffer_size = buffer_size_const.Value;
464
if (buffer_size <= 0) {
465
Report.Error (1665, Location, "`{0}': Fixed size buffers must have a length greater than zero", GetSignatureForError ());
469
EmitFieldSize (buffer_size);
472
if (Module.HasDefaultCharSet)
473
fixed_buffer_type.__SetAttributes (fixed_buffer_type.Attributes | Module.DefaultCharSetType);
476
Module.PredefinedAttributes.UnsafeValueType.EmitAttribute (fixed_buffer_type);
477
Module.PredefinedAttributes.CompilerGenerated.EmitAttribute (fixed_buffer_type);
478
fixed_buffer_type.CreateType ();
483
void EmitFieldSize (int buffer_size)
485
int type_size = BuiltinTypeSpec.GetSize (MemberType);
487
if (buffer_size > int.MaxValue / type_size) {
488
Report.Error (1664, Location, "Fixed size buffer `{0}' of length `{1}' and type `{2}' exceeded 2^31 limit",
489
GetSignatureForError (), buffer_size.ToString (), TypeManager.CSharpName (MemberType));
493
AttributeEncoder encoder;
495
var ctor = Module.PredefinedMembers.StructLayoutAttributeCtor.Resolve (Location);
499
var field_size = Module.PredefinedMembers.StructLayoutSize.Resolve (Location);
500
var field_charset = Module.PredefinedMembers.StructLayoutCharSet.Resolve (Location);
501
if (field_size == null || field_charset == null)
504
var char_set = CharSet ?? Module.DefaultCharSet ?? 0;
506
encoder = new AttributeEncoder ();
507
encoder.Encode ((short)LayoutKind.Sequential);
508
encoder.EncodeNamedArguments (
509
new [] { field_size, field_charset },
511
new IntConstant (Compiler.BuiltinTypes, buffer_size * type_size, Location),
512
new IntConstant (Compiler.BuiltinTypes, (int) char_set, Location)
516
fixed_buffer_type.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), encoder.ToArray ());
519
// Don't emit FixedBufferAttribute attribute for private types
521
if ((ModFlags & Modifiers.PRIVATE) != 0)
524
ctor = Module.PredefinedMembers.FixedBufferAttributeCtor.Resolve (Location);
528
encoder = new AttributeEncoder ();
529
encoder.EncodeTypeName (MemberType);
530
encoder.Encode (buffer_size);
531
encoder.EncodeEmptyNamedArguments ();
533
FieldBuilder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), encoder.ToArray ());
537
class FixedFieldSpec : FieldSpec
539
readonly FieldSpec element;
541
public FixedFieldSpec (ModuleContainer module, TypeSpec declaringType, IMemberDefinition definition, FieldInfo info, FieldSpec element, Modifiers modifiers)
542
: base (declaringType, definition, PointerContainer.MakeType (module, element.MemberType), info, modifiers)
544
this.element = element;
546
// It's never CLS-Compliant
547
state &= ~StateFlags.CLSCompliant_Undetected;
550
public FieldSpec Element {
556
public TypeSpec ElementType {
558
return element.MemberType;
564
// The Field class is used to represents class/struct fields during parsing.
566
public class Field : FieldBase {
568
// Modifiers allowed in a class declaration
570
const Modifiers AllowedModifiers =
573
Modifiers.PROTECTED |
581
public Field (TypeDefinition parent, FullNamedExpression type, Modifiers mod, MemberName name, Attributes attrs)
582
: base (parent, type, mod, AllowedModifiers, name, attrs)
586
bool CanBeVolatile ()
588
switch (MemberType.BuiltinType) {
589
case BuiltinTypeSpec.Type.Bool:
590
case BuiltinTypeSpec.Type.Char:
591
case BuiltinTypeSpec.Type.SByte:
592
case BuiltinTypeSpec.Type.Byte:
593
case BuiltinTypeSpec.Type.Short:
594
case BuiltinTypeSpec.Type.UShort:
595
case BuiltinTypeSpec.Type.Int:
596
case BuiltinTypeSpec.Type.UInt:
597
case BuiltinTypeSpec.Type.Float:
598
case BuiltinTypeSpec.Type.UIntPtr:
599
case BuiltinTypeSpec.Type.IntPtr:
603
if (TypeSpec.IsReferenceType (MemberType))
606
if (MemberType.IsEnum)
612
public override void Accept (StructuralVisitor visitor)
614
visitor.Visit (this);
617
public override bool Define ()
622
MetaType[] required_modifier = null;
623
if ((ModFlags & Modifiers.VOLATILE) != 0) {
624
var mod = Module.PredefinedTypes.IsVolatile.Resolve ();
626
required_modifier = new MetaType[] { mod.GetMetaInfo () };
629
FieldBuilder = Parent.TypeBuilder.DefineField (
630
Name, member_type.GetMetaInfo (), required_modifier, null, ModifiersExtensions.FieldAttr (ModFlags));
632
spec = new FieldSpec (Parent.Definition, this, MemberType, FieldBuilder, ModFlags);
635
// Don't cache inaccessible fields except for struct where we
636
// need them for definitive assignment checks
638
if ((ModFlags & Modifiers.BACKING_FIELD) == 0 || Parent.Kind == MemberKind.Struct) {
639
Parent.MemberCache.AddMember (spec);
642
if (initializer != null) {
643
Parent.RegisterFieldForInitialization (this, new FieldInitializer (this, initializer, TypeExpression.Location));
646
if (declarators != null) {
647
foreach (var d in declarators) {
648
var t = new TypeExpression (MemberType, d.Name.Location);
649
var f = new Field (Parent, t, ModFlags, new MemberName (d.Name.Value, d.Name.Location), OptAttributes);
650
if (d.Initializer != null)
651
f.initializer = d.Initializer;
654
Parent.PartialContainer.Members.Add (f);
661
protected override void DoMemberTypeDependentChecks ()
663
if ((ModFlags & Modifiers.BACKING_FIELD) != 0)
666
base.DoMemberTypeDependentChecks ();
668
if ((ModFlags & Modifiers.VOLATILE) != 0) {
669
if (!CanBeVolatile ()) {
670
Report.Error (677, Location, "`{0}': A volatile field cannot be of the type `{1}'",
671
GetSignatureForError (), TypeManager.CSharpName (MemberType));
674
if ((ModFlags & Modifiers.READONLY) != 0) {
675
Report.Error (678, Location, "`{0}': A field cannot be both volatile and readonly",
676
GetSignatureForError ());
681
protected override bool VerifyClsCompliance ()
683
if (!base.VerifyClsCompliance ())
686
if ((ModFlags & Modifiers.VOLATILE) != 0) {
687
Report.Warning (3026, 1, Location, "CLS-compliant field `{0}' cannot be volatile", GetSignatureForError ());