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
13 // Copyright 2011 Xamarin Inc
18 using IKVM.Reflection.Emit;
20 using System.Reflection.Emit;
23 namespace Mono.CSharp {
26 /// This interface is implemented by expressions that can be assigned to.
29 /// This interface is implemented by Expressions whose values can not
30 /// store the result on the top of the stack.
32 /// Expressions implementing this (Properties, Indexers and Arrays) would
33 /// perform an assignment of the Expression "source" into its final
36 /// No values on the top of the stack are expected to be left by
37 /// invoking this method.
39 public interface IAssignMethod {
41 // This is an extra version of Emit. If leave_copy is `true'
42 // A copy of the expression will be left on the stack at the
43 // end of the code generated for EmitAssign
45 void Emit (EmitContext ec, bool leave_copy);
48 // This method does the assignment
49 // `source' will be stored into the location specified by `this'
50 // if `leave_copy' is true, a copy of `source' will be left on the stack
51 // if `prepare_for_load' is true, when `source' is emitted, there will
52 // be data on the stack that it can use to compuatate its value. This is
53 // for expressions like a [f ()] ++, where you can't call `f ()' twice.
55 void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool isCompound);
58 For simple assignments, this interface is very simple, EmitAssign is called with source
59 as the source expression and leave_copy and prepare_for_load false.
61 For compound assignments it gets complicated.
63 EmitAssign will be called as before, however, prepare_for_load will be
64 true. The @source expression will contain an expression
65 which calls Emit. So, the calls look like:
67 this.EmitAssign (ec, source, false, true) ->
70 this.Emit (ec, false); ->
71 end this.Emit (ec, false); ->
74 end this.EmitAssign (ec, source, false, true)
77 When prepare_for_load is true, EmitAssign emits a `token' on the stack that
78 Emit will use for its state.
80 Let's take FieldExpr as an example. assume we are emitting f ().y += 1;
82 Here is the call tree again. This time, each call is annotated with the IL
85 this.EmitAssign (ec, source, false, true)
90 this.Emit (ec, false);
92 end this.Emit (ec, false);
102 end this.EmitAssign (ec, source, false, true)
105 1) EmitAssign left a token on the stack. It was the result of f ().
106 2) This token was used by Emit
108 leave_copy (in both EmitAssign and Emit) tells the compiler to leave a copy
109 of the expression at that point in evaluation. This is used for pre/post inc/dec
110 and for a = x += y. Let's do the above example with leave_copy true in EmitAssign
112 this.EmitAssign (ec, source, true, true)
117 this.Emit (ec, false);
119 end this.Emit (ec, false);
132 end this.EmitAssign (ec, source, true, true)
134 And with it true in Emit
136 this.EmitAssign (ec, source, false, true)
141 this.Emit (ec, true);
145 end this.Emit (ec, true);
156 end this.EmitAssign (ec, source, false, true)
158 Note that these two examples are what happens for ++x and x++, respectively.
163 /// An Expression to hold a temporary value.
166 /// The LocalTemporary class is used to hold temporary values of a given
167 /// type to "simulate" the expression semantics. The local variable is
170 /// The local temporary is used to alter the normal flow of code generation
171 /// basically it creates a local variable, and its emit instruction generates
172 /// code to access this value, return its address or save its value.
174 /// If `is_address' is true, then the value that we store is the address to the
175 /// real value, and not the value itself.
177 /// This is needed for a value type, because otherwise you just end up making a
178 /// copy of the value on the stack and modifying it. You really need a pointer
179 /// to the origional value so that you can modify it in that location. This
180 /// Does not happen with a class because a class is a pointer -- so you always
181 /// get the indirection.
184 public class LocalTemporary : Expression, IMemoryLocation, IAssignMethod {
185 LocalBuilder builder;
187 public LocalTemporary (TypeSpec t)
190 eclass = ExprClass.Value;
193 public LocalTemporary (LocalBuilder b, TypeSpec t)
199 public void Release (EmitContext ec)
201 ec.FreeTemporaryLocal (builder, type);
205 public override bool ContainsEmitWithAwait ()
210 public override Expression CreateExpressionTree (ResolveContext ec)
212 Arguments args = new Arguments (1);
213 args.Add (new Argument (this));
214 return CreateExpressionFactoryCall (ec, "Constant", args);
217 protected override Expression DoResolve (ResolveContext ec)
222 public override Expression DoResolveLValue (ResolveContext ec, Expression right_side)
227 public override void Emit (EmitContext ec)
230 throw new InternalErrorException ("Emit without Store, or after Release");
232 ec.Emit (OpCodes.Ldloc, builder);
235 #region IAssignMethod Members
237 public void Emit (EmitContext ec, bool leave_copy)
245 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool isCompound)
248 throw new NotImplementedException ();
260 public LocalBuilder Builder {
261 get { return builder; }
264 public void Store (EmitContext ec)
267 builder = ec.GetTemporaryLocal (type);
269 ec.Emit (OpCodes.Stloc, builder);
272 public void AddressOf (EmitContext ec, AddressOp mode)
275 builder = ec.GetTemporaryLocal (type);
277 if (builder.LocalType.IsByRef) {
279 // if is_address, than this is just the address anyways,
280 // so we just return this.
282 ec.Emit (OpCodes.Ldloc, builder);
284 ec.Emit (OpCodes.Ldloca, builder);
290 /// The Assign node takes care of assigning the value of source into
291 /// the expression represented by target.
293 public abstract class Assign : ExpressionStatement {
294 protected Expression target, source;
296 protected Assign (Expression target, Expression source, Location loc)
298 this.target = target;
299 this.source = source;
303 public Expression Target {
304 get { return target; }
307 public Expression Source {
313 public override Location StartLocation {
315 return target.StartLocation;
319 public override bool ContainsEmitWithAwait ()
321 return target.ContainsEmitWithAwait () || source.ContainsEmitWithAwait ();
324 public override Expression CreateExpressionTree (ResolveContext ec)
326 ec.Report.Error (832, loc, "An expression tree cannot contain an assignment operator");
330 protected override Expression DoResolve (ResolveContext ec)
333 source = source.Resolve (ec);
335 if (source == null) {
337 source = ErrorExpression.Instance;
340 target = target.ResolveLValue (ec, source);
342 if (target == null || !ok)
345 TypeSpec target_type = target.Type;
346 TypeSpec source_type = source.Type;
348 eclass = ExprClass.Value;
351 if (!(target is IAssignMethod)) {
352 target.Error_ValueAssignment (ec, source);
356 if (target_type != source_type) {
357 Expression resolved = ResolveConversions (ec);
359 if (resolved != this)
366 public override System.Linq.Expressions.Expression MakeExpression (BuilderContext ctx)
368 var tassign = target as IDynamicAssign;
370 throw new InternalErrorException (target.GetType () + " does not support dynamic assignment");
372 var target_object = tassign.MakeAssignExpression (ctx, source);
375 // Some hacking is needed as DLR does not support void type and requires
376 // always have object convertible return type to support caching and chaining
378 // We do this by introducing an explicit block which returns RHS value when
381 if (target_object.NodeType == System.Linq.Expressions.ExpressionType.Block)
382 return target_object;
384 System.Linq.Expressions.UnaryExpression source_object;
385 if (ctx.HasSet (BuilderContext.Options.CheckedScope)) {
386 source_object = System.Linq.Expressions.Expression.ConvertChecked (source.MakeExpression (ctx), target_object.Type);
388 source_object = System.Linq.Expressions.Expression.Convert (source.MakeExpression (ctx), target_object.Type);
391 return System.Linq.Expressions.Expression.Assign (target_object, source_object);
393 protected virtual Expression ResolveConversions (ResolveContext ec)
395 source = Convert.ImplicitConversionRequired (ec, source, target.Type, source.Location);
402 void Emit (EmitContext ec, bool is_statement)
404 IAssignMethod t = (IAssignMethod) target;
405 t.EmitAssign (ec, source, !is_statement, this is CompoundAssign);
408 public override void Emit (EmitContext ec)
413 public override void EmitStatement (EmitContext ec)
418 public override void FlowAnalysis (FlowAnalysisContext fc)
420 source.FlowAnalysis (fc);
422 if (target is ArrayAccess || target is IndexerExpr) {
423 target.FlowAnalysis (fc);
427 var pe = target as PropertyExpr;
428 if (pe != null && !pe.IsAutoPropertyAccess)
429 target.FlowAnalysis (fc);
432 protected override void CloneTo (CloneContext clonectx, Expression t)
434 Assign _target = (Assign) t;
436 _target.target = target.Clone (clonectx);
437 _target.source = source.Clone (clonectx);
440 public override object Accept (StructuralVisitor visitor)
442 return visitor.Visit (this);
446 public class SimpleAssign : Assign
448 public SimpleAssign (Expression target, Expression source)
449 : this (target, source, target.Location)
453 public SimpleAssign (Expression target, Expression source, Location loc)
454 : base (target, source, loc)
458 bool CheckEqualAssign (Expression t)
460 if (source is Assign) {
461 Assign a = (Assign) source;
462 if (t.Equals (a.Target))
464 return a is SimpleAssign && ((SimpleAssign) a).CheckEqualAssign (t);
466 return t.Equals (source);
469 protected override Expression DoResolve (ResolveContext ec)
471 Expression e = base.DoResolve (ec);
472 if (e == null || e != this)
475 if (CheckEqualAssign (target))
476 ec.Report.Warning (1717, 3, loc, "Assignment made to same variable; did you mean to assign something else?");
481 public override void FlowAnalysis (FlowAnalysisContext fc)
483 base.FlowAnalysis (fc);
485 var vr = target as VariableReference;
487 if (vr.VariableInfo != null)
488 fc.SetVariableAssigned (vr.VariableInfo);
493 var fe = target as FieldExpr;
495 fe.SetFieldAssigned (fc);
499 var pe = target as PropertyExpr;
501 pe.SetBackingFieldAssigned (fc);
506 public override void MarkReachable (Reachability rc)
508 var es = source as ExpressionStatement;
510 es.MarkReachable (rc);
514 public class RuntimeExplicitAssign : Assign
516 public RuntimeExplicitAssign (Expression target, Expression source)
517 : base (target, source, target.Location)
521 protected override Expression ResolveConversions (ResolveContext ec)
523 source = EmptyCast.Create (source, target.Type);
529 // Compiler generated assign
531 class CompilerAssign : Assign
533 public CompilerAssign (Expression target, Expression source, Location loc)
534 : base (target, source, loc)
536 if (target.Type != null) {
538 eclass = ExprClass.Value;
542 protected override Expression DoResolve (ResolveContext ec)
544 var expr = base.DoResolve (ec);
545 var vr = target as VariableReference;
546 if (vr != null && vr.VariableInfo != null)
547 vr.VariableInfo.IsEverAssigned = false;
552 public void UpdateSource (Expression source)
554 base.source = source;
559 // Implements fields and events class initializers
561 public class FieldInitializer : Assign
564 // Field initializers are tricky for partial classes. They have to
565 // share same constructor (block) for expression trees resolve but
566 // they have they own resolve scope
568 sealed class FieldInitializerContext : BlockContext
570 readonly ExplicitBlock ctor_block;
572 public FieldInitializerContext (IMemberContext mc, BlockContext constructorContext)
573 : base (mc, null, constructorContext.ReturnType)
575 flags |= Options.FieldInitializerScope | Options.ConstructorScope;
576 this.ctor_block = constructorContext.CurrentBlock.Explicit;
578 if (ctor_block.IsCompilerGenerated)
579 CurrentBlock = ctor_block;
582 public override ExplicitBlock ConstructorBlock {
590 // Keep resolved value because field initializers have their own rules
592 ExpressionStatement resolved;
595 public FieldInitializer (FieldBase mc, Expression expression, Location loc)
596 : base (new FieldExpr (mc.Spec, expression.Location), expression, loc)
600 ((FieldExpr)target).InstanceExpression = new CompilerGeneratedThis (mc.CurrentType, expression.Location);
603 public int AssignmentOffset { get; private set; }
605 public FieldBase Field {
611 public override Location StartLocation {
617 protected override Expression DoResolve (ResolveContext rc)
619 // Field initializer can be resolved (fail) many times
623 if (resolved == null) {
624 var bc = (BlockContext) rc;
625 var ctx = new FieldInitializerContext (mc, bc);
626 resolved = base.DoResolve (ctx) as ExpressionStatement;
627 AssignmentOffset = ctx.AssignmentInfoOffset - bc.AssignmentInfoOffset;
633 public override void EmitStatement (EmitContext ec)
635 if (resolved == null)
639 // Emit sequence symbol info even if we are in compiler generated
640 // block to allow debugging field initializers when constructor is
641 // compiler generated
643 if (ec.HasSet (BuilderContext.Options.OmitDebugInfo) && ec.HasMethodSymbolBuilder) {
644 using (ec.With (BuilderContext.Options.OmitDebugInfo, false)) {
649 if (resolved != this)
650 resolved.EmitStatement (ec);
652 base.EmitStatement (ec);
655 public override void FlowAnalysis (FlowAnalysisContext fc)
657 source.FlowAnalysis (fc);
658 ((FieldExpr) target).SetFieldAssigned (fc);
661 public bool IsDefaultInitializer {
663 Constant c = source as Constant;
667 FieldExpr fe = (FieldExpr)target;
668 return c.IsDefaultInitializer (fe.Type);
672 public override bool IsSideEffectFree {
674 return source.IsSideEffectFree;
679 class PrimaryConstructorAssign : SimpleAssign
681 readonly Field field;
682 readonly Parameter parameter;
684 public PrimaryConstructorAssign (Field field, Parameter parameter)
685 : base (null, null, parameter.Location)
688 this.parameter = parameter;
691 protected override Expression DoResolve (ResolveContext rc)
693 target = new FieldExpr (field, loc);
694 source = rc.CurrentBlock.ParametersBlock.GetParameterInfo (parameter).CreateReferenceExpression (rc, loc);
695 return base.DoResolve (rc);
698 public override void EmitStatement (EmitContext ec)
700 using (ec.With (BuilderContext.Options.OmitDebugInfo, true)) {
701 base.EmitStatement (ec);
707 // This class is used for compound assignments.
709 public class CompoundAssign : Assign
711 // This is just a hack implemented for arrays only
712 public sealed class TargetExpression : Expression
714 readonly Expression child;
716 public TargetExpression (Expression child)
719 this.loc = child.Location;
722 public override bool ContainsEmitWithAwait ()
724 return child.ContainsEmitWithAwait ();
727 public override Expression CreateExpressionTree (ResolveContext ec)
729 throw new NotSupportedException ("ET");
732 protected override Expression DoResolve (ResolveContext ec)
735 eclass = ExprClass.Value;
739 public override void Emit (EmitContext ec)
744 public override Expression EmitToField (EmitContext ec)
746 return child.EmitToField (ec);
750 // Used for underlying binary operator
751 readonly Binary.Operator op;
755 public CompoundAssign (Binary.Operator op, Expression target, Expression source)
756 : base (target, source, target.Location)
762 public CompoundAssign (Binary.Operator op, Expression target, Expression source, Expression left)
763 : this (op, target, source)
768 public Binary.Operator Operator {
774 protected override Expression DoResolve (ResolveContext ec)
776 right = right.Resolve (ec);
780 MemberAccess ma = target as MemberAccess;
781 using (ec.Set (ResolveContext.Options.CompoundAssignmentScope)) {
782 target = target.Resolve (ec);
788 if (target is MethodGroupExpr){
789 ec.Report.Error (1656, loc,
790 "Cannot assign to `{0}' because it is a `{1}'",
791 ((MethodGroupExpr)target).Name, target.ExprClassName);
795 var event_expr = target as EventExpr;
796 if (event_expr != null) {
797 source = Convert.ImplicitConversionRequired (ec, right, target.Type, loc);
802 if (op == Binary.Operator.Addition)
803 rside = EmptyExpression.EventAddition;
804 else if (op == Binary.Operator.Subtraction)
805 rside = EmptyExpression.EventSubtraction;
809 target = target.ResolveLValue (ec, rside);
813 eclass = ExprClass.Value;
814 type = event_expr.Operator.ReturnType;
819 // Only now we can decouple the original source/target
820 // into a tree, to guarantee that we do not have side
824 left = new TargetExpression (target);
826 source = new Binary (op, left, right, true);
828 if (target is DynamicMemberAssignable) {
829 Arguments targs = ((DynamicMemberAssignable) target).Arguments;
830 source = source.Resolve (ec);
832 Arguments args = new Arguments (targs.Count + 1);
833 args.AddRange (targs);
834 args.Add (new Argument (source));
836 var binder_flags = CSharpBinderFlags.ValueFromCompoundAssignment;
839 // Compound assignment does target conversion using additional method
840 // call, set checked context as the binary operation can overflow
842 if (ec.HasSet (ResolveContext.Options.CheckedScope))
843 binder_flags |= CSharpBinderFlags.CheckedContext;
845 if (target is DynamicMemberBinder) {
846 source = new DynamicMemberBinder (ma.Name, binder_flags, args, loc).Resolve (ec);
848 // Handles possible event addition/subtraction
849 if (op == Binary.Operator.Addition || op == Binary.Operator.Subtraction) {
850 args = new Arguments (targs.Count + 1);
851 args.AddRange (targs);
852 args.Add (new Argument (right));
853 string method_prefix = op == Binary.Operator.Addition ?
854 Event.AEventAccessor.AddPrefix : Event.AEventAccessor.RemovePrefix;
856 var invoke = DynamicInvocation.CreateSpecialNameInvoke (
857 new MemberAccess (right, method_prefix + ma.Name, loc), args, loc).Resolve (ec);
859 args = new Arguments (targs.Count);
860 args.AddRange (targs);
861 source = new DynamicEventCompoundAssign (ma.Name, args,
862 (ExpressionStatement) source, (ExpressionStatement) invoke, loc).Resolve (ec);
865 source = new DynamicIndexBinder (binder_flags, args, loc).Resolve (ec);
871 return base.DoResolve (ec);
874 public override void FlowAnalysis (FlowAnalysisContext fc)
876 target.FlowAnalysis (fc);
877 source.FlowAnalysis (fc);
880 protected override Expression ResolveConversions (ResolveContext ec)
883 // LAMESPEC: Under dynamic context no target conversion is happening
884 // This allows more natual dynamic behaviour but breaks compatibility
885 // with static binding
887 if (target is RuntimeValueExpression)
890 TypeSpec target_type = target.Type;
893 // 1. the return type is implicitly convertible to the type of target
895 if (Convert.ImplicitConversionExists (ec, source, target_type)) {
896 source = Convert.ImplicitConversion (ec, source, target_type, loc);
901 // Otherwise, if the selected operator is a predefined operator
903 Binary b = source as Binary;
905 if (source is ReducedExpression)
906 b = ((ReducedExpression) source).OriginalExpression as Binary;
907 else if (source is ReducedExpression.ReducedConstantExpression) {
908 b = ((ReducedExpression.ReducedConstantExpression) source).OriginalExpression as Binary;
909 } else if (source is Nullable.LiftedBinaryOperator) {
910 var po = ((Nullable.LiftedBinaryOperator) source);
911 if (po.UserOperator == null)
913 } else if (source is TypeCast) {
914 b = ((TypeCast) source).Child as Binary;
920 // 2a. the operator is a shift operator
922 // 2b. the return type is explicitly convertible to the type of x, and
923 // y is implicitly convertible to the type of x
925 if ((b.Oper & Binary.Operator.ShiftMask) != 0 ||
926 Convert.ImplicitConversionExists (ec, right, target_type)) {
927 source = Convert.ExplicitConversion (ec, source, target_type, loc);
932 if (source.Type.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
933 Arguments arg = new Arguments (1);
934 arg.Add (new Argument (source));
935 return new SimpleAssign (target, new DynamicConversion (target_type, CSharpBinderFlags.ConvertExplicit, arg, loc), loc).Resolve (ec);
938 right.Error_ValueCannotBeConverted (ec, target_type, false);
942 protected override void CloneTo (CloneContext clonectx, Expression t)
944 CompoundAssign ctarget = (CompoundAssign) t;
946 ctarget.right = ctarget.source = source.Clone (clonectx);
947 ctarget.target = target.Clone (clonectx);
950 public override object Accept (StructuralVisitor visitor)
952 return visitor.Visit (this);