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
17 using IKVM.Reflection.Emit;
19 using System.Reflection.Emit;
22 namespace Mono.CSharp {
25 /// This interface is implemented by expressions that can be assigned to.
28 /// This interface is implemented by Expressions whose values can not
29 /// store the result on the top of the stack.
31 /// Expressions implementing this (Properties, Indexers and Arrays) would
32 /// perform an assignment of the Expression "source" into its final
35 /// No values on the top of the stack are expected to be left by
36 /// invoking this method.
38 public interface IAssignMethod {
40 // This is an extra version of Emit. If leave_copy is `true'
41 // A copy of the expression will be left on the stack at the
42 // end of the code generated for EmitAssign
44 void Emit (EmitContext ec, bool leave_copy);
47 // This method does the assignment
48 // `source' will be stored into the location specified by `this'
49 // if `leave_copy' is true, a copy of `source' will be left on the stack
50 // if `prepare_for_load' is true, when `source' is emitted, there will
51 // be data on the stack that it can use to compuatate its value. This is
52 // for expressions like a [f ()] ++, where you can't call `f ()' twice.
54 void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load);
57 For simple assignments, this interface is very simple, EmitAssign is called with source
58 as the source expression and leave_copy and prepare_for_load false.
60 For compound assignments it gets complicated.
62 EmitAssign will be called as before, however, prepare_for_load will be
63 true. The @source expression will contain an expression
64 which calls Emit. So, the calls look like:
66 this.EmitAssign (ec, source, false, true) ->
69 this.Emit (ec, false); ->
70 end this.Emit (ec, false); ->
73 end this.EmitAssign (ec, source, false, true)
76 When prepare_for_load is true, EmitAssign emits a `token' on the stack that
77 Emit will use for its state.
79 Let's take FieldExpr as an example. assume we are emitting f ().y += 1;
81 Here is the call tree again. This time, each call is annotated with the IL
84 this.EmitAssign (ec, source, false, true)
89 this.Emit (ec, false);
91 end this.Emit (ec, false);
101 end this.EmitAssign (ec, source, false, true)
104 1) EmitAssign left a token on the stack. It was the result of f ().
105 2) This token was used by Emit
107 leave_copy (in both EmitAssign and Emit) tells the compiler to leave a copy
108 of the expression at that point in evaluation. This is used for pre/post inc/dec
109 and for a = x += y. Let's do the above example with leave_copy true in EmitAssign
111 this.EmitAssign (ec, source, true, true)
116 this.Emit (ec, false);
118 end this.Emit (ec, false);
131 end this.EmitAssign (ec, source, true, true)
133 And with it true in Emit
135 this.EmitAssign (ec, source, false, true)
140 this.Emit (ec, true);
144 end this.Emit (ec, true);
155 end this.EmitAssign (ec, source, false, true)
157 Note that these two examples are what happens for ++x and x++, respectively.
162 /// An Expression to hold a temporary value.
165 /// The LocalTemporary class is used to hold temporary values of a given
166 /// type to "simulate" the expression semantics. The local variable is
169 /// The local temporary is used to alter the normal flow of code generation
170 /// basically it creates a local variable, and its emit instruction generates
171 /// code to access this value, return its address or save its value.
173 /// If `is_address' is true, then the value that we store is the address to the
174 /// real value, and not the value itself.
176 /// This is needed for a value type, because otherwise you just end up making a
177 /// copy of the value on the stack and modifying it. You really need a pointer
178 /// to the origional value so that you can modify it in that location. This
179 /// Does not happen with a class because a class is a pointer -- so you always
180 /// get the indirection.
183 public class LocalTemporary : Expression, IMemoryLocation, IAssignMethod {
184 LocalBuilder builder;
186 public LocalTemporary (TypeSpec t)
189 eclass = ExprClass.Value;
192 public LocalTemporary (LocalBuilder b, TypeSpec t)
198 public void Release (EmitContext ec)
200 ec.FreeTemporaryLocal (builder, type);
204 public override Expression CreateExpressionTree (ResolveContext ec)
206 Arguments args = new Arguments (1);
207 args.Add (new Argument (this));
208 return CreateExpressionFactoryCall (ec, "Constant", args);
211 protected override Expression DoResolve (ResolveContext ec)
216 public override Expression DoResolveLValue (ResolveContext ec, Expression right_side)
221 public override void Emit (EmitContext ec)
224 throw new InternalErrorException ("Emit without Store, or after Release");
226 ec.Emit (OpCodes.Ldloc, builder);
229 #region IAssignMethod Members
231 public void Emit (EmitContext ec, bool leave_copy)
239 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
241 if (prepare_for_load)
242 throw new NotImplementedException ();
254 public LocalBuilder Builder {
255 get { return builder; }
258 public void Store (EmitContext ec)
261 builder = ec.GetTemporaryLocal (type);
263 ec.Emit (OpCodes.Stloc, builder);
266 public void AddressOf (EmitContext ec, AddressOp mode)
269 builder = ec.GetTemporaryLocal (type);
271 if (builder.LocalType.IsByRef) {
273 // if is_address, than this is just the address anyways,
274 // so we just return this.
276 ec.Emit (OpCodes.Ldloc, builder);
278 ec.Emit (OpCodes.Ldloca, builder);
284 /// The Assign node takes care of assigning the value of source into
285 /// the expression represented by target.
287 public abstract class Assign : ExpressionStatement {
288 protected Expression target, source;
290 protected Assign (Expression target, Expression source, Location loc)
292 this.target = target;
293 this.source = source;
297 public override Expression CreateExpressionTree (ResolveContext ec)
299 ec.Report.Error (832, loc, "An expression tree cannot contain an assignment operator");
303 public Expression Target {
304 get { return target; }
307 public Expression Source {
313 protected override Expression DoResolve (ResolveContext ec)
316 source = source.Resolve (ec);
318 if (source == null) {
320 source = EmptyExpression.Null;
323 target = target.ResolveLValue (ec, source);
325 if (target == null || !ok)
328 TypeSpec target_type = target.Type;
329 TypeSpec source_type = source.Type;
331 eclass = ExprClass.Value;
334 if (!(target is IAssignMethod)) {
335 Error_ValueAssignment (ec, loc);
339 if (target_type != source_type) {
340 Expression resolved = ResolveConversions (ec);
342 if (resolved != this)
350 public override System.Linq.Expressions.Expression MakeExpression (BuilderContext ctx)
352 var tassign = target as IDynamicAssign;
354 throw new InternalErrorException (target.GetType () + " does not support dynamic assignment");
356 var target_object = tassign.MakeAssignExpression (ctx, source);
359 // Some hacking is needed as DLR does not support void type and requires
360 // always have object convertible return type to support caching and chaining
362 // We do this by introducing an explicit block which returns RHS value when
365 if (target_object.NodeType == System.Linq.Expressions.ExpressionType.Block)
366 return target_object;
368 System.Linq.Expressions.UnaryExpression source_object;
369 if (ctx.HasSet (BuilderContext.Options.CheckedScope)) {
370 source_object = System.Linq.Expressions.Expression.ConvertChecked (source.MakeExpression (ctx), target_object.Type);
372 source_object = System.Linq.Expressions.Expression.Convert (source.MakeExpression (ctx), target_object.Type);
375 return System.Linq.Expressions.Expression.Assign (target_object, source_object);
378 protected virtual Expression ResolveConversions (ResolveContext ec)
380 source = Convert.ImplicitConversionRequired (ec, source, target.Type, loc);
387 void Emit (EmitContext ec, bool is_statement)
389 IAssignMethod t = (IAssignMethod) target;
390 t.EmitAssign (ec, source, !is_statement, this is CompoundAssign);
393 public override void Emit (EmitContext ec)
398 public override void EmitStatement (EmitContext ec)
403 protected override void CloneTo (CloneContext clonectx, Expression t)
405 Assign _target = (Assign) t;
407 _target.target = target.Clone (clonectx);
408 _target.source = source.Clone (clonectx);
412 public class SimpleAssign : Assign
414 public SimpleAssign (Expression target, Expression source)
415 : this (target, source, target.Location)
419 public SimpleAssign (Expression target, Expression source, Location loc)
420 : base (target, source, loc)
424 bool CheckEqualAssign (Expression t)
426 if (source is Assign) {
427 Assign a = (Assign) source;
428 if (t.Equals (a.Target))
430 return a is SimpleAssign && ((SimpleAssign) a).CheckEqualAssign (t);
432 return t.Equals (source);
435 protected override Expression DoResolve (ResolveContext ec)
437 Expression e = base.DoResolve (ec);
438 if (e == null || e != this)
441 if (CheckEqualAssign (target))
442 ec.Report.Warning (1717, 3, loc, "Assignment made to same variable; did you mean to assign something else?");
448 public class RuntimeExplicitAssign : Assign
450 public RuntimeExplicitAssign (Expression target, Expression source)
451 : base (target, source, target.Location)
455 protected override Expression ResolveConversions (ResolveContext ec)
457 source = EmptyCast.Create (source, target.Type);
463 // Compiler generated assign
465 class CompilerAssign : Assign
467 public CompilerAssign (Expression target, Expression source, Location loc)
468 : base (target, source, loc)
472 public void UpdateSource (Expression source)
474 base.source = source;
479 // Implements fields and events class initializers
481 public class FieldInitializer : Assign
484 // Field initializers are tricky for partial classes. They have to
485 // share same constructor (block) for expression trees resolve but
486 // they have they own resolve scope
488 sealed class FieldInitializerContext : ResolveContext
490 ExplicitBlock ctor_block;
492 public FieldInitializerContext (IMemberContext mc, ResolveContext constructorContext)
493 : base (mc, Options.FieldInitializerScope | Options.ConstructorScope)
495 this.ctor_block = constructorContext.CurrentBlock.Explicit;
498 public override ExplicitBlock ConstructorBlock {
506 // Keep resolved value because field initializers have their own rules
508 ExpressionStatement resolved;
511 public FieldInitializer (FieldSpec spec, Expression expression, IMemberContext mc)
512 : base (new FieldExpr (spec, expression.Location), expression, expression.Location)
516 ((FieldExpr)target).InstanceExpression = CompilerGeneratedThis.Instance;
519 protected override Expression DoResolve (ResolveContext ec)
521 // Field initializer can be resolved (fail) many times
525 if (resolved == null) {
526 var ctx = new FieldInitializerContext (mc, ec);
527 resolved = base.DoResolve (ctx) as ExpressionStatement;
533 public override void EmitStatement (EmitContext ec)
535 if (resolved == null)
538 if (resolved != this)
539 resolved.EmitStatement (ec);
541 base.EmitStatement (ec);
544 public bool IsComplexInitializer {
545 get { return !(source is Constant); }
548 public bool IsDefaultInitializer {
550 Constant c = source as Constant;
554 FieldExpr fe = (FieldExpr)target;
555 return c.IsDefaultInitializer (fe.Type);
561 // This class is used for compound assignments.
563 public class CompoundAssign : Assign
565 // This is just a hack implemented for arrays only
566 public sealed class TargetExpression : Expression
569 public TargetExpression (Expression child)
572 this.loc = child.Location;
575 public override Expression CreateExpressionTree (ResolveContext ec)
577 throw new NotSupportedException ("ET");
580 protected override Expression DoResolve (ResolveContext ec)
583 eclass = ExprClass.Value;
587 public override void Emit (EmitContext ec)
593 // Used for underlying binary operator
594 readonly Binary.Operator op;
598 public CompoundAssign (Binary.Operator op, Expression target, Expression source, Location loc)
599 : base (target, source, loc)
605 public CompoundAssign (Binary.Operator op, Expression target, Expression source, Expression left, Location loc)
606 : this (op, target, source, loc)
611 protected override Expression DoResolve (ResolveContext ec)
613 right = right.Resolve (ec);
617 MemberAccess ma = target as MemberAccess;
618 using (ec.Set (ResolveContext.Options.CompoundAssignmentScope)) {
619 target = target.Resolve (ec);
625 if (target is MethodGroupExpr){
626 ec.Report.Error (1656, loc,
627 "Cannot assign to `{0}' because it is a `{1}'",
628 ((MethodGroupExpr)target).Name, target.ExprClassName);
632 var event_expr = target as EventExpr;
633 if (event_expr != null) {
634 source = Convert.ImplicitConversionRequired (ec, right, target.Type, loc);
639 if (op == Binary.Operator.Addition)
640 rside = EmptyExpression.EventAddition;
641 else if (op == Binary.Operator.Subtraction)
642 rside = EmptyExpression.EventSubtraction;
646 target = target.ResolveLValue (ec, rside);
650 eclass = ExprClass.Value;
651 type = event_expr.Operator.ReturnType;
656 // Only now we can decouple the original source/target
657 // into a tree, to guarantee that we do not have side
661 left = new TargetExpression (target);
663 source = new Binary (op, left, right, true, loc);
665 if (target is DynamicMemberAssignable) {
666 Arguments targs = ((DynamicMemberAssignable) target).Arguments;
667 source = source.Resolve (ec);
669 Arguments args = new Arguments (targs.Count + 1);
670 args.AddRange (targs);
671 args.Add (new Argument (source));
673 var binder_flags = CSharpBinderFlags.ValueFromCompoundAssignment;
676 // Compound assignment does target conversion using additional method
677 // call, set checked context as the binary operation can overflow
679 if (ec.HasSet (ResolveContext.Options.CheckedScope))
680 binder_flags |= CSharpBinderFlags.CheckedContext;
682 if (target is DynamicMemberBinder) {
683 source = new DynamicMemberBinder (ma.Name, binder_flags, args, loc).Resolve (ec);
685 // Handles possible event addition/subtraction
686 if (op == Binary.Operator.Addition || op == Binary.Operator.Subtraction) {
687 args = new Arguments (targs.Count + 1);
688 args.AddRange (targs);
689 args.Add (new Argument (right));
690 string method_prefix = op == Binary.Operator.Addition ?
691 Event.AEventAccessor.AddPrefix : Event.AEventAccessor.RemovePrefix;
693 var invoke = DynamicInvocation.CreateSpecialNameInvoke (
694 new MemberAccess (right, method_prefix + ma.Name, loc), args, loc).Resolve (ec);
696 args = new Arguments (targs.Count);
697 args.AddRange (targs);
698 source = new DynamicEventCompoundAssign (ma.Name, args,
699 (ExpressionStatement) source, (ExpressionStatement) invoke, loc).Resolve (ec);
702 source = new DynamicIndexBinder (binder_flags, args, loc).Resolve (ec);
708 return base.DoResolve (ec);
711 protected override Expression ResolveConversions (ResolveContext ec)
714 // LAMESPEC: Under dynamic context no target conversion is happening
715 // This allows more natual dynamic behaviour but breaks compatibility
716 // with static binding
718 if (target is RuntimeValueExpression)
721 TypeSpec target_type = target.Type;
724 // 1. the return type is implicitly convertible to the type of target
726 if (Convert.ImplicitConversionExists (ec, source, target_type)) {
727 source = Convert.ImplicitConversion (ec, source, target_type, loc);
732 // Otherwise, if the selected operator is a predefined operator
734 Binary b = source as Binary;
735 if (b == null && source is ReducedExpression)
736 b = ((ReducedExpression) source).OriginalExpression as Binary;
740 // 2a. the operator is a shift operator
742 // 2b. the return type is explicitly convertible to the type of x, and
743 // y is implicitly convertible to the type of x
745 if ((b.Oper & Binary.Operator.ShiftMask) != 0 ||
746 Convert.ImplicitConversionExists (ec, right, target_type)) {
747 source = Convert.ExplicitConversion (ec, source, target_type, loc);
752 if (source.Type.BuildinType == BuildinTypeSpec.Type.Dynamic) {
753 Arguments arg = new Arguments (1);
754 arg.Add (new Argument (source));
755 return new SimpleAssign (target, new DynamicConversion (target_type, CSharpBinderFlags.ConvertExplicit, arg, loc), loc).Resolve (ec);
758 right.Error_ValueCannotBeConverted (ec, loc, target_type, false);
762 protected override void CloneTo (CloneContext clonectx, Expression t)
764 CompoundAssign ctarget = (CompoundAssign) t;
766 ctarget.right = ctarget.source = source.Clone (clonectx);
767 ctarget.target = target.Clone (clonectx);