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;
23 // Abstract class for all fields
25 abstract public class FieldBase : MemberBase
27 public FieldBuilder FieldBuilder;
28 protected FieldSpec spec;
30 protected Expression initializer;
33 public enum Status : byte {
34 HAS_OFFSET = 4 // Used by FieldMember.
37 static readonly string[] attribute_targets = new string [] { "field" };
39 protected FieldBase (DeclSpace parent, FullNamedExpression type, Modifiers mod,
40 Modifiers allowed_mod, MemberName name, Attributes attrs)
41 : base (parent, null, type, mod, allowed_mod | Modifiers.ABSTRACT, Modifiers.PRIVATE,
44 if ((mod & Modifiers.ABSTRACT) != 0)
45 Report.Error (681, Location, "The modifier 'abstract' is not valid on fields. Try using a property instead");
48 public override AttributeTargets AttributeTargets {
50 return AttributeTargets.Field;
54 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb, PredefinedAttributes pa)
56 if (a.Type == pa.FieldOffset) {
57 status |= Status.HAS_OFFSET;
59 if (!Parent.PartialContainer.HasExplicitLayout) {
60 Report.Error (636, Location, "The FieldOffset attribute can only be placed on members of types marked with the StructLayout(LayoutKind.Explicit)");
64 if ((ModFlags & Modifiers.STATIC) != 0 || this is Const) {
65 Report.Error (637, Location, "The FieldOffset attribute is not allowed on static or const fields");
70 if (a.Type == pa.FixedBuffer) {
71 Report.Error (1716, Location, "Do not use 'System.Runtime.CompilerServices.FixedBuffer' attribute. Use the 'fixed' field modifier instead");
76 if (a.Type == pa.MarshalAs) {
77 UnmanagedMarshal marshal = a.GetMarshal (this);
78 if (marshal != null) {
79 FieldBuilder.SetMarshal (marshal);
84 if ((a.HasSecurityAttribute)) {
85 a.Error_InvalidSecurityParent ();
89 if (a.Type == pa.Dynamic) {
90 a.Error_MisusedDynamicAttribute ();
94 FieldBuilder.SetCustomAttribute (cb);
97 protected override bool CheckBase ()
99 if (!base.CheckBase ())
102 MemberInfo conflict_symbol = Parent.PartialContainer.FindBaseMemberWithSameName (Name, false);
103 if (conflict_symbol == null) {
104 if ((ModFlags & Modifiers.NEW) != 0) {
105 Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
110 if ((ModFlags & (Modifiers.NEW | Modifiers.OVERRIDE | Modifiers.BACKING_FIELD)) == 0) {
111 Report.SymbolRelatedToPreviousError (conflict_symbol);
112 Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
113 GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
119 public virtual Constant ConvertInitializer (ResolveContext rc, Constant expr)
121 return expr.ConvertImplicitly (rc, MemberType);
124 protected override void DoMemberTypeDependentChecks ()
126 base.DoMemberTypeDependentChecks ();
128 if (TypeManager.IsGenericParameter (MemberType))
131 if (MemberType.IsSealed && MemberType.IsAbstract) {
132 Error_VariableOfStaticClass (Location, GetSignatureForError (), MemberType, Report);
140 // Represents header string for documentation comment.
142 public override string DocCommentHeader {
146 public override void Emit ()
148 if (TypeManager.IsDynamicType (member_type)) {
149 PredefinedAttributes.Get.Dynamic.EmitAttribute (FieldBuilder);
151 var trans_flags = TypeManager.HasDynamicTypeUsed (member_type);
152 if (trans_flags != null) {
153 var pa = PredefinedAttributes.Get.DynamicTransform;
154 if (pa.Constructor != null || pa.ResolveConstructor (Location, TypeManager.bool_type.MakeArrayType ())) {
155 FieldBuilder.SetCustomAttribute (new CustomAttributeBuilder (pa.Constructor, new object[] { trans_flags }));
160 if ((ModFlags & Modifiers.COMPILER_GENERATED) != 0 && !Parent.IsCompilerGenerated)
161 PredefinedAttributes.Get.CompilerGenerated.EmitAttribute (FieldBuilder);
163 if (OptAttributes != null) {
164 OptAttributes.Emit ();
167 if (((status & Status.HAS_OFFSET) == 0) && (ModFlags & (Modifiers.STATIC | Modifiers.BACKING_FIELD)) == 0 && Parent.PartialContainer.HasExplicitLayout) {
168 Report.Error (625, Location, "`{0}': Instance field types marked with StructLayout(LayoutKind.Explicit) must have a FieldOffset attribute", GetSignatureForError ());
174 public static void Error_VariableOfStaticClass (Location loc, string variable_name, Type static_class, Report Report)
176 Report.SymbolRelatedToPreviousError (static_class);
177 Report.Error (723, loc, "`{0}': cannot declare variables of static types",
181 public Expression Initializer {
187 this.initializer = value;
192 protected virtual bool IsFieldClsCompliant {
194 if (FieldBuilder == null)
197 return AttributeTester.IsClsCompliant (FieldBuilder.FieldType);
201 public FieldSpec Spec {
205 public override string[] ValidAttributeTargets
208 return attribute_targets;
212 protected override bool VerifyClsCompliance ()
214 if (!base.VerifyClsCompliance ())
217 if (!IsFieldClsCompliant) {
218 Report.Warning (3003, 1, Location, "Type of `{0}' is not CLS-compliant",
219 GetSignatureForError ());
224 public void SetAssigned ()
226 caching_flags |= Flags.IsAssigned;
231 // Field specification
233 public class FieldSpec : MemberSpec
237 public FieldSpec (IMemberDefinition definition, FieldInfo info, Modifiers modifiers)
238 : base (MemberKind.Field, definition, info.Name, modifiers)
243 public bool IsReadOnly {
244 get { return (modifiers & Modifiers.READONLY) != 0; }
247 public FieldInfo MetaInfo {
256 public override Type DeclaringType {
258 return MetaInfo.DeclaringType;
263 public Type FieldType {
265 return MetaInfo.FieldType;
271 /// Fixed buffer implementation
273 public class FixedField : FieldBase
275 public const string FixedElementName = "FixedElementField";
276 static int GlobalCounter = 0;
277 static object[] ctor_args = new object[] { (short)LayoutKind.Sequential };
278 static FieldInfo[] fi;
280 TypeBuilder fixed_buffer_type;
282 const Modifiers AllowedModifiers =
285 Modifiers.PROTECTED |
290 public FixedField (DeclSpace parent, FullNamedExpression type, Modifiers mod, string name,
291 Expression size_expr, Attributes attrs, Location loc):
292 base (parent, type, mod, AllowedModifiers, new MemberName (name, loc), attrs)
294 if (RootContext.Version < LanguageVersion.ISO_2)
295 Report.FeatureIsNotAvailable (loc, "fixed size buffers");
297 initializer = new ConstInitializer (this, size_expr);
300 public override Constant ConvertInitializer (ResolveContext rc, Constant expr)
302 return expr.ImplicitConversionRequired (rc, TypeManager.int32_type, Location);
305 public override bool Define ()
310 if (!TypeManager.IsPrimitiveType (MemberType)) {
311 Report.Error (1663, Location,
312 "`{0}': Fixed size buffers type must be one of the following: bool, byte, short, int, long, char, sbyte, ushort, uint, ulong, float or double",
313 GetSignatureForError ());
316 // Create nested fixed buffer container
317 string name = String.Format ("<{0}>__FixedBuffer{1}", Name, GlobalCounter++);
318 fixed_buffer_type = Parent.TypeBuilder.DefineNestedType (name, Parent.Module.DefaultCharSetType |
319 TypeAttributes.NestedPublic | TypeAttributes.Sealed | TypeAttributes.BeforeFieldInit, TypeManager.value_type);
321 var element = fixed_buffer_type.DefineField (FixedElementName, MemberType, FieldAttributes.Public);
322 RootContext.RegisterCompilerGeneratedType (fixed_buffer_type);
324 FieldBuilder = Parent.TypeBuilder.DefineField (Name, fixed_buffer_type, ModifiersExtensions.FieldAttr (ModFlags));
325 spec = new FixedFieldSpec (this, FieldBuilder, element, ModFlags);
327 Parent.MemberCache.AddMember (FieldBuilder, this);
328 TypeManager.RegisterFieldBase (FieldBuilder, this);
333 protected override void DoMemberTypeIndependentChecks ()
335 base.DoMemberTypeIndependentChecks ();
338 Expression.UnsafeError (Report, Location);
340 if (Parent.PartialContainer.Kind != Kind.Struct) {
341 Report.Error (1642, Location, "`{0}': Fixed size buffer fields may only be members of structs",
342 GetSignatureForError ());
346 public override void Emit()
348 ResolveContext rc = new ResolveContext (this);
349 IntConstant buffer_size_const = initializer.Resolve (rc) as IntConstant;
350 if (buffer_size_const == null)
353 int buffer_size = buffer_size_const.Value;
355 if (buffer_size <= 0) {
356 Report.Error (1665, Location, "`{0}': Fixed size buffers must have a length greater than zero", GetSignatureForError ());
360 int type_size = Expression.GetTypeSize (MemberType);
362 if (buffer_size > int.MaxValue / type_size) {
363 Report.Error (1664, Location, "Fixed size buffer `{0}' of length `{1}' and type `{2}' exceeded 2^31 limit",
364 GetSignatureForError (), buffer_size.ToString (), TypeManager.CSharpName (MemberType));
368 buffer_size *= type_size;
369 EmitFieldSize (buffer_size);
371 PredefinedAttributes.Get.UnsafeValueType.EmitAttribute (fixed_buffer_type);
376 void EmitFieldSize (int buffer_size)
378 CustomAttributeBuilder cab;
379 PredefinedAttribute pa;
381 pa = PredefinedAttributes.Get.StructLayout;
382 if (pa.Constructor == null &&
383 !pa.ResolveConstructor (Location, TypeManager.short_type))
386 // TODO: It's not cleared
388 fi = new FieldInfo[] { pa.Type.GetField ("Size") };
390 object[] fi_val = new object[] { buffer_size };
391 cab = new CustomAttributeBuilder (pa.Constructor,
392 ctor_args, fi, fi_val);
393 fixed_buffer_type.SetCustomAttribute (cab);
396 // Don't emit FixedBufferAttribute attribute for private types
398 if ((ModFlags & Modifiers.PRIVATE) != 0)
401 pa = PredefinedAttributes.Get.FixedBuffer;
402 if (pa.Constructor == null &&
403 !pa.ResolveConstructor (Location, TypeManager.type_type, TypeManager.int32_type))
406 cab = new CustomAttributeBuilder (pa.Constructor, new object[] { MemberType, buffer_size });
407 FieldBuilder.SetCustomAttribute (cab);
410 protected override bool IsFieldClsCompliant {
416 public void SetCharSet (TypeAttributes ta)
418 TypeAttributes cta = fixed_buffer_type.Attributes;
419 if ((cta & TypeAttributes.UnicodeClass) != (ta & TypeAttributes.UnicodeClass))
420 SetTypeBuilderCharSet ((cta & ~TypeAttributes.AutoClass) | TypeAttributes.UnicodeClass);
421 else if ((cta & TypeAttributes.AutoClass) != (ta & TypeAttributes.AutoClass))
422 SetTypeBuilderCharSet ((cta & ~TypeAttributes.UnicodeClass) | TypeAttributes.AutoClass);
423 else if (cta == 0 && ta != 0)
424 SetTypeBuilderCharSet (cta & ~(TypeAttributes.UnicodeClass | TypeAttributes.AutoClass));
427 void SetTypeBuilderCharSet (TypeAttributes ta)
429 MethodInfo mi = typeof (TypeBuilder).GetMethod ("SetCharSet", BindingFlags.Instance | BindingFlags.NonPublic);
431 Report.RuntimeMissingSupport (Location, "TypeBuilder::SetCharSet");
433 mi.Invoke (fixed_buffer_type, new object [] { ta });
438 class FixedFieldSpec : FieldSpec
440 readonly FieldInfo element;
442 public FixedFieldSpec (IMemberDefinition definition, FieldInfo info, FieldInfo element, Modifiers modifiers)
443 : base (definition, info, modifiers)
445 this.element = element;
448 public FieldInfo Element {
454 public Type ElementType {
456 return element.FieldType;
462 // The Field class is used to represents class/struct fields during parsing.
464 public class Field : FieldBase {
466 // Modifiers allowed in a class declaration
468 const Modifiers AllowedModifiers =
471 Modifiers.PROTECTED |
479 public Field (DeclSpace parent, FullNamedExpression type, Modifiers mod, MemberName name,
481 : base (parent, type, mod, AllowedModifiers, name, attrs)
485 bool CanBeVolatile ()
487 if (TypeManager.IsReferenceType (MemberType))
490 if (MemberType == TypeManager.bool_type || MemberType == TypeManager.char_type ||
491 MemberType == TypeManager.sbyte_type || MemberType == TypeManager.byte_type ||
492 MemberType == TypeManager.short_type || MemberType == TypeManager.ushort_type ||
493 MemberType == TypeManager.int32_type || MemberType == TypeManager.uint32_type ||
494 MemberType == TypeManager.float_type ||
495 MemberType == TypeManager.intptr_type || MemberType == TypeManager.uintptr_type)
498 if (TypeManager.IsEnumType (MemberType))
504 bool CheckStructLayout (Type type, bool isStatic)
506 if (TypeManager.IsBuiltinType (type))
510 if (!TypeManager.IsValueType (type) || TypeManager.IsEqual (type, Parent.TypeBuilder))
514 if (!TypeManager.IsEqual (TypeManager.DropGenericTypeArguments (type), Parent.TypeBuilder)) {
515 if (!TypeManager.IsGenericType (type))
518 foreach (Type t in TypeManager.GetTypeArguments (type)) {
519 if (!CheckStructLayout (t, false))
525 Report.Error (523, Location,
526 "Struct member `{0}' of type `{1}' causes a cycle in the struct layout",
527 GetSignatureForError (), TypeManager.CSharpName (MemberType));
531 public override bool Define ()
537 Type[] required_modifier = null;
538 if ((ModFlags & Modifiers.VOLATILE) != 0) {
539 if (TypeManager.isvolatile_type == null)
540 TypeManager.isvolatile_type = TypeManager.CoreLookupType (Compiler,
541 "System.Runtime.CompilerServices", "IsVolatile", Kind.Class, true);
543 if (TypeManager.isvolatile_type != null)
544 required_modifier = new Type [] { TypeManager.isvolatile_type };
547 FieldBuilder = Parent.TypeBuilder.DefineField (
548 Name, MemberType, required_modifier, null, ModifiersExtensions.FieldAttr (ModFlags));
550 spec = new FieldSpec (this, FieldBuilder, ModFlags);
552 // Don't cache inaccessible fields
553 if ((ModFlags & Modifiers.BACKING_FIELD) == 0) {
554 Parent.MemberCache.AddMember (FieldBuilder, this);
557 TypeManager.RegisterFieldBase (FieldBuilder, this);
559 catch (ArgumentException) {
560 Report.RuntimeMissingSupport (Location, "`void' or `void*' field type");
564 if (initializer != null) {
565 ((TypeContainer) Parent).RegisterFieldForInitialization (this,
566 new FieldInitializer (this, initializer, this));
568 if (Parent.PartialContainer.Kind == Kind.Struct)
569 CheckStructLayout (member_type, (ModFlags & Modifiers.STATIC) != 0);
575 protected override void DoMemberTypeDependentChecks ()
577 base.DoMemberTypeDependentChecks ();
579 if ((ModFlags & Modifiers.VOLATILE) != 0) {
580 if (!CanBeVolatile ()) {
581 Report.Error (677, Location, "`{0}': A volatile field cannot be of the type `{1}'",
582 GetSignatureForError (), TypeManager.CSharpName (MemberType));
585 if ((ModFlags & Modifiers.READONLY) != 0) {
586 Report.Error (678, Location, "`{0}': A field cannot be both volatile and readonly",
587 GetSignatureForError ());
592 protected override bool VerifyClsCompliance ()
594 if (!base.VerifyClsCompliance ())
597 if ((ModFlags & Modifiers.VOLATILE) != 0) {
598 Report.Warning (3026, 1, Location, "CLS-compliant field `{0}' cannot be volatile", GetSignatureForError ());