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
15 using System.Collections.Generic;
16 using System.Runtime.InteropServices;
19 using MetaType = IKVM.Reflection.Type;
20 using IKVM.Reflection;
21 using IKVM.Reflection.Emit;
23 using MetaType = System.Type;
24 using System.Reflection;
25 using System.Reflection.Emit;
30 public class FieldDeclarator
32 public FieldDeclarator (SimpleMemberName name, Expression initializer)
35 this.Initializer = initializer;
40 public SimpleMemberName Name { get; private set; }
41 public Expression Initializer { get; private set; }
47 // Abstract class for all fields
49 abstract public class FieldBase : MemberBase
51 protected FieldBuilder FieldBuilder;
52 protected FieldSpec spec;
54 protected Expression initializer;
55 protected List<FieldDeclarator> declarators;
58 public enum Status : byte {
59 HAS_OFFSET = 4 // Used by FieldMember.
62 static readonly string[] attribute_targets = new string [] { "field" };
64 protected FieldBase (DeclSpace parent, FullNamedExpression type, Modifiers mod,
65 Modifiers allowed_mod, MemberName name, Attributes attrs)
66 : base (parent, null, type, mod, allowed_mod | Modifiers.ABSTRACT, Modifiers.PRIVATE,
69 if ((mod & Modifiers.ABSTRACT) != 0)
70 Report.Error (681, Location, "The modifier 'abstract' is not valid on fields. Try using a property instead");
75 public override AttributeTargets AttributeTargets {
77 return AttributeTargets.Field;
81 public Expression Initializer {
86 this.initializer = value;
90 public FieldSpec Spec {
96 public override string[] ValidAttributeTargets {
98 return attribute_targets;
104 public void AddDeclarator (FieldDeclarator declarator)
106 if (declarators == null)
107 declarators = new List<FieldDeclarator> (2);
109 declarators.Add (declarator);
111 // TODO: This will probably break
112 Parent.AddMember (this, declarator.Name.Value);
115 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
117 if (a.Type == pa.FieldOffset) {
118 status |= Status.HAS_OFFSET;
120 if (!Parent.PartialContainer.HasExplicitLayout) {
121 Report.Error (636, Location, "The FieldOffset attribute can only be placed on members of types marked with the StructLayout(LayoutKind.Explicit)");
125 if ((ModFlags & Modifiers.STATIC) != 0 || this is Const) {
126 Report.Error (637, Location, "The FieldOffset attribute is not allowed on static or const fields");
131 if (a.Type == pa.FixedBuffer) {
132 Report.Error (1716, Location, "Do not use 'System.Runtime.CompilerServices.FixedBuffer' attribute. Use the 'fixed' field modifier instead");
137 if (a.Type == pa.MarshalAs) {
138 UnmanagedMarshal marshal = a.GetMarshal (this);
139 if (marshal != null) {
140 FieldBuilder.SetMarshal (marshal);
145 if ((a.HasSecurityAttribute)) {
146 a.Error_InvalidSecurityParent ();
150 if (a.Type == pa.Dynamic) {
151 a.Error_MisusedDynamicAttribute ();
155 FieldBuilder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), cdata);
158 public void SetCustomAttribute (MethodSpec ctor, byte[] data)
160 FieldBuilder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), data);
163 protected override bool CheckBase ()
165 if (!base.CheckBase ())
168 MemberSpec candidate;
169 var conflict_symbol = MemberCache.FindBaseMember (this, out candidate);
170 if (conflict_symbol == null)
171 conflict_symbol = candidate;
173 if (conflict_symbol == null) {
174 if ((ModFlags & Modifiers.NEW) != 0) {
175 Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required",
176 GetSignatureForError ());
179 if ((ModFlags & (Modifiers.NEW | Modifiers.OVERRIDE | Modifiers.BACKING_FIELD)) == 0) {
180 Report.SymbolRelatedToPreviousError (conflict_symbol);
181 Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
182 GetSignatureForError (), conflict_symbol.GetSignatureForError ());
185 if (conflict_symbol.IsAbstract) {
186 Report.SymbolRelatedToPreviousError (conflict_symbol);
187 Report.Error (533, Location, "`{0}' hides inherited abstract member `{1}'",
188 GetSignatureForError (), conflict_symbol.GetSignatureForError ());
195 public virtual Constant ConvertInitializer (ResolveContext rc, Constant expr)
197 return expr.ConvertImplicitly (MemberType);
200 protected override void DoMemberTypeDependentChecks ()
202 base.DoMemberTypeDependentChecks ();
204 if (MemberType.IsGenericParameter)
207 if (MemberType.IsStatic)
208 Error_VariableOfStaticClass (Location, GetSignatureForError (), MemberType, Report);
215 // Represents header string for documentation comment.
217 public override string DocCommentHeader {
221 public override void Emit ()
223 if (member_type.BuildinType == BuildinTypeSpec.Type.Dynamic) {
224 Module.PredefinedAttributes.Dynamic.EmitAttribute (FieldBuilder);
225 } else if (!(Parent is CompilerGeneratedClass) && member_type.HasDynamicElement) {
226 Module.PredefinedAttributes.Dynamic.EmitAttribute (FieldBuilder, member_type, Location);
229 if ((ModFlags & Modifiers.COMPILER_GENERATED) != 0 && !Parent.IsCompilerGenerated)
230 Module.PredefinedAttributes.CompilerGenerated.EmitAttribute (FieldBuilder);
232 if (OptAttributes != null) {
233 OptAttributes.Emit ();
236 if (((status & Status.HAS_OFFSET) == 0) && (ModFlags & (Modifiers.STATIC | Modifiers.BACKING_FIELD)) == 0 && Parent.PartialContainer.HasExplicitLayout) {
237 Report.Error (625, Location, "`{0}': Instance field types marked with StructLayout(LayoutKind.Explicit) must have a FieldOffset attribute", GetSignatureForError ());
243 public static void Error_VariableOfStaticClass (Location loc, string variable_name, TypeSpec static_class, Report Report)
245 Report.SymbolRelatedToPreviousError (static_class);
246 Report.Error (723, loc, "`{0}': cannot declare variables of static types",
250 protected override bool VerifyClsCompliance ()
252 if (!base.VerifyClsCompliance ())
255 if (!MemberType.IsCLSCompliant () || this is FixedField) {
256 Report.Warning (3003, 1, Location, "Type of `{0}' is not CLS-compliant",
257 GetSignatureForError ());
264 // Field specification
266 public class FieldSpec : MemberSpec, IInterfaceMemberSpec
271 public FieldSpec (TypeSpec declaringType, IMemberDefinition definition, TypeSpec memberType, FieldInfo info, Modifiers modifiers)
272 : base (MemberKind.Field, declaringType, definition, modifiers)
274 this.metaInfo = info;
275 this.memberType = memberType;
280 public bool IsReadOnly {
282 return (Modifiers & Modifiers.READONLY) != 0;
286 public TypeSpec MemberType {
294 public FieldInfo GetMetaInfo ()
296 if ((state & StateFlags.PendingMetaInflate) != 0) {
297 var decl_meta = DeclaringType.GetMetaInfo ();
298 if (DeclaringType.IsTypeBuilder) {
299 metaInfo = TypeBuilder.GetField (decl_meta, metaInfo);
301 var orig_token = metaInfo.MetadataToken;
302 metaInfo = decl_meta.GetField (Name, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static);
303 if (metaInfo.MetadataToken != orig_token)
304 throw new NotImplementedException ("Resolved to wrong meta token");
306 // What a stupid API, does not work because field handle is imported
307 // metaInfo = FieldInfo.GetFieldFromHandle (metaInfo.FieldHandle, DeclaringType.MetaInfo.TypeHandle);
310 state &= ~StateFlags.PendingMetaInflate;
316 public override MemberSpec InflateMember (TypeParameterInflator inflator)
318 var fs = (FieldSpec) base.InflateMember (inflator);
319 fs.memberType = inflator.Inflate (memberType);
323 public FieldSpec Mutate (TypeParameterMutator mutator)
325 var decl = DeclaringType;
326 if (DeclaringType.IsGenericOrParentIsGeneric)
327 decl = mutator.Mutate (decl);
329 if (decl == DeclaringType)
332 var fs = (FieldSpec) MemberwiseClone ();
333 fs.declaringType = decl;
334 fs.state |= StateFlags.PendingMetaInflate;
336 // Gets back FieldInfo in case of metaInfo was inflated
337 fs.metaInfo = MemberCache.GetMember (TypeParameterMutator.GetMemberDeclaringType (DeclaringType), this).metaInfo;
341 public override List<TypeSpec> ResolveMissingDependencies ()
343 return memberType.ResolveMissingDependencies ();
348 /// Fixed buffer implementation
350 public class FixedField : FieldBase
352 public const string FixedElementName = "FixedElementField";
353 static int GlobalCounter = 0;
355 TypeBuilder fixed_buffer_type;
357 const Modifiers AllowedModifiers =
360 Modifiers.PROTECTED |
365 public FixedField (DeclSpace parent, FullNamedExpression type, Modifiers mod, MemberName name, Attributes attrs)
366 : base (parent, type, mod, AllowedModifiers, name, attrs)
373 // Explicit struct layout set by parent
375 public CharSet? CharSet {
381 public override Constant ConvertInitializer (ResolveContext rc, Constant expr)
383 return expr.ImplicitConversionRequired (rc, rc.BuildinTypes.Int, Location);
386 public override bool Define ()
391 if (!BuildinTypeSpec.IsPrimitiveType (MemberType)) {
392 Report.Error (1663, Location,
393 "`{0}': Fixed size buffers type must be one of the following: bool, byte, short, int, long, char, sbyte, ushort, uint, ulong, float or double",
394 GetSignatureForError ());
395 } else if (declarators != null) {
396 var t = new TypeExpression (MemberType, TypeExpression.Location);
397 int index = Parent.PartialContainer.Fields.IndexOf (this);
398 foreach (var d in declarators) {
399 var f = new FixedField (Parent, t, ModFlags, new MemberName (d.Name.Value, d.Name.Location), OptAttributes);
400 f.initializer = d.Initializer;
401 ((ConstInitializer) f.initializer).Name = d.Name.Value;
402 Parent.PartialContainer.Fields.Insert (++index, f);
406 // Create nested fixed buffer container
407 string name = String.Format ("<{0}>__FixedBuffer{1}", Name, GlobalCounter++);
408 fixed_buffer_type = Parent.TypeBuilder.DefineNestedType (name,
409 TypeAttributes.NestedPublic | TypeAttributes.Sealed | TypeAttributes.BeforeFieldInit,
410 Compiler.BuildinTypes.ValueType.GetMetaInfo ());
412 fixed_buffer_type.DefineField (FixedElementName, MemberType.GetMetaInfo (), FieldAttributes.Public);
414 FieldBuilder = Parent.TypeBuilder.DefineField (Name, fixed_buffer_type, ModifiersExtensions.FieldAttr (ModFlags));
415 var element_spec = new FieldSpec (null, this, MemberType, FieldBuilder, ModFlags);
416 spec = new FixedFieldSpec (Parent.Definition, this, FieldBuilder, element_spec, ModFlags);
418 Parent.MemberCache.AddMember (spec);
422 protected override void DoMemberTypeIndependentChecks ()
424 base.DoMemberTypeIndependentChecks ();
427 Expression.UnsafeError (Report, Location);
429 if (Parent.PartialContainer.Kind != MemberKind.Struct) {
430 Report.Error (1642, Location, "`{0}': Fixed size buffer fields may only be members of structs",
431 GetSignatureForError ());
435 public override void Emit()
437 ResolveContext rc = new ResolveContext (this);
438 IntConstant buffer_size_const = initializer.Resolve (rc) as IntConstant;
439 if (buffer_size_const == null)
442 int buffer_size = buffer_size_const.Value;
444 if (buffer_size <= 0) {
445 Report.Error (1665, Location, "`{0}': Fixed size buffers must have a length greater than zero", GetSignatureForError ());
449 int type_size = BuildinTypeSpec.GetSize (MemberType);
451 if (buffer_size > int.MaxValue / type_size) {
452 Report.Error (1664, Location, "Fixed size buffer `{0}' of length `{1}' and type `{2}' exceeded 2^31 limit",
453 GetSignatureForError (), buffer_size.ToString (), TypeManager.CSharpName (MemberType));
457 EmitFieldSize (buffer_size);
460 if (Module.HasDefaultCharSet)
461 fixed_buffer_type.__SetAttributes (fixed_buffer_type.Attributes | Module.DefaultCharSetType);
464 Module.PredefinedAttributes.UnsafeValueType.EmitAttribute (fixed_buffer_type);
465 Module.PredefinedAttributes.CompilerGenerated.EmitAttribute (fixed_buffer_type);
466 fixed_buffer_type.CreateType ();
471 void EmitFieldSize (int buffer_size)
473 PredefinedAttribute pa;
474 AttributeEncoder encoder;
476 pa = Module.PredefinedAttributes.StructLayout;
477 if (pa.Constructor == null && !pa.ResolveConstructor (Location, Compiler.BuildinTypes.Short))
480 var char_set_type = Module.PredefinedTypes.CharSet.Resolve (Location);
481 if (char_set_type == null)
484 var field_size = pa.GetField ("Size", Compiler.BuildinTypes.Int, Location);
485 var field_charset = pa.GetField ("CharSet", char_set_type, Location);
486 if (field_size == null || field_charset == null)
489 var char_set = CharSet ?? Module.DefaultCharSet ?? 0;
491 encoder = new AttributeEncoder ();
492 encoder.Encode ((short)LayoutKind.Sequential);
493 encoder.EncodeNamedArguments (
494 new [] { field_size, field_charset },
496 new IntConstant (Compiler.BuildinTypes, buffer_size, Location),
497 new IntConstant (Compiler.BuildinTypes, (int) char_set, Location)
501 pa.EmitAttribute (fixed_buffer_type, encoder);
504 // Don't emit FixedBufferAttribute attribute for private types
506 if ((ModFlags & Modifiers.PRIVATE) != 0)
509 pa = Module.PredefinedAttributes.FixedBuffer;
510 if (pa.Constructor == null && !pa.ResolveConstructor (Location, Compiler.BuildinTypes.Type, Compiler.BuildinTypes.Int))
513 encoder = new AttributeEncoder ();
514 encoder.EncodeTypeName (MemberType);
515 encoder.Encode (buffer_size);
516 encoder.EncodeEmptyNamedArguments ();
518 pa.EmitAttribute (FieldBuilder, encoder);
522 class FixedFieldSpec : FieldSpec
524 readonly FieldSpec element;
526 public FixedFieldSpec (TypeSpec declaringType, IMemberDefinition definition, FieldInfo info, FieldSpec element, Modifiers modifiers)
527 : base (declaringType, definition, element.MemberType, info, modifiers)
529 this.element = element;
531 // It's never CLS-Compliant
532 state &= ~StateFlags.CLSCompliant_Undetected;
535 public FieldSpec Element {
541 public TypeSpec ElementType {
549 // The Field class is used to represents class/struct fields during parsing.
551 public class Field : FieldBase {
553 // Modifiers allowed in a class declaration
555 const Modifiers AllowedModifiers =
558 Modifiers.PROTECTED |
566 public Field (DeclSpace parent, FullNamedExpression type, Modifiers mod, MemberName name,
568 : base (parent, type, mod, AllowedModifiers, name, attrs)
572 bool CanBeVolatile ()
574 if (TypeManager.IsReferenceType (MemberType))
577 switch (MemberType.BuildinType) {
578 case BuildinTypeSpec.Type.Bool:
579 case BuildinTypeSpec.Type.Char:
580 case BuildinTypeSpec.Type.SByte:
581 case BuildinTypeSpec.Type.Byte:
582 case BuildinTypeSpec.Type.Short:
583 case BuildinTypeSpec.Type.UShort:
584 case BuildinTypeSpec.Type.Int:
585 case BuildinTypeSpec.Type.UInt:
586 case BuildinTypeSpec.Type.Float:
587 case BuildinTypeSpec.Type.UIntPtr:
588 case BuildinTypeSpec.Type.IntPtr:
592 if (MemberType.IsEnum)
598 public override bool Define ()
603 MetaType[] required_modifier = null;
604 if ((ModFlags & Modifiers.VOLATILE) != 0) {
605 var mod = Module.PredefinedTypes.IsVolatile.Resolve (Location);
607 required_modifier = new MetaType[] { mod.GetMetaInfo () };
610 FieldBuilder = Parent.TypeBuilder.DefineField (
611 Name, member_type.GetMetaInfo (), required_modifier, null, ModifiersExtensions.FieldAttr (ModFlags));
613 spec = new FieldSpec (Parent.Definition, this, MemberType, FieldBuilder, ModFlags);
615 // Don't cache inaccessible fields
616 if ((ModFlags & Modifiers.BACKING_FIELD) == 0) {
617 Parent.MemberCache.AddMember (spec);
620 if (initializer != null) {
621 ((TypeContainer) Parent).RegisterFieldForInitialization (this,
622 new FieldInitializer (spec, initializer, this));
625 if (declarators != null) {
626 var t = new TypeExpression (MemberType, TypeExpression.Location);
627 int index = Parent.PartialContainer.Fields.IndexOf (this);
628 foreach (var d in declarators) {
629 var f = new Field (Parent, t, ModFlags, new MemberName (d.Name.Value, d.Name.Location), OptAttributes);
630 if (d.Initializer != null)
631 f.initializer = d.Initializer;
633 Parent.PartialContainer.Fields.Insert (++index, f);
640 protected override void DoMemberTypeDependentChecks ()
642 if ((ModFlags & Modifiers.BACKING_FIELD) != 0)
645 base.DoMemberTypeDependentChecks ();
647 if ((ModFlags & Modifiers.VOLATILE) != 0) {
648 if (!CanBeVolatile ()) {
649 Report.Error (677, Location, "`{0}': A volatile field cannot be of the type `{1}'",
650 GetSignatureForError (), TypeManager.CSharpName (MemberType));
653 if ((ModFlags & Modifiers.READONLY) != 0) {
654 Report.Error (678, Location, "`{0}': A field cannot be both volatile and readonly",
655 GetSignatureForError ());
660 protected override bool VerifyClsCompliance ()
662 if (!base.VerifyClsCompliance ())
665 if ((ModFlags & Modifiers.VOLATILE) != 0) {
666 Report.Warning (3026, 1, Location, "CLS-compliant field `{0}' cannot be volatile", GetSignatureForError ());