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
, MethodSpec ctor
, byte[] cdata
, 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 ((ConstructorInfo
) ctor
.GetMetaInfo (), cdata
);
97 protected override bool CheckBase ()
99 if (!base.CheckBase ())
102 MemberSpec candidate
;
103 var conflict_symbol
= MemberCache
.FindBaseMember (this, out candidate
);
104 if (conflict_symbol
== null)
105 conflict_symbol
= candidate
;
107 if (conflict_symbol
== null) {
108 if ((ModFlags
& Modifiers
.NEW
) != 0) {
109 Report
.Warning (109, 4, Location
, "The member `{0}' does not hide an inherited member. The new keyword is not required",
110 GetSignatureForError ());
113 if ((ModFlags
& (Modifiers
.NEW
| Modifiers
.OVERRIDE
| Modifiers
.BACKING_FIELD
)) == 0) {
114 Report
.SymbolRelatedToPreviousError (conflict_symbol
);
115 Report
.Warning (108, 2, Location
, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
116 GetSignatureForError (), conflict_symbol
.GetSignatureForError ());
119 if (conflict_symbol
.IsAbstract
) {
120 Report
.SymbolRelatedToPreviousError (conflict_symbol
);
121 Report
.Error (533, Location
, "`{0}' hides inherited abstract member `{1}'",
122 GetSignatureForError (), conflict_symbol
.GetSignatureForError ());
129 public virtual Constant
ConvertInitializer (ResolveContext rc
, Constant expr
)
131 return expr
.ConvertImplicitly (rc
, MemberType
);
134 protected override void DoMemberTypeDependentChecks ()
136 base.DoMemberTypeDependentChecks ();
138 if (MemberType
.IsGenericParameter
)
141 if (MemberType
.IsStatic
)
142 Error_VariableOfStaticClass (Location
, GetSignatureForError (), MemberType
, Report
);
149 // Represents header string for documentation comment.
151 public override string DocCommentHeader
{
155 public override void Emit ()
157 if (member_type
== InternalType
.Dynamic
) {
158 PredefinedAttributes
.Get
.Dynamic
.EmitAttribute (FieldBuilder
);
160 var trans_flags
= TypeManager
.HasDynamicTypeUsed (member_type
);
161 if (trans_flags
!= null) {
162 var pa
= PredefinedAttributes
.Get
.DynamicTransform
;
163 if (pa
.Constructor
!= null || pa
.ResolveConstructor (Location
, ArrayContainer
.MakeType (TypeManager
.bool_type
, 1))) {
164 FieldBuilder
.SetCustomAttribute (new CustomAttributeBuilder (pa
.Constructor
, new object[] { trans_flags }
));
169 if ((ModFlags
& Modifiers
.COMPILER_GENERATED
) != 0 && !Parent
.IsCompilerGenerated
)
170 PredefinedAttributes
.Get
.CompilerGenerated
.EmitAttribute (FieldBuilder
);
172 if (OptAttributes
!= null) {
173 OptAttributes
.Emit ();
176 if (((status
& Status
.HAS_OFFSET
) == 0) && (ModFlags
& (Modifiers
.STATIC
| Modifiers
.BACKING_FIELD
)) == 0 && Parent
.PartialContainer
.HasExplicitLayout
) {
177 Report
.Error (625, Location
, "`{0}': Instance field types marked with StructLayout(LayoutKind.Explicit) must have a FieldOffset attribute", GetSignatureForError ());
183 public static void Error_VariableOfStaticClass (Location loc
, string variable_name
, TypeSpec static_class
, Report Report
)
185 Report
.SymbolRelatedToPreviousError (static_class
);
186 Report
.Error (723, loc
, "`{0}': cannot declare variables of static types",
190 public Expression Initializer
{
196 this.initializer
= value;
201 public FieldSpec Spec
{
205 public override string[] ValidAttributeTargets
208 return attribute_targets
;
212 protected override bool VerifyClsCompliance ()
214 if (!base.VerifyClsCompliance ())
217 if (!MemberType
.IsCLSCompliant () || this is FixedField
) {
218 Report
.Warning (3003, 1, Location
, "Type of `{0}' is not CLS-compliant",
219 GetSignatureForError ());
226 // Field specification
228 public class FieldSpec
: MemberSpec
, IInterfaceMemberSpec
233 public FieldSpec (TypeSpec declaringType
, IMemberDefinition definition
, TypeSpec memberType
, FieldInfo info
, Modifiers modifiers
)
234 : base (MemberKind
.Field
, declaringType
, definition
, modifiers
)
236 this.metaInfo
= info
;
237 this.memberType
= memberType
;
242 public bool IsReadOnly
{
244 return (Modifiers
& Modifiers
.READONLY
) != 0;
248 public TypeSpec MemberType
{
256 public FieldInfo
GetMetaInfo ()
258 if ((state
& StateFlags
.PendingMetaInflate
) != 0) {
259 var decl_meta
= DeclaringType
.GetMetaInfo ();
260 if (DeclaringType
.IsTypeBuilder
) {
261 metaInfo
= TypeBuilder
.GetField (decl_meta
, metaInfo
);
263 var orig_token
= metaInfo
.MetadataToken
;
264 metaInfo
= decl_meta
.GetField (Name
, BindingFlags
.Public
| BindingFlags
.NonPublic
| BindingFlags
.Instance
| BindingFlags
.Static
);
265 if (metaInfo
.MetadataToken
!= orig_token
)
266 throw new NotImplementedException ("Resolved to wrong meta token");
268 // What a stupid API, does not work because field handle is imported
269 // metaInfo = FieldInfo.GetFieldFromHandle (metaInfo.FieldHandle, DeclaringType.MetaInfo.TypeHandle);
272 state
&= ~StateFlags
.PendingMetaInflate
;
278 public override MemberSpec
InflateMember (TypeParameterInflator inflator
)
280 var fs
= (FieldSpec
) base.InflateMember (inflator
);
281 fs
.memberType
= inflator
.Inflate (memberType
);
285 public FieldSpec
Mutate (TypeParameterMutator mutator
)
287 var decl
= DeclaringType
;
288 if (DeclaringType
.IsGenericOrParentIsGeneric
)
289 decl
= mutator
.Mutate (decl
);
291 if (decl
== DeclaringType
)
294 var fs
= (FieldSpec
) MemberwiseClone ();
295 fs
.declaringType
= decl
;
296 fs
.state
|= StateFlags
.PendingMetaInflate
;
298 // Gets back FieldInfo in case of metaInfo was inflated
299 fs
.metaInfo
= MemberCache
.GetMember (DeclaringType
.GetDefinition (), this).metaInfo
;
305 /// Fixed buffer implementation
307 public class FixedField
: FieldBase
309 public const string FixedElementName
= "FixedElementField";
310 static int GlobalCounter
= 0;
311 static object[] ctor_args
= new object[] { (short)LayoutKind.Sequential }
;
312 static FieldInfo
[] fi
;
314 TypeBuilder fixed_buffer_type
;
316 const Modifiers AllowedModifiers
=
319 Modifiers
.PROTECTED
|
324 public FixedField (DeclSpace parent
, FullNamedExpression type
, Modifiers mod
, string name
,
325 Expression size_expr
, Attributes attrs
, Location loc
):
326 base (parent
, type
, mod
, AllowedModifiers
, new MemberName (name
, loc
), attrs
)
328 initializer
= new ConstInitializer (this, size_expr
);
331 public override Constant
ConvertInitializer (ResolveContext rc
, Constant expr
)
333 return expr
.ImplicitConversionRequired (rc
, TypeManager
.int32_type
, Location
);
336 public override bool Define ()
341 if (!TypeManager
.IsPrimitiveType (MemberType
)) {
342 Report
.Error (1663, Location
,
343 "`{0}': Fixed size buffers type must be one of the following: bool, byte, short, int, long, char, sbyte, ushort, uint, ulong, float or double",
344 GetSignatureForError ());
347 // Create nested fixed buffer container
348 string name
= String
.Format ("<{0}>__FixedBuffer{1}", Name
, GlobalCounter
++);
349 fixed_buffer_type
= Parent
.TypeBuilder
.DefineNestedType (name
, Parent
.Module
.DefaultCharSetType
|
350 TypeAttributes
.NestedPublic
| TypeAttributes
.Sealed
| TypeAttributes
.BeforeFieldInit
, TypeManager
.value_type
.GetMetaInfo ());
352 fixed_buffer_type
.DefineField (FixedElementName
, MemberType
.GetMetaInfo (), FieldAttributes
.Public
);
353 RootContext
.RegisterCompilerGeneratedType (fixed_buffer_type
);
355 FieldBuilder
= Parent
.TypeBuilder
.DefineField (Name
, fixed_buffer_type
, ModifiersExtensions
.FieldAttr (ModFlags
));
356 var element_spec
= new FieldSpec (null, this, MemberType
, FieldBuilder
, ModFlags
);
357 spec
= new FixedFieldSpec (Parent
.Definition
, this, FieldBuilder
, element_spec
, ModFlags
);
359 Parent
.MemberCache
.AddMember (spec
);
363 protected override void DoMemberTypeIndependentChecks ()
365 base.DoMemberTypeIndependentChecks ();
368 Expression
.UnsafeError (Report
, Location
);
370 if (Parent
.PartialContainer
.Kind
!= MemberKind
.Struct
) {
371 Report
.Error (1642, Location
, "`{0}': Fixed size buffer fields may only be members of structs",
372 GetSignatureForError ());
376 public override void Emit()
378 ResolveContext rc
= new ResolveContext (this);
379 IntConstant buffer_size_const
= initializer
.Resolve (rc
) as IntConstant
;
380 if (buffer_size_const
== null)
383 int buffer_size
= buffer_size_const
.Value
;
385 if (buffer_size
<= 0) {
386 Report
.Error (1665, Location
, "`{0}': Fixed size buffers must have a length greater than zero", GetSignatureForError ());
390 int type_size
= Expression
.GetTypeSize (MemberType
);
392 if (buffer_size
> int.MaxValue
/ type_size
) {
393 Report
.Error (1664, Location
, "Fixed size buffer `{0}' of length `{1}' and type `{2}' exceeded 2^31 limit",
394 GetSignatureForError (), buffer_size
.ToString (), TypeManager
.CSharpName (MemberType
));
398 buffer_size
*= type_size
;
399 EmitFieldSize (buffer_size
);
401 PredefinedAttributes
.Get
.UnsafeValueType
.EmitAttribute (fixed_buffer_type
);
406 void EmitFieldSize (int buffer_size
)
408 CustomAttributeBuilder cab
;
409 PredefinedAttribute pa
;
411 pa
= PredefinedAttributes
.Get
.StructLayout
;
412 if (pa
.Constructor
== null &&
413 !pa
.ResolveConstructor (Location
, TypeManager
.short_type
))
416 // TODO: It's not cleared
418 var field
= (FieldSpec
) MemberCache
.FindMember (pa
.Type
, MemberFilter
.Field ("Size", null), BindingRestriction
.DeclaredOnly
);
419 fi
= new FieldInfo
[] { field.GetMetaInfo () }
;
422 object[] fi_val
= new object[] { buffer_size }
;
423 cab
= new CustomAttributeBuilder (pa
.Constructor
,
424 ctor_args
, fi
, fi_val
);
425 fixed_buffer_type
.SetCustomAttribute (cab
);
428 // Don't emit FixedBufferAttribute attribute for private types
430 if ((ModFlags
& Modifiers
.PRIVATE
) != 0)
433 pa
= PredefinedAttributes
.Get
.FixedBuffer
;
434 if (pa
.Constructor
== null &&
435 !pa
.ResolveConstructor (Location
, TypeManager
.type_type
, TypeManager
.int32_type
))
438 cab
= new CustomAttributeBuilder (pa
.Constructor
, new object[] { MemberType.GetMetaInfo (), buffer_size }
);
439 FieldBuilder
.SetCustomAttribute (cab
);
442 public void SetCharSet (TypeAttributes ta
)
444 TypeAttributes cta
= fixed_buffer_type
.Attributes
;
445 if ((cta
& TypeAttributes
.UnicodeClass
) != (ta
& TypeAttributes
.UnicodeClass
))
446 SetTypeBuilderCharSet ((cta
& ~TypeAttributes
.AutoClass
) | TypeAttributes
.UnicodeClass
);
447 else if ((cta
& TypeAttributes
.AutoClass
) != (ta
& TypeAttributes
.AutoClass
))
448 SetTypeBuilderCharSet ((cta
& ~TypeAttributes
.UnicodeClass
) | TypeAttributes
.AutoClass
);
449 else if (cta
== 0 && ta
!= 0)
450 SetTypeBuilderCharSet (cta
& ~
(TypeAttributes
.UnicodeClass
| TypeAttributes
.AutoClass
));
453 void SetTypeBuilderCharSet (TypeAttributes ta
)
455 MethodInfo mi
= typeof (TypeBuilder
).GetMethod ("SetCharSet", BindingFlags
.Instance
| BindingFlags
.NonPublic
);
457 Report
.RuntimeMissingSupport (Location
, "TypeBuilder::SetCharSet");
459 mi
.Invoke (fixed_buffer_type
, new object [] { ta }
);
464 class FixedFieldSpec
: FieldSpec
466 readonly FieldSpec element
;
468 public FixedFieldSpec (TypeSpec declaringType
, IMemberDefinition definition
, FieldInfo info
, FieldSpec element
, Modifiers modifiers
)
469 : base (declaringType
, definition
, element
.MemberType
, info
, modifiers
)
471 this.element
= element
;
473 // It's never CLS-Compliant
474 state
&= ~StateFlags
.CLSCompliant_Undetected
;
477 public FieldSpec Element
{
483 public TypeSpec ElementType
{
491 // The Field class is used to represents class/struct fields during parsing.
493 public class Field
: FieldBase
{
495 // Modifiers allowed in a class declaration
497 const Modifiers AllowedModifiers
=
500 Modifiers
.PROTECTED
|
508 public Field (DeclSpace parent
, FullNamedExpression type
, Modifiers mod
, MemberName name
,
510 : base (parent
, type
, mod
, AllowedModifiers
, name
, attrs
)
514 bool CanBeVolatile ()
516 if (TypeManager
.IsReferenceType (MemberType
))
519 if (MemberType
== TypeManager
.bool_type
|| MemberType
== TypeManager
.char_type
||
520 MemberType
== TypeManager
.sbyte_type
|| MemberType
== TypeManager
.byte_type
||
521 MemberType
== TypeManager
.short_type
|| MemberType
== TypeManager
.ushort_type
||
522 MemberType
== TypeManager
.int32_type
|| MemberType
== TypeManager
.uint32_type
||
523 MemberType
== TypeManager
.float_type
||
524 MemberType
== TypeManager
.intptr_type
|| MemberType
== TypeManager
.uintptr_type
)
527 if (MemberType
.IsEnum
)
533 public override bool Define ()
539 Type
[] required_modifier
= null;
540 if ((ModFlags
& Modifiers
.VOLATILE
) != 0) {
541 if (TypeManager
.isvolatile_type
== null)
542 TypeManager
.isvolatile_type
= TypeManager
.CoreLookupType (Compiler
,
543 "System.Runtime.CompilerServices", "IsVolatile", MemberKind
.Class
, true);
545 if (TypeManager
.isvolatile_type
!= null)
546 required_modifier
= new Type
[] { TypeManager.isvolatile_type.GetMetaInfo () }
;
549 FieldBuilder
= Parent
.TypeBuilder
.DefineField (
550 Name
, member_type
.GetMetaInfo (), required_modifier
, null, ModifiersExtensions
.FieldAttr (ModFlags
));
552 spec
= new FieldSpec (Parent
.Definition
, this, MemberType
, FieldBuilder
, ModFlags
);
554 // Don't cache inaccessible fields
555 if ((ModFlags
& Modifiers
.BACKING_FIELD
) == 0) {
556 Parent
.MemberCache
.AddMember (spec
);
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));
572 protected override void DoMemberTypeDependentChecks ()
574 if ((ModFlags
& Modifiers
.BACKING_FIELD
) != 0)
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 ());