[mcs] Implements C# 7.2 readonly structs
[mono.git] / mcs / mcs / field.cs
1 //
2 // field.cs: All field handlers
3 //
4 // Authors: Miguel de Icaza (miguel@gnu.org)
5 //          Martin Baulig (martin@ximian.com)
6 //          Marek Safar (marek.safar@seznam.cz)
7 //
8 // Dual licensed under the terms of the MIT X11 or GNU GPL
9 //
10 // Copyright 2001, 2002, 2003 Ximian, Inc (http://www.ximian.com)
11 // Copyright 2004-2008 Novell, Inc
12 // Copyright 2011 Xamarin Inc
13 //
14
15 using System;
16 using System.Collections.Generic;
17 using System.Runtime.InteropServices;
18
19 #if STATIC
20 using MetaType = IKVM.Reflection.Type;
21 using IKVM.Reflection;
22 using IKVM.Reflection.Emit;
23 #else
24 using MetaType = System.Type;
25 using System.Reflection;
26 using System.Reflection.Emit;
27 #endif
28
29 namespace Mono.CSharp
30 {
31         public class FieldDeclarator
32         {
33                 public FieldDeclarator (SimpleMemberName name, Expression initializer)
34                 {
35                         this.Name = name;
36                         this.Initializer = initializer;
37                 }
38
39                 #region Properties
40
41                 public SimpleMemberName Name { get; private set; }
42                 public Expression Initializer { get; private set; }
43
44                 #endregion
45
46                 public virtual FullNamedExpression GetFieldTypeExpression (FieldBase field)
47                 {
48                         return new TypeExpression (field.MemberType, Name.Location); 
49                 }
50         }
51
52         //
53         // Abstract class for all fields
54         //
55         abstract public class FieldBase : MemberBase
56         {
57                 protected FieldBuilder FieldBuilder;
58                 protected FieldSpec spec;
59                 public Status status;
60                 protected Expression initializer;
61                 protected List<FieldDeclarator> declarators;
62
63                 [Flags]
64                 public enum Status : byte {
65                         HAS_OFFSET = 4          // Used by FieldMember.
66                 }
67
68                 static readonly string[] attribute_targets = new string [] { "field" };
69
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)
72                 {
73                         if ((mod & Modifiers.ABSTRACT) != 0)
74                                 Report.Error (681, Location, "The modifier 'abstract' is not valid on fields. Try using a property instead");
75                 }
76
77                 #region Properties
78
79                 public override AttributeTargets AttributeTargets {
80                         get {
81                                 return AttributeTargets.Field;
82                         }
83                 }
84
85                 public List<FieldDeclarator> Declarators {
86                         get {
87                                 return this.declarators;
88                         }
89                 }
90
91                 public Expression Initializer {
92                         get {
93                                 return initializer;
94                         }
95                         set {
96                                 this.initializer = value;
97                         }
98                 }
99
100                 public string Name {
101                         get {
102                                 return MemberName.Name;
103                         }
104                 }
105
106                 public FieldSpec Spec {
107                         get {
108                                 return spec;
109                         }
110                 }
111
112                 public override string[] ValidAttributeTargets  {
113                         get {
114                                 return attribute_targets;
115                         }
116                 }
117
118                 #endregion
119
120                 public void AddDeclarator (FieldDeclarator declarator)
121                 {
122                         if (declarators == null)
123                                 declarators = new List<FieldDeclarator> (2);
124
125                         declarators.Add (declarator);
126
127                         Parent.AddNameToContainer (this, declarator.Name.Value);
128                 }
129
130                 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
131                 {
132                         if (a.Type == pa.FieldOffset) {
133                                 status |= Status.HAS_OFFSET;
134
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)");
137                                         return;
138                                 }
139
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");
142                                         return;
143                                 }
144                         }
145
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");
148                                 return;
149                         }
150
151 #if false
152                         if (a.Type == pa.MarshalAs) {
153                                 UnmanagedMarshal marshal = a.GetMarshal (this);
154                                 if (marshal != null) {
155                                         FieldBuilder.SetMarshal (marshal);
156                                 }
157                                 return;
158                         }
159 #endif
160                         if ((a.HasSecurityAttribute)) {
161                                 a.Error_InvalidSecurityParent ();
162                                 return;
163                         }
164
165                         if (a.Type == pa.Dynamic) {
166                                 a.Error_MisusedDynamicAttribute ();
167                                 return;
168                         }
169
170                         FieldBuilder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), cdata);
171                 }
172
173                 public void SetCustomAttribute (MethodSpec ctor, byte[] data)
174                 {
175                         FieldBuilder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), data);
176                 }
177
178                 protected override bool CheckBase ()
179                 {
180                         if (!base.CheckBase ())
181                                 return false;
182
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;
188
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 ());
193                                 }
194                         } else {
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 ());
199                                 }
200
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 ());
205                                 }
206                         }
207  
208                         return true;
209                 }
210
211                 public virtual Constant ConvertInitializer (ResolveContext rc, Constant expr)
212                 {
213                         return expr.ConvertImplicitly (MemberType);
214                 }
215
216                 protected override void DoMemberTypeDependentChecks ()
217                 {
218                         base.DoMemberTypeDependentChecks ();
219
220                         if (MemberType.IsGenericParameter)
221                                 return;
222
223                         if (MemberType.IsStatic)
224                                 Error_VariableOfStaticClass (Location, GetSignatureForError (), MemberType, Report);
225
226                         if (!IsCompilerGenerated)
227                                 CheckBase ();
228
229                         IsTypePermitted ();
230                 }
231
232                 //
233                 //   Represents header string for documentation comment.
234                 //
235                 public override string DocCommentHeader {
236                         get { return "F:"; }
237                 }
238
239                 public override void Emit ()
240                 {
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);
245                         }
246
247                         if (member_type.HasNamedTupleElement) {
248                                 Module.PredefinedAttributes.TupleElementNames.EmitAttribute (FieldBuilder, member_type, Location);
249                         }
250
251                         if ((ModFlags & Modifiers.COMPILER_GENERATED) != 0 && !Parent.IsCompilerGenerated)
252                                 Module.PredefinedAttributes.CompilerGenerated.EmitAttribute (FieldBuilder);
253                         if ((ModFlags & Modifiers.DEBUGGER_HIDDEN) != 0)
254                                 Module.PredefinedAttributes.DebuggerBrowsable.EmitAttribute (FieldBuilder, System.Diagnostics.DebuggerBrowsableState.Never);
255
256                         if (OptAttributes != null) {
257                                 OptAttributes.Emit ();
258                         }
259
260                         if (((status & Status.HAS_OFFSET) == 0) && (ModFlags & (Modifiers.STATIC | Modifiers.BACKING_FIELD)) == 0 && Parent.PartialContainer.HasExplicitLayout) {
261                                 Report.Error (625, Location, "`{0}': Instance field types marked with StructLayout(LayoutKind.Explicit) must have a FieldOffset attribute", GetSignatureForError ());
262                         }
263
264                         if (!IsCompilerGenerated)
265                                 ConstraintChecker.Check (this, member_type, type_expr.Location);
266
267                         base.Emit ();
268                 }
269
270                 public static void Error_VariableOfStaticClass (Location loc, string variable_name, TypeSpec static_class, Report Report)
271                 {
272                         Report.SymbolRelatedToPreviousError (static_class);
273                         Report.Error (723, loc, "`{0}': cannot declare variables of static types",
274                                 variable_name);
275                 }
276
277                 protected override bool VerifyClsCompliance ()
278                 {
279                         if (!base.VerifyClsCompliance ())
280                                 return false;
281
282                         if (!MemberType.IsCLSCompliant () || this is FixedField) {
283                                 Report.Warning (3003, 1, Location, "Type of `{0}' is not CLS-compliant",
284                                         GetSignatureForError ());
285                         }
286                         return true;
287                 }
288         }
289
290         //
291         // Field specification
292         //
293         public class FieldSpec : MemberSpec, IInterfaceMemberSpec
294         {
295                 FieldInfo metaInfo;
296                 TypeSpec memberType;
297
298                 public FieldSpec (TypeSpec declaringType, IMemberDefinition definition, TypeSpec memberType, FieldInfo info, Modifiers modifiers)
299                         : base (MemberKind.Field, declaringType, definition, modifiers)
300                 {
301                         this.metaInfo = info;
302                         this.memberType = memberType;
303                 }
304
305                 #region Properties
306
307                 public bool IsReadOnly {
308                         get {
309                                 return (Modifiers & Modifiers.READONLY) != 0;
310                         }
311                 }
312
313                 public TypeSpec MemberType {
314                         get {
315                                 return memberType;
316                         }
317                 }
318
319                 #endregion
320
321                 public FieldInfo GetMetaInfo ()
322                 {
323                         if ((state & StateFlags.PendingMetaInflate) != 0) {
324                                 var decl_meta = DeclaringType.GetMetaInfo ();
325                                 if (DeclaringType.IsTypeBuilder) {
326                                         metaInfo = TypeBuilder.GetField (decl_meta, metaInfo);
327                                 } else {
328                                         var orig_token = metaInfo.MetadataToken;
329                                         metaInfo = decl_meta.GetField (Name, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static);
330                                         if (metaInfo.MetadataToken != orig_token)
331                                                 throw new NotImplementedException ("Resolved to wrong meta token");
332
333                                         // What a stupid API, does not work because field handle is imported
334                                         // metaInfo = FieldInfo.GetFieldFromHandle (metaInfo.FieldHandle, DeclaringType.MetaInfo.TypeHandle);
335                                 }
336
337                                 state &= ~StateFlags.PendingMetaInflate;
338                         }
339
340                         return metaInfo;
341                 }
342
343                 public override MemberSpec InflateMember (TypeParameterInflator inflator)
344                 {
345                         var fs = (FieldSpec) base.InflateMember (inflator);
346                         fs.memberType = inflator.Inflate (memberType);
347                         return fs;
348                 }
349
350                 public FieldSpec Mutate (TypeParameterMutator mutator)
351                 {
352                         var decl = DeclaringType;
353                         if (DeclaringType.IsGenericOrParentIsGeneric)
354                                 decl = mutator.Mutate (decl);
355
356                         if (decl == DeclaringType)
357                                 return this;
358
359                         var fs = (FieldSpec) MemberwiseClone ();
360                         fs.declaringType = decl;
361                         fs.state |= StateFlags.PendingMetaInflate;
362
363                         // Gets back FieldInfo in case of metaInfo was inflated
364                         fs.metaInfo = MemberCache.GetMember (TypeParameterMutator.GetMemberDeclaringType (DeclaringType), this).metaInfo;
365                         return fs;
366                 }
367
368                 public override List<MissingTypeSpecReference> ResolveMissingDependencies (MemberSpec caller)
369                 {
370                         return memberType.ResolveMissingDependencies (this);
371                 }
372         }
373
374         /// <summary>
375         /// Fixed buffer implementation
376         /// </summary>
377         public class FixedField : FieldBase
378         {
379                 public const string FixedElementName = "FixedElementField";
380                 static int GlobalCounter;
381
382                 TypeBuilder fixed_buffer_type;
383
384                 const Modifiers AllowedModifiers =
385                         Modifiers.NEW |
386                         Modifiers.PUBLIC |
387                         Modifiers.PROTECTED |
388                         Modifiers.INTERNAL |
389                         Modifiers.PRIVATE |
390                         Modifiers.UNSAFE;
391
392                 public FixedField (TypeDefinition parent, FullNamedExpression type, Modifiers mod, MemberName name, Attributes attrs)
393                         : base (parent, type, mod, AllowedModifiers, name, attrs)
394                 {
395                 }
396
397                 #region Properties
398
399                 //
400                 // Explicit struct layout set by parent
401                 //
402                 public CharSet? CharSetValue {
403                         get; set;
404                 }               
405
406                 #endregion
407
408                 public override Constant ConvertInitializer (ResolveContext rc, Constant expr)
409                 {
410                         return expr.ImplicitConversionRequired (rc, rc.BuiltinTypes.Int);
411                 }
412
413                 public override bool Define ()
414                 {
415                         if (!base.Define ())
416                                 return false;
417
418                         if (!BuiltinTypeSpec.IsPrimitiveType (MemberType)) {
419                                 Report.Error (1663, Location,
420                                         "`{0}': Fixed size buffers type must be one of the following: bool, byte, short, int, long, char, sbyte, ushort, uint, ulong, float or double",
421                                         GetSignatureForError ());
422                         } else if (declarators != null) {
423                                 foreach (var d in declarators) {
424                                         var f = new FixedField (Parent, d.GetFieldTypeExpression (this), ModFlags, new MemberName (d.Name.Value, d.Name.Location), OptAttributes);
425                                         f.initializer = d.Initializer;
426                                         ((ConstInitializer) f.initializer).Name = d.Name.Value;
427                                         f.Define ();
428                                         Parent.PartialContainer.Members.Add (f);
429                                 }
430                         }
431                         
432                         // Create nested fixed buffer container
433                         string name = String.Format ("<{0}>__FixedBuffer{1}", TypeDefinition.FilterNestedName (Name), GlobalCounter++);
434                         fixed_buffer_type = Parent.TypeBuilder.DefineNestedType (name,
435                                 TypeAttributes.NestedPublic | TypeAttributes.Sealed | TypeAttributes.BeforeFieldInit,
436                                 Compiler.BuiltinTypes.ValueType.GetMetaInfo ());
437
438                         var ffield = fixed_buffer_type.DefineField (FixedElementName, MemberType.GetMetaInfo (), FieldAttributes.Public);
439                         
440                         FieldBuilder = Parent.TypeBuilder.DefineField (Name, fixed_buffer_type, ModifiersExtensions.FieldAttr (ModFlags));
441
442                         var element_spec = new FieldSpec (null, this, MemberType, ffield, ModFlags);
443                         spec = new FixedFieldSpec (Module, Parent.Definition, this, FieldBuilder, element_spec, ModFlags);
444
445                         Parent.MemberCache.AddMember (spec);
446                         return true;
447                 }
448
449                 protected override void DoMemberTypeIndependentChecks ()
450                 {
451                         base.DoMemberTypeIndependentChecks ();
452
453                         if (!IsUnsafe)
454                                 Expression.UnsafeError (Report, Location);
455
456                         if (Parent.PartialContainer.Kind != MemberKind.Struct) {
457                                 Report.Error (1642, Location, "`{0}': Fixed size buffer fields may only be members of structs",
458                                         GetSignatureForError ());
459                         }
460                 }
461
462                 public override void Emit()
463                 {
464                         ResolveContext rc = new ResolveContext (this);
465                         IntConstant buffer_size_const = initializer.Resolve (rc) as IntConstant;
466                         if (buffer_size_const == null)
467                                 return;
468
469                         int buffer_size = buffer_size_const.Value;
470
471                         if (buffer_size <= 0) {
472                                 Report.Error (1665, Location, "`{0}': Fixed size buffers must have a length greater than zero", GetSignatureForError ());
473                                 return;
474                         }
475
476                         EmitFieldSize (buffer_size);
477
478 #if STATIC
479                         if (Module.HasDefaultCharSet)
480                                 fixed_buffer_type.__SetAttributes (fixed_buffer_type.Attributes | Module.DefaultCharSetType);
481 #endif
482
483                         Module.PredefinedAttributes.UnsafeValueType.EmitAttribute (fixed_buffer_type);
484                         Module.PredefinedAttributes.CompilerGenerated.EmitAttribute (fixed_buffer_type);
485                         fixed_buffer_type.CreateType ();
486
487                         base.Emit ();
488                 }
489
490                 void EmitFieldSize (int buffer_size)
491                 {
492                         int type_size = BuiltinTypeSpec.GetSize (MemberType);
493
494                         if (buffer_size > int.MaxValue / type_size) {
495                                 Report.Error (1664, Location, "Fixed size buffer `{0}' of length `{1}' and type `{2}' exceeded 2^31 limit",
496                                         GetSignatureForError (), buffer_size.ToString (), MemberType.GetSignatureForError ());
497                                 return;
498                         }
499
500                         AttributeEncoder encoder;
501                         MethodSpec ctor;
502
503                         var char_set = CharSetValue ?? Module.DefaultCharSet ?? 0;
504 #if STATIC
505                         //
506                         // Set struct layout without resolving StructLayoutAttribute which is not always available
507                         //
508
509                         TypeAttributes attribs = TypeAttributes.SequentialLayout;
510                         switch (char_set) {
511                         case CharSet.None:
512                         case CharSet.Ansi:
513                                 attribs |= TypeAttributes.AnsiClass;
514                                 break;
515                         case CharSet.Auto:
516                                 attribs |= TypeAttributes.AutoClass;
517                                 break;
518                         case CharSet.Unicode:
519                                 attribs |= TypeAttributes.UnicodeClass;
520                                 break;
521                         }
522
523                         fixed_buffer_type.__SetAttributes (fixed_buffer_type.Attributes | attribs);
524                         fixed_buffer_type.__SetLayout (0, buffer_size * type_size);
525 #else
526                         ctor = Module.PredefinedMembers.StructLayoutAttributeCtor.Resolve (Location);
527                         if (ctor == null)
528                                 return;
529
530                         var field_size = Module.PredefinedMembers.StructLayoutSize.Resolve (Location);
531                         var field_charset = Module.PredefinedMembers.StructLayoutCharSet.Resolve (Location);
532                         if (field_size == null || field_charset == null)
533                                 return;
534
535                         encoder = new AttributeEncoder ();
536                         encoder.Encode ((short)LayoutKind.Sequential);
537                         encoder.EncodeNamedArguments (
538                                 new [] { field_size, field_charset },
539                                 new Constant [] { 
540                                         new IntConstant (Compiler.BuiltinTypes, buffer_size * type_size, Location),
541                                         new IntConstant (Compiler.BuiltinTypes, (int) char_set, Location)
542                                 }
543                         );
544
545                         fixed_buffer_type.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), encoder.ToArray ());
546 #endif
547                         //
548                         // Don't emit FixedBufferAttribute attribute for private types
549                         //
550                         if ((ModFlags & Modifiers.PRIVATE) != 0)
551                                 return;
552
553                         ctor = Module.PredefinedMembers.FixedBufferAttributeCtor.Resolve (Location);
554                         if (ctor == null)
555                                 return;
556
557                         encoder = new AttributeEncoder ();
558                         encoder.EncodeTypeName (MemberType);
559                         encoder.Encode (buffer_size);
560                         encoder.EncodeEmptyNamedArguments ();
561
562                         FieldBuilder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), encoder.ToArray ());
563                 }
564         }
565
566         class FixedFieldSpec : FieldSpec
567         {
568                 readonly FieldSpec element;
569
570                 public FixedFieldSpec (ModuleContainer module, TypeSpec declaringType, IMemberDefinition definition, FieldInfo info, FieldSpec element, Modifiers modifiers)
571                         : base (declaringType, definition, PointerContainer.MakeType (module, element.MemberType), info, modifiers)
572                 {
573                         this.element = element;
574
575                         // It's never CLS-Compliant
576                         state &= ~StateFlags.CLSCompliant_Undetected;
577                 }
578
579                 public FieldSpec Element {
580                         get {
581                                 return element;
582                         }
583                 }
584                 
585                 public TypeSpec ElementType {
586                         get {
587                                 return element.MemberType;
588                         }
589                 }
590         }
591
592         //
593         // The Field class is used to represents class/struct fields during parsing.
594         //
595         public class Field : FieldBase {
596                 // <summary>
597                 //   Modifiers allowed in a class declaration
598                 // </summary>
599                 const Modifiers AllowedModifiers =
600                         Modifiers.NEW |
601                         Modifiers.PUBLIC |
602                         Modifiers.PROTECTED |
603                         Modifiers.INTERNAL |
604                         Modifiers.PRIVATE |
605                         Modifiers.STATIC |
606                         Modifiers.VOLATILE |
607                         Modifiers.UNSAFE |
608                         Modifiers.READONLY;
609
610                 public Field (TypeDefinition parent, FullNamedExpression type, Modifiers mod, MemberName name, Attributes attrs)
611                         : base (parent, type, mod, AllowedModifiers, name, attrs)
612                 {
613                 }
614
615                 bool CanBeVolatile ()
616                 {
617                         switch (MemberType.BuiltinType) {
618                         case BuiltinTypeSpec.Type.Bool:
619                         case BuiltinTypeSpec.Type.Char:
620                         case BuiltinTypeSpec.Type.SByte:
621                         case BuiltinTypeSpec.Type.Byte:
622                         case BuiltinTypeSpec.Type.Short:
623                         case BuiltinTypeSpec.Type.UShort:
624                         case BuiltinTypeSpec.Type.Int:
625                         case BuiltinTypeSpec.Type.UInt:
626                         case BuiltinTypeSpec.Type.Float:
627                         case BuiltinTypeSpec.Type.UIntPtr:
628                         case BuiltinTypeSpec.Type.IntPtr:
629                                 return true;
630                         }
631
632                         if (TypeSpec.IsReferenceType (MemberType))
633                                 return true;
634
635                         if (MemberType.IsPointer)
636                                 return true;
637
638                         if (MemberType.IsEnum) {
639                                 switch (EnumSpec.GetUnderlyingType (MemberType).BuiltinType) {
640                                 case BuiltinTypeSpec.Type.SByte:
641                                 case BuiltinTypeSpec.Type.Byte:
642                                 case BuiltinTypeSpec.Type.Short:
643                                 case BuiltinTypeSpec.Type.UShort:
644                                 case BuiltinTypeSpec.Type.Int:
645                                 case BuiltinTypeSpec.Type.UInt:
646                                         return true;
647                                 default:
648                                         return false;
649                                 }
650                         }
651
652                         return false;
653                 }
654
655                 public override void Accept (StructuralVisitor visitor)
656                 {
657                         visitor.Visit (this);
658                 }
659                 
660                 public override bool Define ()
661                 {
662                         if (!base.Define ())
663                                 return false;
664
665                         MetaType[] required_modifier = null;
666                         if ((ModFlags & Modifiers.VOLATILE) != 0) {
667                                 var mod = Module.PredefinedTypes.IsVolatile.Resolve ();
668                                 if (mod != null)
669                                         required_modifier = new MetaType[] { mod.GetMetaInfo () };
670                         }
671
672                         FieldBuilder = Parent.TypeBuilder.DefineField (
673                                 Name, member_type.GetMetaInfo (), required_modifier, null, ModifiersExtensions.FieldAttr (ModFlags));
674
675                         spec = new FieldSpec (Parent.Definition, this, MemberType, FieldBuilder, ModFlags);
676
677                         //
678                         // Don't cache inaccessible fields except for struct where we
679                         // need them for definitive assignment checks
680                         //
681                         if ((ModFlags & Modifiers.BACKING_FIELD) == 0 || Parent.Kind == MemberKind.Struct) {
682                                 Parent.MemberCache.AddMember (spec);
683                         }
684
685                         if (initializer != null) {
686                                 Parent.RegisterFieldForInitialization (this, new FieldInitializer (this, initializer, TypeExpression.Location));
687                         }
688
689                         if (declarators != null) {
690                                 foreach (var d in declarators) {
691                                         var f = new Field (Parent, d.GetFieldTypeExpression (this), ModFlags, new MemberName (d.Name.Value, d.Name.Location), OptAttributes);
692                                         if (d.Initializer != null)
693                                                 f.initializer = d.Initializer;
694
695                                         f.Define ();
696                                         Parent.PartialContainer.Members.Add (f);
697                                 }
698                         }
699
700                         return true;
701                 }
702
703                 protected override void DoMemberTypeIndependentChecks ()
704                 {
705                         if ((Parent.PartialContainer.ModFlags & Modifiers.READONLY) != 0 && (ModFlags & (Modifiers.READONLY | Modifiers.STATIC)) == 0) {
706                                 Report.Error (8340, Location, "`{0}': Instance fields in readonly structs must be readonly",
707                                         GetSignatureForError ());
708                         }
709
710                         base.DoMemberTypeIndependentChecks ();
711                 }
712
713                 protected override void DoMemberTypeDependentChecks ()
714                 {
715                         if ((ModFlags & Modifiers.BACKING_FIELD) != 0)
716                                 return;
717
718                         base.DoMemberTypeDependentChecks ();
719
720                         if ((ModFlags & Modifiers.VOLATILE) != 0) {
721                                 if (!CanBeVolatile ()) {
722                                         Report.Error (677, Location, "`{0}': A volatile field cannot be of the type `{1}'",
723                                                 GetSignatureForError (), MemberType.GetSignatureForError ());
724                                 }
725
726                                 if ((ModFlags & Modifiers.READONLY) != 0) {
727                                         Report.Error (678, Location, "`{0}': A field cannot be both volatile and readonly",
728                                                 GetSignatureForError ());
729                                 }
730                         }
731                 }
732
733                 protected override bool VerifyClsCompliance ()
734                 {
735                         if (!base.VerifyClsCompliance ())
736                                 return false;
737
738                         if ((ModFlags & Modifiers.VOLATILE) != 0) {
739                                 Report.Warning (3026, 1, Location, "CLS-compliant field `{0}' cannot be volatile", GetSignatureForError ());
740                         }
741
742                         return true;
743                 }
744         }
745
746         class PrimaryConstructorField : Field
747         {
748                 //
749                 // Proxy resolved parameter type expression to avoid type double resolve
750                 // and problems with correct resolve context on partial classes
751                 //
752                 sealed class TypeExpressionFromParameter : TypeExpr
753                 {
754                         Parameter parameter;
755
756                         public TypeExpressionFromParameter (Parameter parameter)
757                         {
758                                 this.parameter = parameter;
759                                 eclass = ExprClass.Type;
760                                 loc = parameter.Location;
761                         }
762
763                         public override TypeSpec ResolveAsType (IMemberContext mc, bool allowUnboundTypeArguments)
764                         {
765                                 return parameter.Type;
766                         }
767                 }
768
769                 public PrimaryConstructorField (TypeDefinition parent, Parameter parameter)
770                         : base (parent, new TypeExpressionFromParameter (parameter), Modifiers.PRIVATE, new MemberName (parameter.Name, parameter.Location), null)
771                 {
772                         caching_flags |= Flags.IsUsed | Flags.IsAssigned;
773                 }
774
775                 public override string GetSignatureForError ()
776                 {
777                         return MemberName.Name;
778                 }
779         }
780 }