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.Reflection;
17 using System.Reflection.Emit;
18 using System.Runtime.InteropServices;
22 public class FieldDeclarator
24 public FieldDeclarator (SimpleMemberName name, Expression initializer)
27 this.Initializer = initializer;
32 public SimpleMemberName Name { get; private set; }
33 public Expression Initializer { get; private set; }
39 // Abstract class for all fields
41 abstract public class FieldBase : MemberBase
43 protected FieldBuilder FieldBuilder;
44 protected FieldSpec spec;
46 protected Expression initializer;
47 protected List<FieldDeclarator> declarators;
50 public enum Status : byte {
51 HAS_OFFSET = 4 // Used by FieldMember.
54 static readonly string[] attribute_targets = new string [] { "field" };
56 protected FieldBase (DeclSpace parent, FullNamedExpression type, Modifiers mod,
57 Modifiers allowed_mod, MemberName name, Attributes attrs)
58 : base (parent, null, type, mod, allowed_mod | Modifiers.ABSTRACT, Modifiers.PRIVATE,
61 if ((mod & Modifiers.ABSTRACT) != 0)
62 Report.Error (681, Location, "The modifier 'abstract' is not valid on fields. Try using a property instead");
67 public override AttributeTargets AttributeTargets {
69 return AttributeTargets.Field;
73 public Expression Initializer {
78 this.initializer = value;
82 public FieldSpec Spec {
88 public override string[] ValidAttributeTargets {
90 return attribute_targets;
96 public void AddDeclarator (FieldDeclarator declarator)
98 if (declarators == null)
99 declarators = new List<FieldDeclarator> (2);
101 declarators.Add (declarator);
103 // TODO: This will probably break
104 Parent.AddMember (this, declarator.Name.Value);
107 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
109 if (a.Type == pa.FieldOffset) {
110 status |= Status.HAS_OFFSET;
112 if (!Parent.PartialContainer.HasExplicitLayout) {
113 Report.Error (636, Location, "The FieldOffset attribute can only be placed on members of types marked with the StructLayout(LayoutKind.Explicit)");
117 if ((ModFlags & Modifiers.STATIC) != 0 || this is Const) {
118 Report.Error (637, Location, "The FieldOffset attribute is not allowed on static or const fields");
123 if (a.Type == pa.FixedBuffer) {
124 Report.Error (1716, Location, "Do not use 'System.Runtime.CompilerServices.FixedBuffer' attribute. Use the 'fixed' field modifier instead");
129 if (a.Type == pa.MarshalAs) {
130 UnmanagedMarshal marshal = a.GetMarshal (this);
131 if (marshal != null) {
132 FieldBuilder.SetMarshal (marshal);
137 if ((a.HasSecurityAttribute)) {
138 a.Error_InvalidSecurityParent ();
142 if (a.Type == pa.Dynamic) {
143 a.Error_MisusedDynamicAttribute ();
147 FieldBuilder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), cdata);
150 protected override bool CheckBase ()
152 if (!base.CheckBase ())
155 MemberSpec candidate;
156 var conflict_symbol = MemberCache.FindBaseMember (this, out candidate);
157 if (conflict_symbol == null)
158 conflict_symbol = candidate;
160 if (conflict_symbol == null) {
161 if ((ModFlags & Modifiers.NEW) != 0) {
162 Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required",
163 GetSignatureForError ());
166 if ((ModFlags & (Modifiers.NEW | Modifiers.OVERRIDE | Modifiers.BACKING_FIELD)) == 0) {
167 Report.SymbolRelatedToPreviousError (conflict_symbol);
168 Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
169 GetSignatureForError (), conflict_symbol.GetSignatureForError ());
172 if (conflict_symbol.IsAbstract) {
173 Report.SymbolRelatedToPreviousError (conflict_symbol);
174 Report.Error (533, Location, "`{0}' hides inherited abstract member `{1}'",
175 GetSignatureForError (), conflict_symbol.GetSignatureForError ());
182 public virtual Constant ConvertInitializer (ResolveContext rc, Constant expr)
184 return expr.ConvertImplicitly (rc, MemberType);
187 protected override void DoMemberTypeDependentChecks ()
189 base.DoMemberTypeDependentChecks ();
191 if (MemberType.IsGenericParameter)
194 if (MemberType.IsStatic)
195 Error_VariableOfStaticClass (Location, GetSignatureForError (), MemberType, Report);
202 // Represents header string for documentation comment.
204 public override string DocCommentHeader {
208 public override void Emit ()
210 if (member_type == InternalType.Dynamic) {
211 PredefinedAttributes.Get.Dynamic.EmitAttribute (FieldBuilder);
213 var trans_flags = TypeManager.HasDynamicTypeUsed (member_type);
214 if (trans_flags != null) {
215 var pa = PredefinedAttributes.Get.DynamicTransform;
216 if (pa.Constructor != null || pa.ResolveConstructor (Location, ArrayContainer.MakeType (TypeManager.bool_type, 1))) {
217 FieldBuilder.SetCustomAttribute (new CustomAttributeBuilder (pa.Constructor, new object[] { trans_flags }));
222 if ((ModFlags & Modifiers.COMPILER_GENERATED) != 0 && !Parent.IsCompilerGenerated)
223 PredefinedAttributes.Get.CompilerGenerated.EmitAttribute (FieldBuilder);
225 if (OptAttributes != null) {
226 OptAttributes.Emit ();
229 if (((status & Status.HAS_OFFSET) == 0) && (ModFlags & (Modifiers.STATIC | Modifiers.BACKING_FIELD)) == 0 && Parent.PartialContainer.HasExplicitLayout) {
230 Report.Error (625, Location, "`{0}': Instance field types marked with StructLayout(LayoutKind.Explicit) must have a FieldOffset attribute", GetSignatureForError ());
236 public static void Error_VariableOfStaticClass (Location loc, string variable_name, TypeSpec static_class, Report Report)
238 Report.SymbolRelatedToPreviousError (static_class);
239 Report.Error (723, loc, "`{0}': cannot declare variables of static types",
243 protected override bool VerifyClsCompliance ()
245 if (!base.VerifyClsCompliance ())
248 if (!MemberType.IsCLSCompliant () || this is FixedField) {
249 Report.Warning (3003, 1, Location, "Type of `{0}' is not CLS-compliant",
250 GetSignatureForError ());
257 // Field specification
259 public class FieldSpec : MemberSpec, IInterfaceMemberSpec
264 public FieldSpec (TypeSpec declaringType, IMemberDefinition definition, TypeSpec memberType, FieldInfo info, Modifiers modifiers)
265 : base (MemberKind.Field, declaringType, definition, modifiers)
267 this.metaInfo = info;
268 this.memberType = memberType;
273 public bool IsReadOnly {
275 return (Modifiers & Modifiers.READONLY) != 0;
279 public TypeSpec MemberType {
287 public FieldInfo GetMetaInfo ()
289 if ((state & StateFlags.PendingMetaInflate) != 0) {
290 var decl_meta = DeclaringType.GetMetaInfo ();
291 if (DeclaringType.IsTypeBuilder) {
292 metaInfo = TypeBuilder.GetField (decl_meta, metaInfo);
294 var orig_token = metaInfo.MetadataToken;
295 metaInfo = decl_meta.GetField (Name, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static);
296 if (metaInfo.MetadataToken != orig_token)
297 throw new NotImplementedException ("Resolved to wrong meta token");
299 // What a stupid API, does not work because field handle is imported
300 // metaInfo = FieldInfo.GetFieldFromHandle (metaInfo.FieldHandle, DeclaringType.MetaInfo.TypeHandle);
303 state &= ~StateFlags.PendingMetaInflate;
309 public override MemberSpec InflateMember (TypeParameterInflator inflator)
311 var fs = (FieldSpec) base.InflateMember (inflator);
312 fs.memberType = inflator.Inflate (memberType);
316 public FieldSpec Mutate (TypeParameterMutator mutator)
318 var decl = DeclaringType;
319 if (DeclaringType.IsGenericOrParentIsGeneric)
320 decl = mutator.Mutate (decl);
322 if (decl == DeclaringType)
325 var fs = (FieldSpec) MemberwiseClone ();
326 fs.declaringType = decl;
327 fs.state |= StateFlags.PendingMetaInflate;
329 // Gets back FieldInfo in case of metaInfo was inflated
330 fs.metaInfo = MemberCache.GetMember (DeclaringType.GetDefinition (), this).metaInfo;
336 /// Fixed buffer implementation
338 public class FixedField : FieldBase
340 public const string FixedElementName = "FixedElementField";
341 static int GlobalCounter = 0;
342 static object[] ctor_args = new object[] { (short)LayoutKind.Sequential };
343 static FieldInfo[] fi;
345 TypeBuilder fixed_buffer_type;
347 const Modifiers AllowedModifiers =
350 Modifiers.PROTECTED |
355 public FixedField (DeclSpace parent, FullNamedExpression type, Modifiers mod, MemberName name, Attributes attrs)
356 : base (parent, type, mod, AllowedModifiers, name, attrs)
360 public override Constant ConvertInitializer (ResolveContext rc, Constant expr)
362 return expr.ImplicitConversionRequired (rc, TypeManager.int32_type, Location);
365 public override bool Define ()
370 if (!TypeManager.IsPrimitiveType (MemberType)) {
371 Report.Error (1663, Location,
372 "`{0}': Fixed size buffers type must be one of the following: bool, byte, short, int, long, char, sbyte, ushort, uint, ulong, float or double",
373 GetSignatureForError ());
374 } else if (declarators != null) {
375 var t = new TypeExpression (MemberType, TypeExpression.Location);
376 int index = Parent.PartialContainer.Fields.IndexOf (this);
377 foreach (var d in declarators) {
378 var f = new FixedField (Parent, t, ModFlags, new MemberName (d.Name.Value, d.Name.Location), OptAttributes);
379 f.initializer = d.Initializer;
380 ((ConstInitializer) f.initializer).Name = d.Name.Value;
381 Parent.PartialContainer.Fields.Insert (++index, f);
385 // Create nested fixed buffer container
386 string name = String.Format ("<{0}>__FixedBuffer{1}", Name, GlobalCounter++);
387 fixed_buffer_type = Parent.TypeBuilder.DefineNestedType (name, Parent.Module.DefaultCharSetType |
388 TypeAttributes.NestedPublic | TypeAttributes.Sealed | TypeAttributes.BeforeFieldInit, TypeManager.value_type.GetMetaInfo ());
390 fixed_buffer_type.DefineField (FixedElementName, MemberType.GetMetaInfo (), FieldAttributes.Public);
391 RootContext.RegisterCompilerGeneratedType (fixed_buffer_type);
393 FieldBuilder = Parent.TypeBuilder.DefineField (Name, fixed_buffer_type, ModifiersExtensions.FieldAttr (ModFlags));
394 var element_spec = new FieldSpec (null, this, MemberType, FieldBuilder, ModFlags);
395 spec = new FixedFieldSpec (Parent.Definition, this, FieldBuilder, element_spec, ModFlags);
397 Parent.MemberCache.AddMember (spec);
401 protected override void DoMemberTypeIndependentChecks ()
403 base.DoMemberTypeIndependentChecks ();
406 Expression.UnsafeError (Report, Location);
408 if (Parent.PartialContainer.Kind != MemberKind.Struct) {
409 Report.Error (1642, Location, "`{0}': Fixed size buffer fields may only be members of structs",
410 GetSignatureForError ());
414 public override void Emit()
416 ResolveContext rc = new ResolveContext (this);
417 IntConstant buffer_size_const = initializer.Resolve (rc) as IntConstant;
418 if (buffer_size_const == null)
421 int buffer_size = buffer_size_const.Value;
423 if (buffer_size <= 0) {
424 Report.Error (1665, Location, "`{0}': Fixed size buffers must have a length greater than zero", GetSignatureForError ());
428 int type_size = Expression.GetTypeSize (MemberType);
430 if (buffer_size > int.MaxValue / type_size) {
431 Report.Error (1664, Location, "Fixed size buffer `{0}' of length `{1}' and type `{2}' exceeded 2^31 limit",
432 GetSignatureForError (), buffer_size.ToString (), TypeManager.CSharpName (MemberType));
436 buffer_size *= type_size;
437 EmitFieldSize (buffer_size);
439 PredefinedAttributes.Get.UnsafeValueType.EmitAttribute (fixed_buffer_type);
444 void EmitFieldSize (int buffer_size)
446 CustomAttributeBuilder cab;
447 PredefinedAttribute pa;
449 pa = PredefinedAttributes.Get.StructLayout;
450 if (pa.Constructor == null &&
451 !pa.ResolveConstructor (Location, TypeManager.short_type))
454 // TODO: It's not cleared
456 var field = (FieldSpec) MemberCache.FindMember (pa.Type, MemberFilter.Field ("Size", null), BindingRestriction.DeclaredOnly);
457 fi = new FieldInfo[] { field.GetMetaInfo () };
460 object[] fi_val = new object[] { buffer_size };
461 cab = new CustomAttributeBuilder (pa.Constructor,
462 ctor_args, fi, fi_val);
463 fixed_buffer_type.SetCustomAttribute (cab);
466 // Don't emit FixedBufferAttribute attribute for private types
468 if ((ModFlags & Modifiers.PRIVATE) != 0)
471 pa = PredefinedAttributes.Get.FixedBuffer;
472 if (pa.Constructor == null &&
473 !pa.ResolveConstructor (Location, TypeManager.type_type, TypeManager.int32_type))
476 cab = new CustomAttributeBuilder (pa.Constructor, new object[] { MemberType.GetMetaInfo (), buffer_size });
477 FieldBuilder.SetCustomAttribute (cab);
480 public void SetCharSet (TypeAttributes ta)
482 TypeAttributes cta = fixed_buffer_type.Attributes;
483 if ((cta & TypeAttributes.UnicodeClass) != (ta & TypeAttributes.UnicodeClass))
484 SetTypeBuilderCharSet ((cta & ~TypeAttributes.AutoClass) | TypeAttributes.UnicodeClass);
485 else if ((cta & TypeAttributes.AutoClass) != (ta & TypeAttributes.AutoClass))
486 SetTypeBuilderCharSet ((cta & ~TypeAttributes.UnicodeClass) | TypeAttributes.AutoClass);
487 else if (cta == 0 && ta != 0)
488 SetTypeBuilderCharSet (cta & ~(TypeAttributes.UnicodeClass | TypeAttributes.AutoClass));
491 void SetTypeBuilderCharSet (TypeAttributes ta)
493 MethodInfo mi = typeof (TypeBuilder).GetMethod ("SetCharSet", BindingFlags.Instance | BindingFlags.NonPublic);
495 Report.RuntimeMissingSupport (Location, "TypeBuilder::SetCharSet");
497 mi.Invoke (fixed_buffer_type, new object [] { ta });
502 class FixedFieldSpec : FieldSpec
504 readonly FieldSpec element;
506 public FixedFieldSpec (TypeSpec declaringType, IMemberDefinition definition, FieldInfo info, FieldSpec element, Modifiers modifiers)
507 : base (declaringType, definition, element.MemberType, info, modifiers)
509 this.element = element;
511 // It's never CLS-Compliant
512 state &= ~StateFlags.CLSCompliant_Undetected;
515 public FieldSpec Element {
521 public TypeSpec ElementType {
529 // The Field class is used to represents class/struct fields during parsing.
531 public class Field : FieldBase {
533 // Modifiers allowed in a class declaration
535 const Modifiers AllowedModifiers =
538 Modifiers.PROTECTED |
546 public Field (DeclSpace parent, FullNamedExpression type, Modifiers mod, MemberName name,
548 : base (parent, type, mod, AllowedModifiers, name, attrs)
552 bool CanBeVolatile ()
554 if (TypeManager.IsReferenceType (MemberType))
557 if (MemberType == TypeManager.bool_type || MemberType == TypeManager.char_type ||
558 MemberType == TypeManager.sbyte_type || MemberType == TypeManager.byte_type ||
559 MemberType == TypeManager.short_type || MemberType == TypeManager.ushort_type ||
560 MemberType == TypeManager.int32_type || MemberType == TypeManager.uint32_type ||
561 MemberType == TypeManager.float_type ||
562 MemberType == TypeManager.intptr_type || MemberType == TypeManager.uintptr_type)
565 if (MemberType.IsEnum)
571 public override bool Define ()
577 Type[] required_modifier = null;
578 if ((ModFlags & Modifiers.VOLATILE) != 0) {
579 if (TypeManager.isvolatile_type == null)
580 TypeManager.isvolatile_type = TypeManager.CoreLookupType (Compiler,
581 "System.Runtime.CompilerServices", "IsVolatile", MemberKind.Class, true);
583 if (TypeManager.isvolatile_type != null)
584 required_modifier = new Type[] { TypeManager.isvolatile_type.GetMetaInfo () };
587 FieldBuilder = Parent.TypeBuilder.DefineField (
588 Name, member_type.GetMetaInfo (), required_modifier, null, ModifiersExtensions.FieldAttr (ModFlags));
590 spec = new FieldSpec (Parent.Definition, this, MemberType, FieldBuilder, ModFlags);
592 // Don't cache inaccessible fields
593 if ((ModFlags & Modifiers.BACKING_FIELD) == 0) {
594 Parent.MemberCache.AddMember (spec);
597 if (initializer != null) {
598 ((TypeContainer) Parent).RegisterFieldForInitialization (this,
599 new FieldInitializer (spec, initializer, this));
601 } catch (ArgumentException) {
602 Report.RuntimeMissingSupport (Location, "`void' or `void*' field type");
606 if (declarators != null) {
607 var t = new TypeExpression (MemberType, TypeExpression.Location);
608 int index = Parent.PartialContainer.Fields.IndexOf (this);
609 foreach (var d in declarators) {
610 var f = new Field (Parent, t, ModFlags, new MemberName (d.Name.Value, d.Name.Location), OptAttributes);
611 if (d.Initializer != null)
612 f.initializer = d.Initializer;
614 Parent.PartialContainer.Fields.Insert (++index, f);
621 protected override void DoMemberTypeDependentChecks ()
623 if ((ModFlags & Modifiers.BACKING_FIELD) != 0)
626 base.DoMemberTypeDependentChecks ();
628 if ((ModFlags & Modifiers.VOLATILE) != 0) {
629 if (!CanBeVolatile ()) {
630 Report.Error (677, Location, "`{0}': A volatile field cannot be of the type `{1}'",
631 GetSignatureForError (), TypeManager.CSharpName (MemberType));
634 if ((ModFlags & Modifiers.READONLY) != 0) {
635 Report.Error (678, Location, "`{0}': A field cannot be both volatile and readonly",
636 GetSignatureForError ());
641 protected override bool VerifyClsCompliance ()
643 if (!base.VerifyClsCompliance ())
646 if ((ModFlags & Modifiers.VOLATILE) != 0) {
647 Report.Warning (3026, 1, Location, "CLS-compliant field `{0}' cannot be volatile", GetSignatureForError ());