2007-08-16 Marek Safar <marek.safar@gmail.com>
[mono.git] / mcs / mcs / assign.cs
1 //
2 // assign.cs: Assignments.
3 //
4 // Author:
5 //   Miguel de Icaza (miguel@ximian.com)
6 //   Martin Baulig (martin@ximian.com)
7 //
8 // (C) 2001, 2002, 2003 Ximian, Inc.
9 // (C) 2004 Novell, Inc
10 //
11 using System;
12 using System.Reflection;
13 using System.Reflection.Emit;
14
15 namespace Mono.CSharp {
16
17         /// <summary>
18         ///   This interface is implemented by expressions that can be assigned to.
19         /// </summary>
20         /// <remarks>
21         ///   This interface is implemented by Expressions whose values can not
22         ///   store the result on the top of the stack.
23         ///
24         ///   Expressions implementing this (Properties, Indexers and Arrays) would
25         ///   perform an assignment of the Expression "source" into its final
26         ///   location.
27         ///
28         ///   No values on the top of the stack are expected to be left by
29         ///   invoking this method.
30         /// </remarks>
31         public interface IAssignMethod {
32                 //
33                 // This is an extra version of Emit. If leave_copy is `true'
34                 // A copy of the expression will be left on the stack at the
35                 // end of the code generated for EmitAssign
36                 //
37                 void Emit (EmitContext ec, bool leave_copy);
38
39                 //
40                 // This method does the assignment
41                 // `source' will be stored into the location specified by `this'
42                 // if `leave_copy' is true, a copy of `source' will be left on the stack
43                 // if `prepare_for_load' is true, when `source' is emitted, there will
44                 // be data on the stack that it can use to compuatate its value. This is
45                 // for expressions like a [f ()] ++, where you can't call `f ()' twice.
46                 //
47                 void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load);
48
49                 /*
50                 For simple assignments, this interface is very simple, EmitAssign is called with source
51                 as the source expression and leave_copy and prepare_for_load false.
52
53                 For compound assignments it gets complicated.
54
55                 EmitAssign will be called as before, however, prepare_for_load will be
56                 true. The @source expression will contain an expression
57                 which calls Emit. So, the calls look like:
58
59                 this.EmitAssign (ec, source, false, true) ->
60                         source.Emit (ec); ->
61                                 [...] ->
62                                         this.Emit (ec, false); ->
63                                         end this.Emit (ec, false); ->
64                                 end [...]
65                         end source.Emit (ec);
66                 end this.EmitAssign (ec, source, false, true)
67
68
69                 When prepare_for_load is true, EmitAssign emits a `token' on the stack that
70                 Emit will use for its state.
71
72                 Let's take FieldExpr as an example. assume we are emitting f ().y += 1;
73
74                 Here is the call tree again. This time, each call is annotated with the IL
75                 it produces:
76
77                 this.EmitAssign (ec, source, false, true)
78                         call f
79                         dup
80
81                         Binary.Emit ()
82                                 this.Emit (ec, false);
83                                 ldfld y
84                                 end this.Emit (ec, false);
85
86                                 IntConstant.Emit ()
87                                 ldc.i4.1
88                                 end IntConstant.Emit
89
90                                 add
91                         end Binary.Emit ()
92
93                         stfld
94                 end this.EmitAssign (ec, source, false, true)
95
96                 Observe two things:
97                         1) EmitAssign left a token on the stack. It was the result of f ().
98                         2) This token was used by Emit
99
100                 leave_copy (in both EmitAssign and Emit) tells the compiler to leave a copy
101                 of the expression at that point in evaluation. This is used for pre/post inc/dec
102                 and for a = x += y. Let's do the above example with leave_copy true in EmitAssign
103
104                 this.EmitAssign (ec, source, true, true)
105                         call f
106                         dup
107
108                         Binary.Emit ()
109                                 this.Emit (ec, false);
110                                 ldfld y
111                                 end this.Emit (ec, false);
112
113                                 IntConstant.Emit ()
114                                 ldc.i4.1
115                                 end IntConstant.Emit
116
117                                 add
118                         end Binary.Emit ()
119
120                         dup
121                         stloc temp
122                         stfld
123                         ldloc temp
124                 end this.EmitAssign (ec, source, true, true)
125
126                 And with it true in Emit
127
128                 this.EmitAssign (ec, source, false, true)
129                         call f
130                         dup
131
132                         Binary.Emit ()
133                                 this.Emit (ec, true);
134                                 ldfld y
135                                 dup
136                                 stloc temp
137                                 end this.Emit (ec, true);
138
139                                 IntConstant.Emit ()
140                                 ldc.i4.1
141                                 end IntConstant.Emit
142
143                                 add
144                         end Binary.Emit ()
145
146                         stfld
147                         ldloc temp
148                 end this.EmitAssign (ec, source, false, true)
149
150                 Note that these two examples are what happens for ++x and x++, respectively.
151                 */
152         }
153
154         /// <summary>
155         ///   An Expression to hold a temporary value.
156         /// </summary>
157         /// <remarks>
158         ///   The LocalTemporary class is used to hold temporary values of a given
159         ///   type to "simulate" the expression semantics on property and indexer
160         ///   access whose return values are void.
161         ///
162         ///   The local temporary is used to alter the normal flow of code generation
163         ///   basically it creates a local variable, and its emit instruction generates
164         ///   code to access this value, return its address or save its value.
165         ///
166         ///   If `is_address' is true, then the value that we store is the address to the
167         ///   real value, and not the value itself.
168         ///
169         ///   This is needed for a value type, because otherwise you just end up making a
170         ///   copy of the value on the stack and modifying it. You really need a pointer
171         ///   to the origional value so that you can modify it in that location. This
172         ///   Does not happen with a class because a class is a pointer -- so you always
173         ///   get the indirection.
174         ///
175         ///   The `is_address' stuff is really just a hack. We need to come up with a better
176         ///   way to handle it.
177         /// </remarks>
178         public class LocalTemporary : Expression, IMemoryLocation {
179                 LocalBuilder builder;
180                 bool is_address;
181
182                 public LocalTemporary (Type t) : this (t, false) {}
183
184                 public LocalTemporary (Type t, bool is_address)
185                 {
186                         type = t;
187                         eclass = ExprClass.Value;
188                         this.is_address = is_address;
189                 }
190
191                 public LocalTemporary (LocalBuilder b, Type t)
192                 {
193                         type = t;
194                         eclass = ExprClass.Value;
195                         loc = Location.Null;
196                         builder = b;
197                 }
198
199                 public void Release (EmitContext ec)
200                 {
201                         ec.FreeTemporaryLocal (builder, type);
202                         builder = null;
203                 }
204
205                 public override Expression DoResolve (EmitContext ec)
206                 {
207                         return this;
208                 }
209
210                 public override void Emit (EmitContext ec)
211                 {
212                         ILGenerator ig = ec.ig;
213
214                         if (builder == null)
215                                 throw new InternalErrorException ("Emit without Store, or after Release");
216
217                         ig.Emit (OpCodes.Ldloc, builder);
218                         // we need to copy from the pointer
219                         if (is_address)
220                                 LoadFromPtr (ig, type);
221                 }
222
223                 // NB: if you have `is_address' on the stack there must
224                 // be a managed pointer. Otherwise, it is the type from
225                 // the ctor.
226                 public void Store (EmitContext ec)
227                 {
228                         ILGenerator ig = ec.ig;
229                         if (builder == null)
230                                 builder = ec.GetTemporaryLocal (is_address ? TypeManager.GetReferenceType (type): type);
231
232                         ig.Emit (OpCodes.Stloc, builder);
233                 }
234
235                 public void AddressOf (EmitContext ec, AddressOp mode)
236                 {
237                         if (builder == null)
238                                 builder = ec.GetTemporaryLocal (is_address ? TypeManager.GetReferenceType (type): type);
239
240                         // if is_address, than this is just the address anyways,
241                         // so we just return this.
242                         ILGenerator ig = ec.ig;
243
244                         if (is_address)
245                                 ig.Emit (OpCodes.Ldloc, builder);
246                         else
247                                 ig.Emit (OpCodes.Ldloca, builder);
248                 }
249
250                 public bool PointsToAddress {
251                         get {
252                                 return is_address;
253                         }
254                 }
255         }
256
257         /// <summary>
258         ///   The Assign node takes care of assigning the value of source into
259         ///   the expression represented by target.
260         /// </summary>
261         public class Assign : ExpressionStatement {
262                 protected Expression target, source, real_source;
263                 protected LocalTemporary temp = null, real_temp = null;
264                 protected Assign embedded = null;
265                 protected bool is_embedded = false;
266                 protected bool must_free_temp = false;
267
268                 public Assign (Expression target, Expression source)
269                         : this (target, source, target.Location)
270                 {
271                 }
272
273                 public Assign (Expression target, Expression source, Location l)
274                 {
275                         this.target = target;
276                         this.source = this.real_source = source;
277                         this.loc = l;
278                 }
279
280                 protected Assign (Assign embedded, Location l)
281                         : this (embedded.target, embedded.source, l)
282                 {
283                         this.is_embedded = true;
284                 }
285
286                 protected virtual Assign GetEmbeddedAssign (Location loc)
287                 {
288                         return new Assign (this, loc);
289                 }
290
291                 public Expression Target {
292                         get {
293                                 return target;
294                         }
295
296                         set {
297                                 target = value;
298                         }
299                 }
300
301                 public Expression Source {
302                         get {
303                                 return source;
304                         }
305
306                         set {
307                                 source = value;
308                         }
309                 }
310
311                 public static void error70 (EventInfo ei, Location l)
312                 {
313                         Report.Error (70, l, "The event `" + TypeManager.CSharpSignature (ei) +
314                                       "' can only appear on the left hand side of += or -= (except when" +
315                                       " used from within the type `" + ei.DeclaringType + "')");
316                 }
317
318                 //
319                 // Will return either `this' or an instance of `New'.
320                 //
321                 public override Expression DoResolve (EmitContext ec)
322                 {
323                         // Create an embedded assignment if our source is an assignment.
324                         if (source is Assign)
325                                 source = embedded = ((Assign) source).GetEmbeddedAssign (loc);
326
327                         real_source = source = source.Resolve (ec);
328                                                 
329                         if (source == null) {
330                                 // Ensure that we don't propagate the error as spurious "uninitialized variable" errors.
331                                 target = target.ResolveLValue (ec, EmptyExpression.Null, Location);
332                                 return null;
333                         }
334
335                         //
336                         // This is used in an embedded assignment.
337                         // As an example, consider the statement "A = X = Y = Z".
338                         //
339                         if (is_embedded && !(source is Constant)) {
340                                 // If this is the innermost assignment (the "Y = Z" in our example),
341                                 // create a new temporary local, otherwise inherit that variable
342                                 // from our child (the "X = (Y = Z)" inherits the local from the
343                                 // "Y = Z" assignment).
344
345                                 if (embedded == null) {
346                                         if (this is CompoundAssign)
347                                                 real_temp = temp = new LocalTemporary (target.Type);
348                                         else
349                                                 real_temp = temp = new LocalTemporary (source.Type);
350                                 } else
351                                         temp = embedded.temp;
352
353                                 // Set the source to the new temporary variable.
354                                 // This means that the following target.ResolveLValue () will tell
355                                 // the target to read it's source value from that variable.
356                                 source = temp;
357                         }
358
359                         // If we have an embedded assignment, use the embedded assignment's temporary
360                         // local variable as source.
361                         if (embedded != null)
362                                 source = (embedded.temp != null) ? embedded.temp : embedded.source;
363                         
364                         target = target.ResolveLValue (ec, source, Location);
365
366                         if (target == null)
367                                 return null;
368                         
369                         bool same_assignment = (embedded != null) ? embedded.Target.Equals(target) : source.Equals (target);
370                         if (same_assignment) {
371                                 Report.Warning (1717, 3, loc, "Assignment made to same variable; did you mean to assign something else?");
372                         }
373
374                         Type target_type = target.Type;
375                         Type source_type = real_source.Type;
376
377                         // If we're an embedded assignment, our parent will reuse our source as its
378                         // source, it won't read from our target.
379                         if (is_embedded)
380                                 type = source_type;
381                         else
382                                 type = target_type;
383                         eclass = ExprClass.Value;
384
385                         if (target is EventExpr) {
386                                 EventInfo ei = ((EventExpr) target).EventInfo;
387
388                                 Expression ml = MemberLookup (
389                                         ec.ContainerType, ec.ContainerType, ei.Name,
390                                         MemberTypes.Event, AllBindingFlags | BindingFlags.DeclaredOnly, loc);
391
392                                 if (ml == null) {
393                                         //
394                                         // If this is the case, then the Event does not belong
395                                         // to this Type and so, according to the spec
396                                         // is allowed to only appear on the left hand of
397                                         // the += and -= operators
398                                         //
399                                         // Note that target will not appear as an EventExpr
400                                         // in the case it is being referenced within the same type container;
401                                         // it will appear as a FieldExpr in that case.
402                                         //
403
404                                         if (!(source is BinaryDelegate)) {
405                                                 error70 (ei, loc);
406                                                 return null;
407                                         }
408                                 }
409                         }
410
411                         if (!(target is IAssignMethod) && (target.eclass != ExprClass.EventAccess)) {
412                                 Error_ValueAssignment (loc);
413                                 return null;
414                         }
415
416                         if ((source.eclass == ExprClass.Type) && (source is TypeExpr)) {
417                                 source.Error_UnexpectedKind (ec.DeclContainer, "variable or value", loc);
418                                 return null;
419                         } else if ((RootContext.Version == LanguageVersion.ISO_1) &&
420                                    (source is MethodGroupExpr)){
421                                 ((MethodGroupExpr) source).ReportUsageError ();
422                                 return null;
423
424                         }
425
426                         if (target_type == source_type){
427                                 if (source is New && target_type.IsValueType &&
428                                     (target.eclass != ExprClass.IndexerAccess) && (target.eclass != ExprClass.PropertyAccess)){
429                                         New n = (New) source;
430
431                                         if (n.SetValueTypeVariable (target))
432                                                 return n;
433                                         else
434                                                 return null;
435                                 }
436
437                                 return this;
438                         }
439
440                         //
441                         // If this assignment/operator was part of a compound binary
442                         // operator, then we allow an explicit conversion, as detailed
443                         // in the spec.
444                         //
445
446                         if (this is CompoundAssign){
447                                 CompoundAssign a = (CompoundAssign) this;
448
449                                 Binary b = source as Binary;
450                                 if (b != null){
451                                         //
452                                         // 1. if the source is explicitly convertible to the
453                                         //    target_type
454                                         //
455
456                                         source = Convert.ExplicitConversion (ec, source, target_type, loc);
457                                         if (source == null){
458                                                 a.original_source.Error_ValueCannotBeConverted (ec, loc, target_type, true);
459                                                 return null;
460                                         }
461
462                                         //
463                                         // 2. and the original right side is implicitly convertible to
464                                         // the type of target
465                                         //
466                                         if (Convert.ImplicitConversionExists (ec, a.original_source, target_type))
467                                                 return this;
468
469                                         //
470                                         // In the spec 2.4 they added: or if type of the target is int
471                                         // and the operator is a shift operator...
472                                         //
473                                         if (source_type == TypeManager.int32_type &&
474                                             (b.Oper == Binary.Operator.LeftShift || b.Oper == Binary.Operator.RightShift))
475                                                 return this;
476
477                                         a.original_source.Error_ValueCannotBeConverted (ec, loc, target_type, false);
478                                         return null;
479                                 }
480                         }
481
482                         if (source.eclass == ExprClass.MethodGroup && !TypeManager.IsDelegateType (target_type)) {
483                                 Report.Error (428, source.Location, "Cannot convert method group `{0}' to non-delegate type `{1}'. Did you intend to invoke the method?",
484                                         ((MethodGroupExpr)source).Name, target.GetSignatureForError ());
485                                 return null;
486                         }
487
488                         source = Convert.ImplicitConversionRequired (ec, source, target_type, loc);
489                         if (source == null)
490                                 return null;
491
492                         // If we're an embedded assignment, we need to create a new temporary variable
493                         // for the converted value.  Our parent will use this new variable as its source.
494                         // The same applies when we have an embedded assignment - in this case, we need
495                         // to convert our embedded assignment's temporary local variable to the correct
496                         // type and store it in a new temporary local.
497                         if (is_embedded || embedded != null) {
498                                 type = target_type;
499                                 temp = new LocalTemporary (type);
500                                 must_free_temp = true;
501                         }
502
503                         return this;
504                 }
505
506                 Expression EmitEmbedded (EmitContext ec)
507                 {
508                         // Emit an embedded assignment.
509
510                         if (real_temp != null) {
511                                 // If we're the innermost assignment, `real_source' is the right-hand
512                                 // expression which gets assigned to all the variables left of it.
513                                 // Emit this expression and store its result in real_temp.
514                                 real_source.Emit (ec);
515                                 real_temp.Store (ec);
516                         }
517
518                         if (embedded != null)
519                                 embedded.EmitEmbedded (ec);
520
521                         // This happens when we've done a type conversion, in this case source will be
522                         // the expression which does the type conversion from real_temp.
523                         // So emit it and store the result in temp; this is the var which will be read
524                         // by our parent.
525                         if (temp != real_temp) {
526                                 source.Emit (ec);
527                                 temp.Store (ec);
528                         }
529
530                         Expression temp_source = (temp != null) ? temp : source;
531                         ((IAssignMethod) target).EmitAssign (ec, temp_source, false, false);
532                         return temp_source;
533                 }
534
535                 void ReleaseEmbedded (EmitContext ec)
536                 {
537                         if (embedded != null)
538                                 embedded.ReleaseEmbedded (ec);
539
540                         if (real_temp != null)
541                                 real_temp.Release (ec);
542
543                         if (must_free_temp)
544                                 temp.Release (ec);
545                 }
546
547                 void Emit (EmitContext ec, bool is_statement)
548                 {
549                         if (target is EventExpr) {
550                                 ((EventExpr) target).EmitAddOrRemove (ec, source);
551                                 return;
552                         }
553
554                         IAssignMethod am = (IAssignMethod) target;
555
556                         Expression temp_source;
557                         if (embedded != null) {
558                                 temp_source = embedded.EmitEmbedded (ec);
559
560                                 if (temp != null) {
561                                         source.Emit (ec);
562                                         temp.Store (ec);
563                                         temp_source = temp;
564                                 }
565                         } else
566                                 temp_source = source;
567
568                         bool prepare_for_load = this is CompoundAssign && !(source is StringConcat);
569                         am.EmitAssign (ec, temp_source, !is_statement, prepare_for_load);
570
571                         if (embedded != null) {
572                                 if (temp != null)
573                                         temp.Release (ec);
574                                 embedded.ReleaseEmbedded (ec);
575                         }
576                 }
577
578                 public override void Emit (EmitContext ec)
579                 {
580                         Emit (ec, false);
581                 }
582
583                 public override void EmitStatement (EmitContext ec)
584                 {
585                         Emit (ec, true);
586                 }
587
588                 protected override void CloneTo (CloneContext clonectx, Expression t)
589                 {
590                         Assign _target = (Assign) t;
591
592                         _target.target = target.Clone (clonectx);
593                         _target.source = source.Clone (clonectx);
594                 }
595         }
596
597
598         // This class implements fields and events class initializers
599         public class FieldInitializer : Assign
600         {
601                 public readonly DeclSpace TypeContainer;
602
603                 public FieldInitializer (FieldBuilder field, Expression expression, DeclSpace container)
604                         : base (new FieldExpr (field, expression.Location, true), expression)
605                 {
606                         this.TypeContainer = container;
607                         if (!field.IsStatic)
608                                 ((FieldExpr)target).InstanceExpression = CompilerGeneratedThis.Instance;
609                 }
610
611                 public bool IsComplexInitializer {
612                         get {
613                                 if (embedded != null)
614                                         return true;
615
616                                 return !(source is Constant);
617                         }
618                 }
619
620                 public bool IsDefaultInitializer {
621                         get {
622                                 Constant c = source as Constant;
623                                 if (c == null)
624                                         return false;
625                                 
626                                 FieldExpr fe = (FieldExpr)target;
627                                 return c.IsDefaultInitializer (fe.Type);
628                         }
629                 }
630         }
631
632
633         //
634         // This class is used for compound assignments.
635         //
636         class CompoundAssign : Assign {
637                 Binary.Operator op;
638                 public Expression original_source;
639
640                 public CompoundAssign (Binary.Operator op, Expression target, Expression source)
641                         : base (target, source, target.Location)
642                 {
643                         original_source = source;
644                         this.op = op;
645                 }
646
647                 protected CompoundAssign (CompoundAssign embedded, Location l)
648                         : this (embedded.op, embedded.target, embedded.source)
649                 {
650                         this.is_embedded = true;
651                 }
652
653                 protected override Assign GetEmbeddedAssign (Location loc)
654                 {
655                         return new CompoundAssign (this, loc);
656                 }
657
658                 public override Expression DoResolve (EmitContext ec)
659                 {
660                         original_source = original_source.Resolve (ec);
661                         if (original_source == null)
662                                 return null;
663
664                         target = target.Resolve (ec);
665                         if (target == null)
666                                 return null;
667
668                         if (target is MethodGroupExpr){
669                                 Error_CannotAssign (((MethodGroupExpr)target).Name, target.ExprClassName);
670                                 return null;
671                         }
672                         //
673                         // Only now we can decouple the original source/target
674                         // into a tree, to guarantee that we do not have side
675                         // effects.
676                         //
677                         source = new Binary (op, target, original_source);
678                         return base.DoResolve (ec);
679                 }
680
681                 protected override void CloneTo (CloneContext clonectx, Expression t)
682                 {
683                         CompoundAssign target = (CompoundAssign) t;
684
685                         target.original_source = original_source.Clone (clonectx);
686                 }
687         }
688 }