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; }
46 public virtual FullNamedExpression GetFieldTypeExpression (FieldBase field)
48 return new TypeExpression (field.MemberType, Name.Location);
53 // Abstract class for all fields
55 abstract public class FieldBase : MemberBase
57 protected FieldBuilder FieldBuilder;
58 protected FieldSpec spec;
60 protected Expression initializer;
61 protected List<FieldDeclarator> declarators;
64 public enum Status : byte {
65 HAS_OFFSET = 4 // Used by FieldMember.
68 static readonly string[] attribute_targets = new string [] { "field" };
70 protected FieldBase (TypeDefinition parent, FullNamedExpression type, Modifiers mod, Modifiers allowed_mod, MemberName name, Attributes attrs)
71 : base (parent, type, mod, allowed_mod | Modifiers.ABSTRACT, Modifiers.PRIVATE, name, attrs)
73 if ((mod & Modifiers.ABSTRACT) != 0)
74 Report.Error (681, Location, "The modifier 'abstract' is not valid on fields. Try using a property instead");
79 public override AttributeTargets AttributeTargets {
81 return AttributeTargets.Field;
85 public List<FieldDeclarator> Declarators {
87 return this.declarators;
91 public Expression Initializer {
96 this.initializer = value;
102 return MemberName.Name;
106 public FieldSpec Spec {
112 public override string[] ValidAttributeTargets {
114 return attribute_targets;
120 public void AddDeclarator (FieldDeclarator declarator)
122 if (declarators == null)
123 declarators = new List<FieldDeclarator> (2);
125 declarators.Add (declarator);
127 Parent.AddNameToContainer (this, declarator.Name.Value);
130 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
132 if (a.Type == pa.FieldOffset) {
133 status |= Status.HAS_OFFSET;
135 if (!Parent.PartialContainer.HasExplicitLayout) {
136 Report.Error (636, Location, "The FieldOffset attribute can only be placed on members of types marked with the StructLayout(LayoutKind.Explicit)");
140 if ((ModFlags & Modifiers.STATIC) != 0 || this is Const) {
141 Report.Error (637, Location, "The FieldOffset attribute is not allowed on static or const fields");
146 if (a.Type == pa.FixedBuffer) {
147 Report.Error (1716, Location, "Do not use 'System.Runtime.CompilerServices.FixedBuffer' attribute. Use the 'fixed' field modifier instead");
152 if (a.Type == pa.MarshalAs) {
153 UnmanagedMarshal marshal = a.GetMarshal (this);
154 if (marshal != null) {
155 FieldBuilder.SetMarshal (marshal);
160 if ((a.HasSecurityAttribute)) {
161 a.Error_InvalidSecurityParent ();
165 if (a.Type == pa.Dynamic) {
166 a.Error_MisusedDynamicAttribute ();
170 FieldBuilder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), cdata);
173 public void SetCustomAttribute (MethodSpec ctor, byte[] data)
175 FieldBuilder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), data);
178 protected override bool CheckBase ()
180 if (!base.CheckBase ())
183 MemberSpec candidate;
184 bool overrides = false;
185 var conflict_symbol = MemberCache.FindBaseMember (this, out candidate, ref overrides);
186 if (conflict_symbol == null)
187 conflict_symbol = candidate;
189 if (conflict_symbol == null) {
190 if ((ModFlags & Modifiers.NEW) != 0) {
191 Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required",
192 GetSignatureForError ());
195 if ((ModFlags & (Modifiers.NEW | Modifiers.OVERRIDE | Modifiers.BACKING_FIELD)) == 0) {
196 Report.SymbolRelatedToPreviousError (conflict_symbol);
197 Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
198 GetSignatureForError (), conflict_symbol.GetSignatureForError ());
201 if (conflict_symbol.IsAbstract) {
202 Report.SymbolRelatedToPreviousError (conflict_symbol);
203 Report.Error (533, Location, "`{0}' hides inherited abstract member `{1}'",
204 GetSignatureForError (), conflict_symbol.GetSignatureForError ());
211 public virtual Constant ConvertInitializer (ResolveContext rc, Constant expr)
213 return expr.ConvertImplicitly (MemberType);
216 protected override void DoMemberTypeDependentChecks ()
218 base.DoMemberTypeDependentChecks ();
220 if (MemberType.IsGenericParameter)
223 if (MemberType.IsStatic)
224 Error_VariableOfStaticClass (Location, GetSignatureForError (), MemberType, Report);
226 if (!IsCompilerGenerated)
233 // Represents header string for documentation comment.
235 public override string DocCommentHeader {
239 public override void Emit ()
241 if (member_type.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
242 Module.PredefinedAttributes.Dynamic.EmitAttribute (FieldBuilder);
243 } else if (!Parent.IsCompilerGenerated && member_type.HasDynamicElement) {
244 Module.PredefinedAttributes.Dynamic.EmitAttribute (FieldBuilder, member_type, Location);
247 if ((ModFlags & Modifiers.COMPILER_GENERATED) != 0 && !Parent.IsCompilerGenerated)
248 Module.PredefinedAttributes.CompilerGenerated.EmitAttribute (FieldBuilder);
249 if ((ModFlags & Modifiers.DEBUGGER_HIDDEN) != 0)
250 Module.PredefinedAttributes.DebuggerBrowsable.EmitAttribute (FieldBuilder, System.Diagnostics.DebuggerBrowsableState.Never);
252 if (OptAttributes != null) {
253 OptAttributes.Emit ();
256 if (((status & Status.HAS_OFFSET) == 0) && (ModFlags & (Modifiers.STATIC | Modifiers.BACKING_FIELD)) == 0 && Parent.PartialContainer.HasExplicitLayout) {
257 Report.Error (625, Location, "`{0}': Instance field types marked with StructLayout(LayoutKind.Explicit) must have a FieldOffset attribute", GetSignatureForError ());
260 if (!IsCompilerGenerated)
261 ConstraintChecker.Check (this, member_type, type_expr.Location);
266 public static void Error_VariableOfStaticClass (Location loc, string variable_name, TypeSpec static_class, Report Report)
268 Report.SymbolRelatedToPreviousError (static_class);
269 Report.Error (723, loc, "`{0}': cannot declare variables of static types",
273 protected override bool VerifyClsCompliance ()
275 if (!base.VerifyClsCompliance ())
278 if (!MemberType.IsCLSCompliant () || this is FixedField) {
279 Report.Warning (3003, 1, Location, "Type of `{0}' is not CLS-compliant",
280 GetSignatureForError ());
287 // Field specification
289 public class FieldSpec : MemberSpec, IInterfaceMemberSpec
294 public FieldSpec (TypeSpec declaringType, IMemberDefinition definition, TypeSpec memberType, FieldInfo info, Modifiers modifiers)
295 : base (MemberKind.Field, declaringType, definition, modifiers)
297 this.metaInfo = info;
298 this.memberType = memberType;
303 public bool IsReadOnly {
305 return (Modifiers & Modifiers.READONLY) != 0;
309 public TypeSpec MemberType {
317 public FieldInfo GetMetaInfo ()
319 if ((state & StateFlags.PendingMetaInflate) != 0) {
320 var decl_meta = DeclaringType.GetMetaInfo ();
321 if (DeclaringType.IsTypeBuilder) {
322 metaInfo = TypeBuilder.GetField (decl_meta, metaInfo);
324 var orig_token = metaInfo.MetadataToken;
325 metaInfo = decl_meta.GetField (Name, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static);
326 if (metaInfo.MetadataToken != orig_token)
327 throw new NotImplementedException ("Resolved to wrong meta token");
329 // What a stupid API, does not work because field handle is imported
330 // metaInfo = FieldInfo.GetFieldFromHandle (metaInfo.FieldHandle, DeclaringType.MetaInfo.TypeHandle);
333 state &= ~StateFlags.PendingMetaInflate;
339 public override MemberSpec InflateMember (TypeParameterInflator inflator)
341 var fs = (FieldSpec) base.InflateMember (inflator);
342 fs.memberType = inflator.Inflate (memberType);
346 public FieldSpec Mutate (TypeParameterMutator mutator)
348 var decl = DeclaringType;
349 if (DeclaringType.IsGenericOrParentIsGeneric)
350 decl = mutator.Mutate (decl);
352 if (decl == DeclaringType)
355 var fs = (FieldSpec) MemberwiseClone ();
356 fs.declaringType = decl;
357 fs.state |= StateFlags.PendingMetaInflate;
359 // Gets back FieldInfo in case of metaInfo was inflated
360 fs.metaInfo = MemberCache.GetMember (TypeParameterMutator.GetMemberDeclaringType (DeclaringType), this).metaInfo;
364 public override List<MissingTypeSpecReference> ResolveMissingDependencies (MemberSpec caller)
366 return memberType.ResolveMissingDependencies (this);
371 /// Fixed buffer implementation
373 public class FixedField : FieldBase
375 public const string FixedElementName = "FixedElementField";
376 static int GlobalCounter;
378 TypeBuilder fixed_buffer_type;
380 const Modifiers AllowedModifiers =
383 Modifiers.PROTECTED |
388 public FixedField (TypeDefinition parent, FullNamedExpression type, Modifiers mod, MemberName name, Attributes attrs)
389 : base (parent, type, mod, AllowedModifiers, name, attrs)
396 // Explicit struct layout set by parent
398 public CharSet? CharSetValue {
404 public override Constant ConvertInitializer (ResolveContext rc, Constant expr)
406 return expr.ImplicitConversionRequired (rc, rc.BuiltinTypes.Int);
409 public override bool Define ()
414 if (!BuiltinTypeSpec.IsPrimitiveType (MemberType)) {
415 Report.Error (1663, Location,
416 "`{0}': Fixed size buffers type must be one of the following: bool, byte, short, int, long, char, sbyte, ushort, uint, ulong, float or double",
417 GetSignatureForError ());
418 } else if (declarators != null) {
419 foreach (var d in declarators) {
420 var f = new FixedField (Parent, d.GetFieldTypeExpression (this), ModFlags, new MemberName (d.Name.Value, d.Name.Location), OptAttributes);
421 f.initializer = d.Initializer;
422 ((ConstInitializer) f.initializer).Name = d.Name.Value;
424 Parent.PartialContainer.Members.Add (f);
428 // Create nested fixed buffer container
429 string name = String.Format ("<{0}>__FixedBuffer{1}", TypeDefinition.FilterNestedName (Name), GlobalCounter++);
430 fixed_buffer_type = Parent.TypeBuilder.DefineNestedType (name,
431 TypeAttributes.NestedPublic | TypeAttributes.Sealed | TypeAttributes.BeforeFieldInit,
432 Compiler.BuiltinTypes.ValueType.GetMetaInfo ());
434 var ffield = fixed_buffer_type.DefineField (FixedElementName, MemberType.GetMetaInfo (), FieldAttributes.Public);
436 FieldBuilder = Parent.TypeBuilder.DefineField (Name, fixed_buffer_type, ModifiersExtensions.FieldAttr (ModFlags));
438 var element_spec = new FieldSpec (null, this, MemberType, ffield, ModFlags);
439 spec = new FixedFieldSpec (Module, Parent.Definition, this, FieldBuilder, element_spec, ModFlags);
441 Parent.MemberCache.AddMember (spec);
445 protected override void DoMemberTypeIndependentChecks ()
447 base.DoMemberTypeIndependentChecks ();
450 Expression.UnsafeError (Report, Location);
452 if (Parent.PartialContainer.Kind != MemberKind.Struct) {
453 Report.Error (1642, Location, "`{0}': Fixed size buffer fields may only be members of structs",
454 GetSignatureForError ());
458 public override void Emit()
460 ResolveContext rc = new ResolveContext (this);
461 IntConstant buffer_size_const = initializer.Resolve (rc) as IntConstant;
462 if (buffer_size_const == null)
465 int buffer_size = buffer_size_const.Value;
467 if (buffer_size <= 0) {
468 Report.Error (1665, Location, "`{0}': Fixed size buffers must have a length greater than zero", GetSignatureForError ());
472 EmitFieldSize (buffer_size);
475 if (Module.HasDefaultCharSet)
476 fixed_buffer_type.__SetAttributes (fixed_buffer_type.Attributes | Module.DefaultCharSetType);
479 Module.PredefinedAttributes.UnsafeValueType.EmitAttribute (fixed_buffer_type);
480 Module.PredefinedAttributes.CompilerGenerated.EmitAttribute (fixed_buffer_type);
481 fixed_buffer_type.CreateType ();
486 void EmitFieldSize (int buffer_size)
488 int type_size = BuiltinTypeSpec.GetSize (MemberType);
490 if (buffer_size > int.MaxValue / type_size) {
491 Report.Error (1664, Location, "Fixed size buffer `{0}' of length `{1}' and type `{2}' exceeded 2^31 limit",
492 GetSignatureForError (), buffer_size.ToString (), MemberType.GetSignatureForError ());
496 AttributeEncoder encoder;
499 var char_set = CharSetValue ?? Module.DefaultCharSet ?? 0;
502 // Set struct layout without resolving StructLayoutAttribute which is not always available
505 TypeAttributes attribs = TypeAttributes.SequentialLayout;
509 attribs |= TypeAttributes.AnsiClass;
512 attribs |= TypeAttributes.AutoClass;
514 case CharSet.Unicode:
515 attribs |= TypeAttributes.UnicodeClass;
519 fixed_buffer_type.__SetAttributes (fixed_buffer_type.Attributes | attribs);
520 fixed_buffer_type.__SetLayout (0, buffer_size * type_size);
522 ctor = Module.PredefinedMembers.StructLayoutAttributeCtor.Resolve (Location);
526 var field_size = Module.PredefinedMembers.StructLayoutSize.Resolve (Location);
527 var field_charset = Module.PredefinedMembers.StructLayoutCharSet.Resolve (Location);
528 if (field_size == null || field_charset == null)
531 encoder = new AttributeEncoder ();
532 encoder.Encode ((short)LayoutKind.Sequential);
533 encoder.EncodeNamedArguments (
534 new [] { field_size, field_charset },
536 new IntConstant (Compiler.BuiltinTypes, buffer_size * type_size, Location),
537 new IntConstant (Compiler.BuiltinTypes, (int) char_set, Location)
541 fixed_buffer_type.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), encoder.ToArray ());
544 // Don't emit FixedBufferAttribute attribute for private types
546 if ((ModFlags & Modifiers.PRIVATE) != 0)
549 ctor = Module.PredefinedMembers.FixedBufferAttributeCtor.Resolve (Location);
553 encoder = new AttributeEncoder ();
554 encoder.EncodeTypeName (MemberType);
555 encoder.Encode (buffer_size);
556 encoder.EncodeEmptyNamedArguments ();
558 FieldBuilder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), encoder.ToArray ());
562 class FixedFieldSpec : FieldSpec
564 readonly FieldSpec element;
566 public FixedFieldSpec (ModuleContainer module, TypeSpec declaringType, IMemberDefinition definition, FieldInfo info, FieldSpec element, Modifiers modifiers)
567 : base (declaringType, definition, PointerContainer.MakeType (module, element.MemberType), info, modifiers)
569 this.element = element;
571 // It's never CLS-Compliant
572 state &= ~StateFlags.CLSCompliant_Undetected;
575 public FieldSpec Element {
581 public TypeSpec ElementType {
583 return element.MemberType;
589 // The Field class is used to represents class/struct fields during parsing.
591 public class Field : FieldBase {
593 // Modifiers allowed in a class declaration
595 const Modifiers AllowedModifiers =
598 Modifiers.PROTECTED |
606 public Field (TypeDefinition parent, FullNamedExpression type, Modifiers mod, MemberName name, Attributes attrs)
607 : base (parent, type, mod, AllowedModifiers, name, attrs)
611 bool CanBeVolatile ()
613 switch (MemberType.BuiltinType) {
614 case BuiltinTypeSpec.Type.Bool:
615 case BuiltinTypeSpec.Type.Char:
616 case BuiltinTypeSpec.Type.SByte:
617 case BuiltinTypeSpec.Type.Byte:
618 case BuiltinTypeSpec.Type.Short:
619 case BuiltinTypeSpec.Type.UShort:
620 case BuiltinTypeSpec.Type.Int:
621 case BuiltinTypeSpec.Type.UInt:
622 case BuiltinTypeSpec.Type.Float:
623 case BuiltinTypeSpec.Type.UIntPtr:
624 case BuiltinTypeSpec.Type.IntPtr:
628 if (TypeSpec.IsReferenceType (MemberType))
631 if (MemberType.IsPointer)
634 if (MemberType.IsEnum) {
635 switch (EnumSpec.GetUnderlyingType (MemberType).BuiltinType) {
636 case BuiltinTypeSpec.Type.SByte:
637 case BuiltinTypeSpec.Type.Byte:
638 case BuiltinTypeSpec.Type.Short:
639 case BuiltinTypeSpec.Type.UShort:
640 case BuiltinTypeSpec.Type.Int:
641 case BuiltinTypeSpec.Type.UInt:
651 public override void Accept (StructuralVisitor visitor)
653 visitor.Visit (this);
656 public override bool Define ()
661 MetaType[] required_modifier = null;
662 if ((ModFlags & Modifiers.VOLATILE) != 0) {
663 var mod = Module.PredefinedTypes.IsVolatile.Resolve ();
665 required_modifier = new MetaType[] { mod.GetMetaInfo () };
668 FieldBuilder = Parent.TypeBuilder.DefineField (
669 Name, member_type.GetMetaInfo (), required_modifier, null, ModifiersExtensions.FieldAttr (ModFlags));
671 spec = new FieldSpec (Parent.Definition, this, MemberType, FieldBuilder, ModFlags);
674 // Don't cache inaccessible fields except for struct where we
675 // need them for definitive assignment checks
677 if ((ModFlags & Modifiers.BACKING_FIELD) == 0 || Parent.Kind == MemberKind.Struct) {
678 Parent.MemberCache.AddMember (spec);
681 if (initializer != null) {
682 Parent.RegisterFieldForInitialization (this, new FieldInitializer (this, initializer, TypeExpression.Location));
685 if (declarators != null) {
686 foreach (var d in declarators) {
687 var f = new Field (Parent, d.GetFieldTypeExpression (this), ModFlags, new MemberName (d.Name.Value, d.Name.Location), OptAttributes);
688 if (d.Initializer != null)
689 f.initializer = d.Initializer;
692 Parent.PartialContainer.Members.Add (f);
699 protected override void DoMemberTypeDependentChecks ()
701 if ((ModFlags & Modifiers.BACKING_FIELD) != 0)
704 base.DoMemberTypeDependentChecks ();
706 if ((ModFlags & Modifiers.VOLATILE) != 0) {
707 if (!CanBeVolatile ()) {
708 Report.Error (677, Location, "`{0}': A volatile field cannot be of the type `{1}'",
709 GetSignatureForError (), MemberType.GetSignatureForError ());
712 if ((ModFlags & Modifiers.READONLY) != 0) {
713 Report.Error (678, Location, "`{0}': A field cannot be both volatile and readonly",
714 GetSignatureForError ());
719 protected override bool VerifyClsCompliance ()
721 if (!base.VerifyClsCompliance ())
724 if ((ModFlags & Modifiers.VOLATILE) != 0) {
725 Report.Warning (3026, 1, Location, "CLS-compliant field `{0}' cannot be volatile", GetSignatureForError ());
732 class PrimaryConstructorField : Field
735 // Proxy resolved parameter type expression to avoid type double resolve
736 // and problems with correct resolve context on partial classes
738 sealed class TypeExpressionFromParameter : TypeExpr
742 public TypeExpressionFromParameter (Parameter parameter)
744 this.parameter = parameter;
745 eclass = ExprClass.Type;
746 loc = parameter.Location;
749 public override TypeSpec ResolveAsType (IMemberContext mc, bool allowUnboundTypeArguments)
751 return parameter.Type;
755 public PrimaryConstructorField (TypeDefinition parent, Parameter parameter)
756 : base (parent, new TypeExpressionFromParameter (parameter), Modifiers.PRIVATE, new MemberName (parameter.Name, parameter.Location), null)
758 caching_flags |= Flags.IsUsed | Flags.IsAssigned;
761 public override string GetSignatureForError ()
763 return MemberName.Name;