2 // assign.cs: Assignments.
5 // Miguel de Icaza (miguel@ximian.com)
6 // Martin Baulig (martin@ximian.com)
7 // Marek Safar (marek.safar@gmail.com)
9 // Dual licensed under the terms of the MIT X11 or GNU GPL
11 // Copyright 2001, 2002, 2003 Ximian, Inc.
12 // Copyright 2004-2008 Novell, Inc
15 using System.Reflection;
16 using System.Reflection.Emit;
18 namespace Mono.CSharp {
21 /// This interface is implemented by expressions that can be assigned to.
24 /// This interface is implemented by Expressions whose values can not
25 /// store the result on the top of the stack.
27 /// Expressions implementing this (Properties, Indexers and Arrays) would
28 /// perform an assignment of the Expression "source" into its final
31 /// No values on the top of the stack are expected to be left by
32 /// invoking this method.
34 public interface IAssignMethod {
36 // This is an extra version of Emit. If leave_copy is `true'
37 // A copy of the expression will be left on the stack at the
38 // end of the code generated for EmitAssign
40 void Emit (EmitContext ec, bool leave_copy);
43 // This method does the assignment
44 // `source' will be stored into the location specified by `this'
45 // if `leave_copy' is true, a copy of `source' will be left on the stack
46 // if `prepare_for_load' is true, when `source' is emitted, there will
47 // be data on the stack that it can use to compuatate its value. This is
48 // for expressions like a [f ()] ++, where you can't call `f ()' twice.
50 void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load);
53 For simple assignments, this interface is very simple, EmitAssign is called with source
54 as the source expression and leave_copy and prepare_for_load false.
56 For compound assignments it gets complicated.
58 EmitAssign will be called as before, however, prepare_for_load will be
59 true. The @source expression will contain an expression
60 which calls Emit. So, the calls look like:
62 this.EmitAssign (ec, source, false, true) ->
65 this.Emit (ec, false); ->
66 end this.Emit (ec, false); ->
69 end this.EmitAssign (ec, source, false, true)
72 When prepare_for_load is true, EmitAssign emits a `token' on the stack that
73 Emit will use for its state.
75 Let's take FieldExpr as an example. assume we are emitting f ().y += 1;
77 Here is the call tree again. This time, each call is annotated with the IL
80 this.EmitAssign (ec, source, false, true)
85 this.Emit (ec, false);
87 end this.Emit (ec, false);
97 end this.EmitAssign (ec, source, false, true)
100 1) EmitAssign left a token on the stack. It was the result of f ().
101 2) This token was used by Emit
103 leave_copy (in both EmitAssign and Emit) tells the compiler to leave a copy
104 of the expression at that point in evaluation. This is used for pre/post inc/dec
105 and for a = x += y. Let's do the above example with leave_copy true in EmitAssign
107 this.EmitAssign (ec, source, true, true)
112 this.Emit (ec, false);
114 end this.Emit (ec, false);
127 end this.EmitAssign (ec, source, true, true)
129 And with it true in Emit
131 this.EmitAssign (ec, source, false, true)
136 this.Emit (ec, true);
140 end this.Emit (ec, true);
151 end this.EmitAssign (ec, source, false, true)
153 Note that these two examples are what happens for ++x and x++, respectively.
158 /// An Expression to hold a temporary value.
161 /// The LocalTemporary class is used to hold temporary values of a given
162 /// type to "simulate" the expression semantics. The local variable is
165 /// The local temporary is used to alter the normal flow of code generation
166 /// basically it creates a local variable, and its emit instruction generates
167 /// code to access this value, return its address or save its value.
169 /// If `is_address' is true, then the value that we store is the address to the
170 /// real value, and not the value itself.
172 /// This is needed for a value type, because otherwise you just end up making a
173 /// copy of the value on the stack and modifying it. You really need a pointer
174 /// to the origional value so that you can modify it in that location. This
175 /// Does not happen with a class because a class is a pointer -- so you always
176 /// get the indirection.
179 public class LocalTemporary : Expression, IMemoryLocation, IAssignMethod {
180 LocalBuilder builder;
182 public LocalTemporary (TypeSpec t)
185 eclass = ExprClass.Value;
188 public LocalTemporary (LocalBuilder b, TypeSpec t)
194 public void Release (EmitContext ec)
196 ec.FreeTemporaryLocal (builder, type);
200 public override Expression CreateExpressionTree (ResolveContext ec)
202 Arguments args = new Arguments (1);
203 args.Add (new Argument (this));
204 return CreateExpressionFactoryCall (ec, "Constant", args);
207 protected override Expression DoResolve (ResolveContext ec)
212 public override Expression DoResolveLValue (ResolveContext ec, Expression right_side)
217 public override void Emit (EmitContext ec)
220 throw new InternalErrorException ("Emit without Store, or after Release");
222 ec.Emit (OpCodes.Ldloc, builder);
225 #region IAssignMethod Members
227 public void Emit (EmitContext ec, bool leave_copy)
235 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
237 if (prepare_for_load)
238 throw new NotImplementedException ();
250 public LocalBuilder Builder {
251 get { return builder; }
254 public void Store (EmitContext ec)
257 builder = ec.GetTemporaryLocal (type);
259 ec.Emit (OpCodes.Stloc, builder);
262 public void AddressOf (EmitContext ec, AddressOp mode)
265 builder = ec.GetTemporaryLocal (type);
267 if (builder.LocalType.IsByRef) {
269 // if is_address, than this is just the address anyways,
270 // so we just return this.
272 ec.Emit (OpCodes.Ldloc, builder);
274 ec.Emit (OpCodes.Ldloca, builder);
280 /// The Assign node takes care of assigning the value of source into
281 /// the expression represented by target.
283 public abstract class Assign : ExpressionStatement {
284 protected Expression target, source;
286 protected Assign (Expression target, Expression source, Location loc)
288 this.target = target;
289 this.source = source;
293 public override Expression CreateExpressionTree (ResolveContext ec)
295 ec.Report.Error (832, loc, "An expression tree cannot contain an assignment operator");
299 public Expression Target {
300 get { return target; }
303 public Expression Source {
304 get { return source; }
307 protected override Expression DoResolve (ResolveContext ec)
310 source = source.Resolve (ec);
312 if (source == null) {
314 source = EmptyExpression.Null;
317 target = target.ResolveLValue (ec, source);
319 if (target == null || !ok)
322 TypeSpec target_type = target.Type;
323 TypeSpec source_type = source.Type;
325 eclass = ExprClass.Value;
328 if (!(target is IAssignMethod)) {
329 Error_ValueAssignment (ec, loc);
333 if (!TypeManager.IsEqual (target_type, source_type)) {
334 Expression resolved = ResolveConversions (ec);
336 if (resolved != this)
344 public override System.Linq.Expressions.Expression MakeExpression (BuilderContext ctx)
346 var tassign = target as IDynamicAssign;
348 throw new InternalErrorException (target.GetType () + " does not support dynamic assignment");
350 var target_object = tassign.MakeAssignExpression (ctx, source);
353 // Some hacking is needed as DLR does not support void type and requires
354 // always have object convertible return type to support caching and chaining
356 // We do this by introducing an explicit block which returns RHS value when
359 if (target_object.NodeType == System.Linq.Expressions.ExpressionType.Block)
360 return target_object;
362 var source_object = System.Linq.Expressions.Expression.Convert (source.MakeExpression (ctx), target_object.Type);
363 return System.Linq.Expressions.Expression.Assign (target_object, source_object);
366 protected virtual Expression ResolveConversions (ResolveContext ec)
368 source = Convert.ImplicitConversionRequired (ec, source, target.Type, loc);
375 void Emit (EmitContext ec, bool is_statement)
377 IAssignMethod t = (IAssignMethod) target;
378 t.EmitAssign (ec, source, !is_statement, this is CompoundAssign);
381 public override void Emit (EmitContext ec)
386 public override void EmitStatement (EmitContext ec)
391 protected override void CloneTo (CloneContext clonectx, Expression t)
393 Assign _target = (Assign) t;
395 _target.target = target.Clone (clonectx);
396 _target.source = source.Clone (clonectx);
400 public class SimpleAssign : Assign {
401 public SimpleAssign (Expression target, Expression source)
402 : this (target, source, target.Location)
406 public SimpleAssign (Expression target, Expression source, Location loc)
407 : base (target, source, loc)
411 bool CheckEqualAssign (Expression t)
413 if (source is Assign) {
414 Assign a = (Assign) source;
415 if (t.Equals (a.Target))
417 return a is SimpleAssign && ((SimpleAssign) a).CheckEqualAssign (t);
419 return t.Equals (source);
422 protected override Expression DoResolve (ResolveContext ec)
424 Expression e = base.DoResolve (ec);
425 if (e == null || e != this)
428 if (CheckEqualAssign (target))
429 ec.Report.Warning (1717, 3, loc, "Assignment made to same variable; did you mean to assign something else?");
435 // This class implements fields and events class initializers
436 public class FieldInitializer : Assign
439 // Keep resolved value because field initializers have their own rules
441 ExpressionStatement resolved;
444 public FieldInitializer (FieldSpec spec, Expression expression, IMemberContext rc)
445 : base (new FieldExpr (spec, expression.Location), expression, expression.Location)
449 ((FieldExpr)target).InstanceExpression = CompilerGeneratedThis.Instance;
452 protected override Expression DoResolve (ResolveContext ec)
454 // Field initializer can be resolved (fail) many times
458 if (resolved == null) {
460 // Field initializers are tricky for partial classes. They have to
461 // share same constructor (block) but they have they own resolve scope.
464 IMemberContext old = ec.MemberContext;
465 ec.MemberContext = rc;
467 using (ec.Set (ResolveContext.Options.FieldInitializerScope)) {
468 resolved = base.DoResolve (ec) as ExpressionStatement;
471 ec.MemberContext = old;
477 public override void EmitStatement (EmitContext ec)
479 if (resolved == null)
482 if (resolved != this)
483 resolved.EmitStatement (ec);
485 base.EmitStatement (ec);
488 public bool IsComplexInitializer {
489 get { return !(source is Constant); }
492 public bool IsDefaultInitializer {
494 Constant c = source as Constant;
498 FieldExpr fe = (FieldExpr)target;
499 return c.IsDefaultInitializer (fe.Type);
505 // This class is used for compound assignments.
507 public class CompoundAssign : Assign
509 // This is just a hack implemented for arrays only
510 public sealed class TargetExpression : Expression
513 public TargetExpression (Expression child)
516 this.loc = child.Location;
519 public override Expression CreateExpressionTree (ResolveContext ec)
521 throw new NotSupportedException ("ET");
524 protected override Expression DoResolve (ResolveContext ec)
527 eclass = ExprClass.Value;
531 public override void Emit (EmitContext ec)
537 // Used for underlying binary operator
538 readonly Binary.Operator op;
542 public CompoundAssign (Binary.Operator op, Expression target, Expression source, Location loc)
543 : base (target, source, loc)
549 public CompoundAssign (Binary.Operator op, Expression target, Expression source, Expression left, Location loc)
550 : this (op, target, source, loc)
555 protected override Expression DoResolve (ResolveContext ec)
557 right = right.Resolve (ec);
561 MemberAccess ma = target as MemberAccess;
562 using (ec.Set (ResolveContext.Options.CompoundAssignmentScope)) {
563 target = target.Resolve (ec);
569 if (target is MethodGroupExpr){
570 ec.Report.Error (1656, loc,
571 "Cannot assign to `{0}' because it is a `{1}'",
572 ((MethodGroupExpr)target).Name, target.ExprClassName);
576 var event_expr = target as EventExpr;
577 if (event_expr != null) {
578 source = Convert.ImplicitConversionRequired (ec, right, target.Type, loc);
583 if (op == Binary.Operator.Addition)
584 rside = EmptyExpression.EventAddition;
585 else if (op == Binary.Operator.Subtraction)
586 rside = EmptyExpression.EventSubtraction;
590 target = target.ResolveLValue (ec, rside);
594 eclass = ExprClass.Value;
595 type = event_expr.Operator.ReturnType;
600 // Only now we can decouple the original source/target
601 // into a tree, to guarantee that we do not have side
605 left = new TargetExpression (target);
607 source = new Binary (op, left, right, true, loc);
609 if (target is DynamicMemberBinder) {
610 Arguments targs = ((DynamicMemberBinder) target).Arguments;
611 source = source.Resolve (ec);
613 Arguments args = new Arguments (2);
614 args.AddRange (targs);
615 args.Add (new Argument (source));
616 source = new DynamicMemberBinder (ma.Name, args, loc).ResolveLValue (ec, right);
618 // Handles possible event addition/subtraction
619 if (op == Binary.Operator.Addition || op == Binary.Operator.Subtraction) {
620 args = new Arguments (2);
621 args.AddRange (targs);
622 args.Add (new Argument (right));
623 string method_prefix = op == Binary.Operator.Addition ?
624 Event.AEventAccessor.AddPrefix : Event.AEventAccessor.RemovePrefix;
626 var invoke = DynamicInvocation.CreateSpecialNameInvoke (
627 new MemberAccess (right, method_prefix + ma.Name, loc), args, loc).Resolve (ec);
629 args = new Arguments (1);
630 args.AddRange (targs);
631 source = new DynamicEventCompoundAssign (ma.Name, args,
632 (ExpressionStatement) source, (ExpressionStatement) invoke, loc).Resolve (ec);
638 return base.DoResolve (ec);
641 protected override Expression ResolveConversions (ResolveContext ec)
643 TypeSpec target_type = target.Type;
646 // 1. the return type is implicitly convertible to the type of target
648 if (Convert.ImplicitConversionExists (ec, source, target_type)) {
649 source = Convert.ImplicitConversion (ec, source, target_type, loc);
654 // Otherwise, if the selected operator is a predefined operator
656 Binary b = source as Binary;
659 // 2a. the operator is a shift operator
661 // 2b. the return type is explicitly convertible to the type of x, and
662 // y is implicitly convertible to the type of x
664 if ((b.Oper & Binary.Operator.ShiftMask) != 0 ||
665 Convert.ImplicitConversionExists (ec, right, target_type)) {
666 source = Convert.ExplicitConversion (ec, source, target_type, loc);
671 if (source.Type == InternalType.Dynamic) {
672 Arguments arg = new Arguments (1);
673 arg.Add (new Argument (source));
674 return new SimpleAssign (target, new DynamicConversion (target_type, CSharpBinderFlags.ConvertExplicit, arg, loc), loc).Resolve (ec);
677 right.Error_ValueCannotBeConverted (ec, loc, target_type, false);
681 protected override void CloneTo (CloneContext clonectx, Expression t)
683 CompoundAssign ctarget = (CompoundAssign) t;
685 ctarget.right = ctarget.source = source.Clone (clonectx);
686 ctarget.target = target.Clone (clonectx);