Don't multiply fixed buffer size (it's done by runtime). Fixes #654058
[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 //
13
14 using System;
15 using System.Collections.Generic;
16 using System.Reflection;
17 using System.Reflection.Emit;
18 using System.Runtime.InteropServices;
19
20 namespace Mono.CSharp
21 {
22         public class FieldDeclarator
23         {
24                 public FieldDeclarator (SimpleMemberName name, Expression initializer)
25                 {
26                         this.Name = name;
27                         this.Initializer = initializer;
28                 }
29
30                 #region Properties
31
32                 public SimpleMemberName Name { get; private set; }
33                 public Expression Initializer { get; private set; }
34
35                 #endregion
36         }
37
38         //
39         // Abstract class for all fields
40         //
41         abstract public class FieldBase : MemberBase
42         {
43                 protected FieldBuilder FieldBuilder;
44                 protected FieldSpec spec;
45                 public Status status;
46                 protected Expression initializer;
47                 protected List<FieldDeclarator> declarators;
48
49                 [Flags]
50                 public enum Status : byte {
51                         HAS_OFFSET = 4          // Used by FieldMember.
52                 }
53
54                 static readonly string[] attribute_targets = new string [] { "field" };
55
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,
59                                 name, attrs)
60                 {
61                         if ((mod & Modifiers.ABSTRACT) != 0)
62                                 Report.Error (681, Location, "The modifier 'abstract' is not valid on fields. Try using a property instead");
63                 }
64
65                 #region Properties
66
67                 public override AttributeTargets AttributeTargets {
68                         get {
69                                 return AttributeTargets.Field;
70                         }
71                 }
72
73                 public Expression Initializer {
74                         get {
75                                 return initializer;
76                         }
77                         set {
78                                 this.initializer = value;
79                         }
80                 }
81
82                 public FieldSpec Spec {
83                         get {
84                                 return spec;
85                         }
86                 }
87
88                 public override string[] ValidAttributeTargets  {
89                         get {
90                                 return attribute_targets;
91                         }
92                 }
93
94                 #endregion
95
96                 public void AddDeclarator (FieldDeclarator declarator)
97                 {
98                         if (declarators == null)
99                                 declarators = new List<FieldDeclarator> (2);
100
101                         declarators.Add (declarator);
102
103                         // TODO: This will probably break
104                         Parent.AddMember (this, declarator.Name.Value);
105                 }
106
107                 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
108                 {
109                         if (a.Type == pa.FieldOffset) {
110                                 status |= Status.HAS_OFFSET;
111
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)");
114                                         return;
115                                 }
116
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");
119                                         return;
120                                 }
121                         }
122
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");
125                                 return;
126                         }
127
128 #if false
129                         if (a.Type == pa.MarshalAs) {
130                                 UnmanagedMarshal marshal = a.GetMarshal (this);
131                                 if (marshal != null) {
132                                         FieldBuilder.SetMarshal (marshal);
133                                 }
134                                 return;
135                         }
136 #endif
137                         if ((a.HasSecurityAttribute)) {
138                                 a.Error_InvalidSecurityParent ();
139                                 return;
140                         }
141
142                         if (a.Type == pa.Dynamic) {
143                                 a.Error_MisusedDynamicAttribute ();
144                                 return;
145                         }
146
147                         FieldBuilder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), cdata);
148                 }
149
150                 public void SetCustomAttribute (MethodSpec ctor, byte[] data)
151                 {
152                         FieldBuilder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), data);
153                 }
154
155                 protected override bool CheckBase ()
156                 {
157                         if (!base.CheckBase ())
158                                 return false;
159
160                         MemberSpec candidate;
161                         var conflict_symbol = MemberCache.FindBaseMember (this, out candidate);
162                         if (conflict_symbol == null)
163                                 conflict_symbol = candidate;
164
165                         if (conflict_symbol == null) {
166                                 if ((ModFlags & Modifiers.NEW) != 0) {
167                                         Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required",
168                                                 GetSignatureForError ());
169                                 }
170                         } else {
171                                 if ((ModFlags & (Modifiers.NEW | Modifiers.OVERRIDE | Modifiers.BACKING_FIELD)) == 0) {
172                                         Report.SymbolRelatedToPreviousError (conflict_symbol);
173                                         Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
174                                                 GetSignatureForError (), conflict_symbol.GetSignatureForError ());
175                                 }
176
177                                 if (conflict_symbol.IsAbstract) {
178                                         Report.SymbolRelatedToPreviousError (conflict_symbol);
179                                         Report.Error (533, Location, "`{0}' hides inherited abstract member `{1}'",
180                                                 GetSignatureForError (), conflict_symbol.GetSignatureForError ());
181                                 }
182                         }
183  
184                         return true;
185                 }
186
187                 public virtual Constant ConvertInitializer (ResolveContext rc, Constant expr)
188                 {
189                         return expr.ConvertImplicitly (rc, MemberType);
190                 }
191
192                 protected override void DoMemberTypeDependentChecks ()
193                 {
194                         base.DoMemberTypeDependentChecks ();
195
196                         if (MemberType.IsGenericParameter)
197                                 return;
198
199                         if (MemberType.IsStatic)
200                                 Error_VariableOfStaticClass (Location, GetSignatureForError (), MemberType, Report);
201
202                         CheckBase ();
203                         IsTypePermitted ();
204                 }
205
206                 //
207                 //   Represents header string for documentation comment.
208                 //
209                 public override string DocCommentHeader {
210                         get { return "F:"; }
211                 }
212
213                 public override void Emit ()
214                 {
215                         if (member_type == InternalType.Dynamic) {
216                                 Compiler.PredefinedAttributes.Dynamic.EmitAttribute (FieldBuilder);
217                         } else if (!(Parent is CompilerGeneratedClass) && member_type.HasDynamicElement) {
218                                 Compiler.PredefinedAttributes.Dynamic.EmitAttribute (FieldBuilder, member_type);
219                         }
220
221                         if ((ModFlags & Modifiers.COMPILER_GENERATED) != 0 && !Parent.IsCompilerGenerated)
222                                 Compiler.PredefinedAttributes.CompilerGenerated.EmitAttribute (FieldBuilder);
223
224                         if (OptAttributes != null) {
225                                 OptAttributes.Emit ();
226                         }
227
228                         if (((status & Status.HAS_OFFSET) == 0) && (ModFlags & (Modifiers.STATIC | Modifiers.BACKING_FIELD)) == 0 && Parent.PartialContainer.HasExplicitLayout) {
229                                 Report.Error (625, Location, "`{0}': Instance field types marked with StructLayout(LayoutKind.Explicit) must have a FieldOffset attribute", GetSignatureForError ());
230                         }
231
232                         base.Emit ();
233                 }
234
235                 public static void Error_VariableOfStaticClass (Location loc, string variable_name, TypeSpec static_class, Report Report)
236                 {
237                         Report.SymbolRelatedToPreviousError (static_class);
238                         Report.Error (723, loc, "`{0}': cannot declare variables of static types",
239                                 variable_name);
240                 }
241
242                 protected override bool VerifyClsCompliance ()
243                 {
244                         if (!base.VerifyClsCompliance ())
245                                 return false;
246
247                         if (!MemberType.IsCLSCompliant () || this is FixedField) {
248                                 Report.Warning (3003, 1, Location, "Type of `{0}' is not CLS-compliant",
249                                         GetSignatureForError ());
250                         }
251                         return true;
252                 }
253         }
254
255         //
256         // Field specification
257         //
258         public class FieldSpec : MemberSpec, IInterfaceMemberSpec
259         {
260                 FieldInfo metaInfo;
261                 TypeSpec memberType;
262
263                 public FieldSpec (TypeSpec declaringType, IMemberDefinition definition, TypeSpec memberType, FieldInfo info, Modifiers modifiers)
264                         : base (MemberKind.Field, declaringType, definition, modifiers)
265                 {
266                         this.metaInfo = info;
267                         this.memberType = memberType;
268                 }
269
270                 #region Properties
271
272                 public bool IsReadOnly {
273                         get {
274                                 return (Modifiers & Modifiers.READONLY) != 0;
275                         }
276                 }
277
278                 public TypeSpec MemberType {
279                         get {
280                                 return memberType;
281                         }
282                 }
283
284 #endregion
285
286                 public FieldInfo GetMetaInfo ()
287                 {
288                         if ((state & StateFlags.PendingMetaInflate) != 0) {
289                                 var decl_meta = DeclaringType.GetMetaInfo ();
290                                 if (DeclaringType.IsTypeBuilder) {
291                                         metaInfo = TypeBuilder.GetField (decl_meta, metaInfo);
292                                 } else {
293                                         var orig_token = metaInfo.MetadataToken;
294                                         metaInfo = decl_meta.GetField (Name, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static);
295                                         if (metaInfo.MetadataToken != orig_token)
296                                                 throw new NotImplementedException ("Resolved to wrong meta token");
297
298                                         // What a stupid API, does not work because field handle is imported
299                                         // metaInfo = FieldInfo.GetFieldFromHandle (metaInfo.FieldHandle, DeclaringType.MetaInfo.TypeHandle);
300                                 }
301
302                                 state &= ~StateFlags.PendingMetaInflate;
303                         }
304
305                         return metaInfo;
306                 }
307
308                 public override MemberSpec InflateMember (TypeParameterInflator inflator)
309                 {
310                         var fs = (FieldSpec) base.InflateMember (inflator);
311                         fs.memberType = inflator.Inflate (memberType);
312                         return fs;
313                 }
314
315                 public FieldSpec Mutate (TypeParameterMutator mutator)
316                 {
317                         var decl = DeclaringType;
318                         if (DeclaringType.IsGenericOrParentIsGeneric)
319                                 decl = mutator.Mutate (decl);
320
321                         if (decl == DeclaringType)
322                                 return this;
323
324                         var fs = (FieldSpec) MemberwiseClone ();
325                         fs.declaringType = decl;
326                         fs.state |= StateFlags.PendingMetaInflate;
327
328                         // Gets back FieldInfo in case of metaInfo was inflated
329                         fs.metaInfo = MemberCache.GetMember (TypeParameterMutator.GetMemberDeclaringType (DeclaringType), this).metaInfo;
330                         return fs;
331                 }
332         }
333
334         /// <summary>
335         /// Fixed buffer implementation
336         /// </summary>
337         public class FixedField : FieldBase
338         {
339                 public const string FixedElementName = "FixedElementField";
340                 static int GlobalCounter = 0;
341
342                 TypeBuilder fixed_buffer_type;
343
344                 const Modifiers AllowedModifiers =
345                         Modifiers.NEW |
346                         Modifiers.PUBLIC |
347                         Modifiers.PROTECTED |
348                         Modifiers.INTERNAL |
349                         Modifiers.PRIVATE |
350                         Modifiers.UNSAFE;
351
352                 public FixedField (DeclSpace parent, FullNamedExpression type, Modifiers mod, MemberName name, Attributes attrs)
353                         : base (parent, type, mod, AllowedModifiers, name, attrs)
354                 {
355                 }
356
357                 #region Properties
358
359                 //
360                 // Explicit struct layout set by parent
361                 //
362                 public CharSet? CharSet {
363                         get; set;
364                 }               
365
366                 #endregion
367
368                 public override Constant ConvertInitializer (ResolveContext rc, Constant expr)
369                 {
370                         return expr.ImplicitConversionRequired (rc, TypeManager.int32_type, Location);
371                 }
372
373                 public override bool Define ()
374                 {
375                         if (!base.Define ())
376                                 return false;
377
378                         if (!TypeManager.IsPrimitiveType (MemberType)) {
379                                 Report.Error (1663, Location,
380                                         "`{0}': Fixed size buffers type must be one of the following: bool, byte, short, int, long, char, sbyte, ushort, uint, ulong, float or double",
381                                         GetSignatureForError ());
382                         } else if (declarators != null) {
383                                 var t = new TypeExpression (MemberType, TypeExpression.Location);
384                                 int index = Parent.PartialContainer.Fields.IndexOf (this);
385                                 foreach (var d in declarators) {
386                                         var f = new FixedField (Parent, t, ModFlags, new MemberName (d.Name.Value, d.Name.Location), OptAttributes);
387                                         f.initializer = d.Initializer;
388                                         ((ConstInitializer) f.initializer).Name = d.Name.Value;
389                                         Parent.PartialContainer.Fields.Insert (++index, f);
390                                 }
391                         }
392                         
393                         // Create nested fixed buffer container
394                         string name = String.Format ("<{0}>__FixedBuffer{1}", Name, GlobalCounter++);
395                         fixed_buffer_type = Parent.TypeBuilder.DefineNestedType (name, Parent.Module.DefaultCharSetType |
396                                 TypeAttributes.NestedPublic | TypeAttributes.Sealed | TypeAttributes.BeforeFieldInit, TypeManager.value_type.GetMetaInfo ());
397
398                         fixed_buffer_type.DefineField (FixedElementName, MemberType.GetMetaInfo (), FieldAttributes.Public);
399                         
400                         FieldBuilder = Parent.TypeBuilder.DefineField (Name, fixed_buffer_type, ModifiersExtensions.FieldAttr (ModFlags));
401                         var element_spec = new FieldSpec (null, this, MemberType, FieldBuilder, ModFlags);
402                         spec = new FixedFieldSpec (Parent.Definition, this, FieldBuilder, element_spec, ModFlags);
403
404                         Parent.MemberCache.AddMember (spec);
405                         return true;
406                 }
407
408                 protected override void DoMemberTypeIndependentChecks ()
409                 {
410                         base.DoMemberTypeIndependentChecks ();
411
412                         if (!IsUnsafe)
413                                 Expression.UnsafeError (Report, Location);
414
415                         if (Parent.PartialContainer.Kind != MemberKind.Struct) {
416                                 Report.Error (1642, Location, "`{0}': Fixed size buffer fields may only be members of structs",
417                                         GetSignatureForError ());
418                         }
419                 }
420
421                 public override void Emit()
422                 {
423                         ResolveContext rc = new ResolveContext (this);
424                         IntConstant buffer_size_const = initializer.Resolve (rc) as IntConstant;
425                         if (buffer_size_const == null)
426                                 return;
427
428                         int buffer_size = buffer_size_const.Value;
429
430                         if (buffer_size <= 0) {
431                                 Report.Error (1665, Location, "`{0}': Fixed size buffers must have a length greater than zero", GetSignatureForError ());
432                                 return;
433                         }
434
435                         int type_size = Expression.GetTypeSize (MemberType);
436
437                         if (buffer_size > int.MaxValue / type_size) {
438                                 Report.Error (1664, Location, "Fixed size buffer `{0}' of length `{1}' and type `{2}' exceeded 2^31 limit",
439                                         GetSignatureForError (), buffer_size.ToString (), TypeManager.CSharpName (MemberType));
440                                 return;
441                         }
442
443                         EmitFieldSize (buffer_size);
444
445                         Compiler.PredefinedAttributes.UnsafeValueType.EmitAttribute (fixed_buffer_type);
446                         Compiler.PredefinedAttributes.CompilerGenerated.EmitAttribute (fixed_buffer_type);
447                         fixed_buffer_type.CreateType ();
448
449                         base.Emit ();
450                 }
451
452                 void EmitFieldSize (int buffer_size)
453                 {
454                         PredefinedAttribute pa;
455                         AttributeEncoder encoder;
456
457                         pa = Compiler.PredefinedAttributes.StructLayout;
458                         if (pa.Constructor == null && !pa.ResolveConstructor (Location, TypeManager.short_type))
459                                 return;
460
461                         var interop_charset = TypeManager.CoreLookupType (Compiler, "System.Runtime.InteropServices", "CharSet", MemberKind.Enum, true);
462                         if (interop_charset == null)
463                                 return;
464
465                         var field_size = pa.GetField ("Size", TypeManager.int32_type, Location);
466                         var field_charset = pa.GetField ("CharSet", interop_charset, Location);
467                         if (field_size == null || field_charset == null)
468                                 return;
469
470                         var char_set = CharSet ?? Module.DefaultCharSet;
471
472                         encoder = new AttributeEncoder (false);
473                         encoder.Encode ((short)LayoutKind.Sequential);
474                         encoder.EncodeNamedArguments (
475                                 new [] { field_size, field_charset },
476                                 new Constant [] { new IntConstant (buffer_size, Location), new IntConstant ((int) char_set, Location) }
477                         );
478
479                         pa.EmitAttribute (fixed_buffer_type, encoder);
480
481                         //
482                         // Don't emit FixedBufferAttribute attribute for private types
483                         //
484                         if ((ModFlags & Modifiers.PRIVATE) != 0)
485                                 return;
486
487                         pa = Compiler.PredefinedAttributes.FixedBuffer;
488                         if (pa.Constructor == null && !pa.ResolveConstructor (Location, TypeManager.type_type, TypeManager.int32_type))
489                                 return;
490
491                         encoder = new AttributeEncoder (false);
492                         encoder.EncodeTypeName (MemberType);
493                         encoder.Encode (buffer_size);
494                         encoder.EncodeEmptyNamedArguments ();
495
496                         pa.EmitAttribute (FieldBuilder, encoder);
497                 }
498         }
499
500         class FixedFieldSpec : FieldSpec
501         {
502                 readonly FieldSpec element;
503
504                 public FixedFieldSpec (TypeSpec declaringType, IMemberDefinition definition, FieldInfo info, FieldSpec element, Modifiers modifiers)
505                         : base (declaringType, definition, element.MemberType, info, modifiers)
506                 {
507                         this.element = element;
508
509                         // It's never CLS-Compliant
510                         state &= ~StateFlags.CLSCompliant_Undetected;
511                 }
512
513                 public FieldSpec Element {
514                         get {
515                                 return element;
516                         }
517                 }
518
519                 public TypeSpec ElementType {
520                         get {
521                                 return MemberType;
522                         }
523                 }
524         }
525
526         //
527         // The Field class is used to represents class/struct fields during parsing.
528         //
529         public class Field : FieldBase {
530                 // <summary>
531                 //   Modifiers allowed in a class declaration
532                 // </summary>
533                 const Modifiers AllowedModifiers =
534                         Modifiers.NEW |
535                         Modifiers.PUBLIC |
536                         Modifiers.PROTECTED |
537                         Modifiers.INTERNAL |
538                         Modifiers.PRIVATE |
539                         Modifiers.STATIC |
540                         Modifiers.VOLATILE |
541                         Modifiers.UNSAFE |
542                         Modifiers.READONLY;
543
544                 public Field (DeclSpace parent, FullNamedExpression type, Modifiers mod, MemberName name,
545                               Attributes attrs)
546                         : base (parent, type, mod, AllowedModifiers, name, attrs)
547                 {
548                 }
549
550                 bool CanBeVolatile ()
551                 {
552                         if (TypeManager.IsReferenceType (MemberType))
553                                 return true;
554
555                         if (MemberType == TypeManager.bool_type || MemberType == TypeManager.char_type ||
556                                 MemberType == TypeManager.sbyte_type || MemberType == TypeManager.byte_type ||
557                                 MemberType == TypeManager.short_type || MemberType == TypeManager.ushort_type ||
558                                 MemberType == TypeManager.int32_type || MemberType == TypeManager.uint32_type ||
559                                 MemberType == TypeManager.float_type ||
560                                 MemberType == TypeManager.intptr_type || MemberType == TypeManager.uintptr_type)
561                                 return true;
562
563                         if (MemberType.IsEnum)
564                                 return true;
565
566                         return false;
567                 }
568
569                 public override bool Define ()
570                 {
571                         if (!base.Define ())
572                                 return false;
573
574                         Type[] required_modifier = null;
575                         if ((ModFlags & Modifiers.VOLATILE) != 0) {
576                                 if (TypeManager.isvolatile_type == null)
577                                         TypeManager.isvolatile_type = TypeManager.CoreLookupType (Compiler,
578                                                 "System.Runtime.CompilerServices", "IsVolatile", MemberKind.Class, true);
579
580                                 if (TypeManager.isvolatile_type != null)
581                                         required_modifier = new Type[] { TypeManager.isvolatile_type.GetMetaInfo () };
582                         }
583
584                         FieldBuilder = Parent.TypeBuilder.DefineField (
585                                 Name, member_type.GetMetaInfo (), required_modifier, null, ModifiersExtensions.FieldAttr (ModFlags));
586
587                         spec = new FieldSpec (Parent.Definition, this, MemberType, FieldBuilder, ModFlags);
588
589                         // Don't cache inaccessible fields
590                         if ((ModFlags & Modifiers.BACKING_FIELD) == 0) {
591                                 Parent.MemberCache.AddMember (spec);
592                         }
593
594                         if (initializer != null) {
595                                 ((TypeContainer) Parent).RegisterFieldForInitialization (this,
596                                         new FieldInitializer (spec, initializer, this));
597                         }
598
599                         if (declarators != null) {
600                                 var t = new TypeExpression (MemberType, TypeExpression.Location);
601                                 int index = Parent.PartialContainer.Fields.IndexOf (this);
602                                 foreach (var d in declarators) {
603                                         var f = new Field (Parent, t, ModFlags, new MemberName (d.Name.Value, d.Name.Location), OptAttributes);
604                                         if (d.Initializer != null)
605                                                 f.initializer = d.Initializer;
606
607                                         Parent.PartialContainer.Fields.Insert (++index, f);
608                                 }
609                         }
610
611                         return true;
612                 }
613
614                 protected override void DoMemberTypeDependentChecks ()
615                 {
616                         if ((ModFlags & Modifiers.BACKING_FIELD) != 0)
617                                 return;
618
619                         base.DoMemberTypeDependentChecks ();
620
621                         if ((ModFlags & Modifiers.VOLATILE) != 0) {
622                                 if (!CanBeVolatile ()) {
623                                         Report.Error (677, Location, "`{0}': A volatile field cannot be of the type `{1}'",
624                                                 GetSignatureForError (), TypeManager.CSharpName (MemberType));
625                                 }
626
627                                 if ((ModFlags & Modifiers.READONLY) != 0) {
628                                         Report.Error (678, Location, "`{0}': A field cannot be both volatile and readonly",
629                                                 GetSignatureForError ());
630                                 }
631                         }
632                 }
633
634                 protected override bool VerifyClsCompliance ()
635                 {
636                         if (!base.VerifyClsCompliance ())
637                                 return false;
638
639                         if ((ModFlags & Modifiers.VOLATILE) != 0) {
640                                 Report.Warning (3026, 1, Location, "CLS-compliant field `{0}' cannot be volatile", GetSignatureForError ());
641                         }
642
643                         return true;
644                 }
645         }
646 }