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 initializer
= new ConstInitializer (this, size_expr
);
297 public override Constant
ConvertInitializer (ResolveContext rc
, Constant expr
)
299 return expr
.ImplicitConversionRequired (rc
, TypeManager
.int32_type
, Location
);
302 public override bool Define ()
307 if (!TypeManager
.IsPrimitiveType (MemberType
)) {
308 Report
.Error (1663, Location
,
309 "`{0}': Fixed size buffers type must be one of the following: bool, byte, short, int, long, char, sbyte, ushort, uint, ulong, float or double",
310 GetSignatureForError ());
313 // Create nested fixed buffer container
314 string name
= String
.Format ("<{0}>__FixedBuffer{1}", Name
, GlobalCounter
++);
315 fixed_buffer_type
= Parent
.TypeBuilder
.DefineNestedType (name
, Parent
.Module
.DefaultCharSetType
|
316 TypeAttributes
.NestedPublic
| TypeAttributes
.Sealed
| TypeAttributes
.BeforeFieldInit
, TypeManager
.value_type
);
318 var element
= fixed_buffer_type
.DefineField (FixedElementName
, MemberType
, FieldAttributes
.Public
);
319 RootContext
.RegisterCompilerGeneratedType (fixed_buffer_type
);
321 FieldBuilder
= Parent
.TypeBuilder
.DefineField (Name
, fixed_buffer_type
, ModifiersExtensions
.FieldAttr (ModFlags
));
322 spec
= new FixedFieldSpec (this, FieldBuilder
, element
, ModFlags
);
324 Parent
.MemberCache
.AddMember (FieldBuilder
, spec
);
325 TypeManager
.RegisterFieldBase (FieldBuilder
, this);
330 protected override void DoMemberTypeIndependentChecks ()
332 base.DoMemberTypeIndependentChecks ();
335 Expression
.UnsafeError (Report
, Location
);
337 if (Parent
.PartialContainer
.Kind
!= MemberKind
.Struct
) {
338 Report
.Error (1642, Location
, "`{0}': Fixed size buffer fields may only be members of structs",
339 GetSignatureForError ());
343 public override void Emit()
345 ResolveContext rc
= new ResolveContext (this);
346 IntConstant buffer_size_const
= initializer
.Resolve (rc
) as IntConstant
;
347 if (buffer_size_const
== null)
350 int buffer_size
= buffer_size_const
.Value
;
352 if (buffer_size
<= 0) {
353 Report
.Error (1665, Location
, "`{0}': Fixed size buffers must have a length greater than zero", GetSignatureForError ());
357 int type_size
= Expression
.GetTypeSize (MemberType
);
359 if (buffer_size
> int.MaxValue
/ type_size
) {
360 Report
.Error (1664, Location
, "Fixed size buffer `{0}' of length `{1}' and type `{2}' exceeded 2^31 limit",
361 GetSignatureForError (), buffer_size
.ToString (), TypeManager
.CSharpName (MemberType
));
365 buffer_size
*= type_size
;
366 EmitFieldSize (buffer_size
);
368 PredefinedAttributes
.Get
.UnsafeValueType
.EmitAttribute (fixed_buffer_type
);
373 void EmitFieldSize (int buffer_size
)
375 CustomAttributeBuilder cab
;
376 PredefinedAttribute pa
;
378 pa
= PredefinedAttributes
.Get
.StructLayout
;
379 if (pa
.Constructor
== null &&
380 !pa
.ResolveConstructor (Location
, TypeManager
.short_type
))
383 // TODO: It's not cleared
385 fi
= new FieldInfo
[] { pa.Type.GetField ("Size") }
;
387 object[] fi_val
= new object[] { buffer_size }
;
388 cab
= new CustomAttributeBuilder (pa
.Constructor
,
389 ctor_args
, fi
, fi_val
);
390 fixed_buffer_type
.SetCustomAttribute (cab
);
393 // Don't emit FixedBufferAttribute attribute for private types
395 if ((ModFlags
& Modifiers
.PRIVATE
) != 0)
398 pa
= PredefinedAttributes
.Get
.FixedBuffer
;
399 if (pa
.Constructor
== null &&
400 !pa
.ResolveConstructor (Location
, TypeManager
.type_type
, TypeManager
.int32_type
))
403 cab
= new CustomAttributeBuilder (pa
.Constructor
, new object[] { MemberType, buffer_size }
);
404 FieldBuilder
.SetCustomAttribute (cab
);
407 protected override bool IsFieldClsCompliant
{
413 public void SetCharSet (TypeAttributes ta
)
415 TypeAttributes cta
= fixed_buffer_type
.Attributes
;
416 if ((cta
& TypeAttributes
.UnicodeClass
) != (ta
& TypeAttributes
.UnicodeClass
))
417 SetTypeBuilderCharSet ((cta
& ~TypeAttributes
.AutoClass
) | TypeAttributes
.UnicodeClass
);
418 else if ((cta
& TypeAttributes
.AutoClass
) != (ta
& TypeAttributes
.AutoClass
))
419 SetTypeBuilderCharSet ((cta
& ~TypeAttributes
.UnicodeClass
) | TypeAttributes
.AutoClass
);
420 else if (cta
== 0 && ta
!= 0)
421 SetTypeBuilderCharSet (cta
& ~
(TypeAttributes
.UnicodeClass
| TypeAttributes
.AutoClass
));
424 void SetTypeBuilderCharSet (TypeAttributes ta
)
426 MethodInfo mi
= typeof (TypeBuilder
).GetMethod ("SetCharSet", BindingFlags
.Instance
| BindingFlags
.NonPublic
);
428 Report
.RuntimeMissingSupport (Location
, "TypeBuilder::SetCharSet");
430 mi
.Invoke (fixed_buffer_type
, new object [] { ta }
);
435 class FixedFieldSpec
: FieldSpec
437 readonly FieldInfo element
;
439 public FixedFieldSpec (IMemberDefinition definition
, FieldInfo info
, FieldInfo element
, Modifiers modifiers
)
440 : base (definition
, info
, modifiers
)
442 this.element
= element
;
445 public FieldInfo Element
{
451 public Type ElementType
{
453 return element
.FieldType
;
459 // The Field class is used to represents class/struct fields during parsing.
461 public class Field
: FieldBase
{
463 // Modifiers allowed in a class declaration
465 const Modifiers AllowedModifiers
=
468 Modifiers
.PROTECTED
|
476 public Field (DeclSpace parent
, FullNamedExpression type
, Modifiers mod
, MemberName name
,
478 : base (parent
, type
, mod
, AllowedModifiers
, name
, attrs
)
482 bool CanBeVolatile ()
484 if (TypeManager
.IsReferenceType (MemberType
))
487 if (MemberType
== TypeManager
.bool_type
|| MemberType
== TypeManager
.char_type
||
488 MemberType
== TypeManager
.sbyte_type
|| MemberType
== TypeManager
.byte_type
||
489 MemberType
== TypeManager
.short_type
|| MemberType
== TypeManager
.ushort_type
||
490 MemberType
== TypeManager
.int32_type
|| MemberType
== TypeManager
.uint32_type
||
491 MemberType
== TypeManager
.float_type
||
492 MemberType
== TypeManager
.intptr_type
|| MemberType
== TypeManager
.uintptr_type
)
495 if (TypeManager
.IsEnumType (MemberType
))
501 bool CheckStructLayout (Type type
, bool isStatic
)
503 if (TypeManager
.IsBuiltinType (type
))
507 if (!TypeManager
.IsValueType (type
) || TypeManager
.IsEqual (type
, Parent
.TypeBuilder
))
511 if (!TypeManager
.IsEqual (TypeManager
.DropGenericTypeArguments (type
), Parent
.TypeBuilder
)) {
512 if (!TypeManager
.IsGenericType (type
))
515 foreach (Type t
in TypeManager
.GetTypeArguments (type
)) {
516 if (!CheckStructLayout (t
, false))
522 Report
.Error (523, Location
,
523 "Struct member `{0}' of type `{1}' causes a cycle in the struct layout",
524 GetSignatureForError (), TypeManager
.CSharpName (MemberType
));
528 public override bool Define ()
534 Type
[] required_modifier
= null;
535 if ((ModFlags
& Modifiers
.VOLATILE
) != 0) {
536 if (TypeManager
.isvolatile_type
== null)
537 TypeManager
.isvolatile_type
= TypeManager
.CoreLookupType (Compiler
,
538 "System.Runtime.CompilerServices", "IsVolatile", MemberKind
.Class
, true);
540 if (TypeManager
.isvolatile_type
!= null)
541 required_modifier
= new Type
[] { TypeManager.isvolatile_type }
;
544 FieldBuilder
= Parent
.TypeBuilder
.DefineField (
545 Name
, MemberType
, required_modifier
, null, ModifiersExtensions
.FieldAttr (ModFlags
));
547 spec
= new FieldSpec (this, FieldBuilder
, ModFlags
);
549 // Don't cache inaccessible fields
550 if ((ModFlags
& Modifiers
.BACKING_FIELD
) == 0) {
551 Parent
.MemberCache
.AddMember (FieldBuilder
, spec
);
554 TypeManager
.RegisterFieldBase (FieldBuilder
, this);
556 catch (ArgumentException
) {
557 Report
.RuntimeMissingSupport (Location
, "`void' or `void*' field type");
561 if (initializer
!= null) {
562 ((TypeContainer
) Parent
).RegisterFieldForInitialization (this,
563 new FieldInitializer (this, initializer
, this));
565 if (Parent
.PartialContainer
.Kind
== MemberKind
.Struct
)
566 CheckStructLayout (member_type
, (ModFlags
& Modifiers
.STATIC
) != 0);
572 protected override void DoMemberTypeDependentChecks ()
574 base.DoMemberTypeDependentChecks ();
576 if ((ModFlags
& Modifiers
.VOLATILE
) != 0) {
577 if (!CanBeVolatile ()) {
578 Report
.Error (677, Location
, "`{0}': A volatile field cannot be of the type `{1}'",
579 GetSignatureForError (), TypeManager
.CSharpName (MemberType
));
582 if ((ModFlags
& Modifiers
.READONLY
) != 0) {
583 Report
.Error (678, Location
, "`{0}': A field cannot be both volatile and readonly",
584 GetSignatureForError ());
589 protected override bool VerifyClsCompliance ()
591 if (!base.VerifyClsCompliance ())
594 if ((ModFlags
& Modifiers
.VOLATILE
) != 0) {
595 Report
.Warning (3026, 1, Location
, "CLS-compliant field `{0}' cannot be volatile", GetSignatureForError ());