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;
17 using System.Collections;
19 namespace Mono.CSharp {
22 /// This interface is implemented by expressions that can be assigned to.
25 /// This interface is implemented by Expressions whose values can not
26 /// store the result on the top of the stack.
28 /// Expressions implementing this (Properties, Indexers and Arrays) would
29 /// perform an assignment of the Expression "source" into its final
32 /// No values on the top of the stack are expected to be left by
33 /// invoking this method.
35 public interface IAssignMethod {
37 // This is an extra version of Emit. If leave_copy is `true'
38 // A copy of the expression will be left on the stack at the
39 // end of the code generated for EmitAssign
41 void Emit (EmitContext ec, bool leave_copy);
44 // This method does the assignment
45 // `source' will be stored into the location specified by `this'
46 // if `leave_copy' is true, a copy of `source' will be left on the stack
47 // if `prepare_for_load' is true, when `source' is emitted, there will
48 // be data on the stack that it can use to compuatate its value. This is
49 // for expressions like a [f ()] ++, where you can't call `f ()' twice.
51 void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load);
54 For simple assignments, this interface is very simple, EmitAssign is called with source
55 as the source expression and leave_copy and prepare_for_load false.
57 For compound assignments it gets complicated.
59 EmitAssign will be called as before, however, prepare_for_load will be
60 true. The @source expression will contain an expression
61 which calls Emit. So, the calls look like:
63 this.EmitAssign (ec, source, false, true) ->
66 this.Emit (ec, false); ->
67 end this.Emit (ec, false); ->
70 end this.EmitAssign (ec, source, false, true)
73 When prepare_for_load is true, EmitAssign emits a `token' on the stack that
74 Emit will use for its state.
76 Let's take FieldExpr as an example. assume we are emitting f ().y += 1;
78 Here is the call tree again. This time, each call is annotated with the IL
81 this.EmitAssign (ec, source, false, true)
86 this.Emit (ec, false);
88 end this.Emit (ec, false);
98 end this.EmitAssign (ec, source, false, true)
101 1) EmitAssign left a token on the stack. It was the result of f ().
102 2) This token was used by Emit
104 leave_copy (in both EmitAssign and Emit) tells the compiler to leave a copy
105 of the expression at that point in evaluation. This is used for pre/post inc/dec
106 and for a = x += y. Let's do the above example with leave_copy true in EmitAssign
108 this.EmitAssign (ec, source, true, true)
113 this.Emit (ec, false);
115 end this.Emit (ec, false);
128 end this.EmitAssign (ec, source, true, true)
130 And with it true in Emit
132 this.EmitAssign (ec, source, false, true)
137 this.Emit (ec, true);
141 end this.Emit (ec, true);
152 end this.EmitAssign (ec, source, false, true)
154 Note that these two examples are what happens for ++x and x++, respectively.
159 /// An Expression to hold a temporary value.
162 /// The LocalTemporary class is used to hold temporary values of a given
163 /// type to "simulate" the expression semantics on property and indexer
164 /// access whose return values are void.
166 /// The local temporary is used to alter the normal flow of code generation
167 /// basically it creates a local variable, and its emit instruction generates
168 /// code to access this value, return its address or save its value.
170 /// If `is_address' is true, then the value that we store is the address to the
171 /// real value, and not the value itself.
173 /// This is needed for a value type, because otherwise you just end up making a
174 /// copy of the value on the stack and modifying it. You really need a pointer
175 /// to the origional value so that you can modify it in that location. This
176 /// Does not happen with a class because a class is a pointer -- so you always
177 /// get the indirection.
179 /// The `is_address' stuff is really just a hack. We need to come up with a better
180 /// way to handle it.
182 public class LocalTemporary : Expression, IMemoryLocation, IAssignMethod {
183 LocalBuilder builder;
186 public LocalTemporary (Type t) : this (t, false) {}
188 public LocalTemporary (Type t, bool is_address)
191 eclass = ExprClass.Value;
192 this.is_address = is_address;
195 public LocalTemporary (LocalBuilder b, Type t)
198 eclass = ExprClass.Value;
203 public void Release (EmitContext ec)
205 ec.FreeTemporaryLocal (builder, type);
209 public override Expression CreateExpressionTree (EmitContext ec)
211 ArrayList args = new ArrayList (1);
212 args.Add (new Argument (this));
213 return CreateExpressionFactoryCall ("Constant", args);
216 public override Expression DoResolve (EmitContext ec)
221 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
226 public override void Emit (EmitContext ec)
228 ILGenerator ig = ec.ig;
231 throw new InternalErrorException ("Emit without Store, or after Release");
233 ig.Emit (OpCodes.Ldloc, builder);
234 // we need to copy from the pointer
236 LoadFromPtr (ig, type);
239 #region IAssignMethod Members
241 public void Emit (EmitContext ec, bool leave_copy)
249 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
251 if (prepare_for_load)
252 throw new NotImplementedException ();
256 // HACK: variable is already emitted when source is an initializer
257 if (source is NewInitialize) {
271 public LocalBuilder Builder {
272 get { return builder; }
275 // NB: if you have `is_address' on the stack there must
276 // be a managed pointer. Otherwise, it is the type from
278 public void Store (EmitContext ec)
280 ILGenerator ig = ec.ig;
282 builder = ec.GetTemporaryLocal (is_address ? TypeManager.GetReferenceType (type): type);
284 ig.Emit (OpCodes.Stloc, builder);
287 public void AddressOf (EmitContext ec, AddressOp mode)
290 builder = ec.GetTemporaryLocal (is_address ? TypeManager.GetReferenceType (type): type);
292 // if is_address, than this is just the address anyways,
293 // so we just return this.
294 ILGenerator ig = ec.ig;
297 ig.Emit (OpCodes.Ldloc, builder);
299 ig.Emit (OpCodes.Ldloca, builder);
302 public bool PointsToAddress {
310 /// The Assign node takes care of assigning the value of source into
311 /// the expression represented by target.
313 public class Assign : ExpressionStatement {
314 protected Expression target, source;
316 protected Assign (Expression target, Expression source, Location loc)
318 this.target = target;
319 this.source = source;
323 public override Expression CreateExpressionTree (EmitContext ec)
325 Report.Error (832, loc, "An expression tree cannot contain an assignment operator");
329 public Expression Target {
330 get { return target; }
333 public Expression Source {
334 get { return source; }
337 public override Expression DoResolve (EmitContext ec)
340 source = source.Resolve (ec);
342 if (source == null) {
344 source = EmptyExpression.Null;
347 target = target.ResolveLValue (ec, source, Location);
349 if (target == null || !ok)
352 Type target_type = target.Type;
353 Type source_type = source.Type;
355 eclass = ExprClass.Value;
358 if (!(target is IAssignMethod)) {
359 Error_ValueAssignment (loc);
363 if ((source.eclass == ExprClass.Type) && (source is TypeExpr)) {
364 source.Error_UnexpectedKind (ec.DeclContainer, "variable or value", loc);
366 } else if ((RootContext.Version == LanguageVersion.ISO_1) &&
367 (source is MethodGroupExpr)){
368 ((MethodGroupExpr) source).ReportUsageError ();
372 if (TypeManager.IsEqual (target_type, source_type)) {
373 if (target.eclass == ExprClass.Variable) {
374 New n = source as New;
378 if (n.HasInitializer) {
379 n.SetTargetVariable (target);
380 } else if (target_type.IsValueType) {
381 n.SetTargetVariable (target);
389 return ResolveConversions (ec);
392 public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
394 source.MutateHoistedGenericType (storey);
395 target.MutateHoistedGenericType (storey);
396 type = storey.MutateType (type);
399 protected virtual Expression ResolveConversions (EmitContext ec)
401 source = Convert.ImplicitConversionRequired (ec, source, target.Type, loc);
408 void Emit (EmitContext ec, bool is_statement)
410 ((IAssignMethod) target).EmitAssign (ec, source, !is_statement, this is CompoundAssign);
413 public override void Emit (EmitContext ec)
418 public override void EmitStatement (EmitContext ec)
423 protected override void CloneTo (CloneContext clonectx, Expression t)
425 Assign _target = (Assign) t;
427 _target.target = target.Clone (clonectx);
428 _target.source = source.Clone (clonectx);
432 class SimpleAssign : Assign {
433 public SimpleAssign (Expression target, Expression source)
434 : this (target, source, target.Location)
438 public SimpleAssign (Expression target, Expression source, Location loc)
439 : base (target, source, loc)
443 bool CheckEqualAssign (Expression t)
445 if (source is Assign) {
446 Assign a = (Assign) source;
447 if (t.Equals (a.Target))
449 return a is SimpleAssign && ((SimpleAssign) a).CheckEqualAssign (t);
451 return t.Equals (source);
454 public override Expression DoResolve (EmitContext ec)
456 Expression e = base.DoResolve (ec);
457 if (e == null || e != this)
460 if (CheckEqualAssign (target))
461 Report.Warning (1717, 3, loc, "Assignment made to same variable; did you mean to assign something else?");
467 // This class implements fields and events class initializers
468 public class FieldInitializer : Assign
471 // Keep resolved value because field initializers have their own rules
473 ExpressionStatement resolved;
475 public FieldInitializer (FieldBuilder field, Expression expression)
476 : base (new FieldExpr (field, expression.Location, true), expression, expression.Location)
479 ((FieldExpr)target).InstanceExpression = CompilerGeneratedThis.Instance;
482 public override Expression DoResolve (EmitContext ec)
484 // Field initializer can be resolved (fail) many times
488 if (resolved == null)
489 resolved = base.DoResolve (ec) as ExpressionStatement;
494 public override void EmitStatement (EmitContext ec)
496 if (resolved == null)
499 if (resolved != this)
500 resolved.EmitStatement (ec);
502 base.EmitStatement (ec);
505 public bool IsComplexInitializer {
506 get { return !(source is Constant); }
509 public bool IsDefaultInitializer {
511 Constant c = source as Constant;
515 FieldExpr fe = (FieldExpr)target;
516 return c.IsDefaultInitializer (fe.Type);
521 class EventAddOrRemove : ExpressionStatement {
526 public EventAddOrRemove (Expression target, Binary.Operator op, Expression source, Location loc)
528 this.target = target as EventExpr;
530 this.source = source;
534 public override Expression CreateExpressionTree (EmitContext ec)
536 return new SimpleAssign (target, source).CreateExpressionTree (ec);
539 public override Expression DoResolve (EmitContext ec)
541 source = source.Resolve (ec);
545 source = Convert.ImplicitConversionRequired (ec, source, target.Type, loc);
549 eclass = ExprClass.Value;
550 type = TypeManager.void_type;
554 public override void Emit (EmitContext ec)
556 throw new InternalErrorException ("don't know what to emit");
559 public override void EmitStatement (EmitContext ec)
561 target.EmitAddOrRemove (ec, op == Binary.Operator.Addition, source);
566 // This class is used for compound assignments.
568 class CompoundAssign : Assign {
570 Expression original_source;
572 public CompoundAssign (Binary.Operator op, Expression target, Expression source)
573 : base (target, source, target.Location)
575 original_source = source;
579 // !!! What a stupid name
580 public class Helper : Expression {
582 public Helper (Expression child)
585 this.loc = child.Location;
588 public override Expression CreateExpressionTree (EmitContext ec)
590 throw new NotSupportedException ("ET");
593 public override Expression DoResolve (EmitContext ec)
595 child = child.Resolve (ec);
599 eclass = ExprClass.Value;
603 public override void Emit (EmitContext ec)
609 public override Expression DoResolve (EmitContext ec)
611 original_source = original_source.Resolve (ec);
612 if (original_source == null)
615 using (ec.Set (EmitContext.Flags.InCompoundAssignment)) {
616 target = target.Resolve (ec);
622 if (target is MethodGroupExpr){
623 Error_CannotAssign (((MethodGroupExpr)target).Name, target.ExprClassName);
627 if (target is EventExpr)
628 return new EventAddOrRemove (target, op, original_source, loc).DoResolve (ec);
631 // Only now we can decouple the original source/target
632 // into a tree, to guarantee that we do not have side
635 source = new Binary (op, new Helper (target), original_source, true);
636 return base.DoResolve (ec);
639 protected override Expression ResolveConversions (EmitContext ec)
641 // source might have changed to BinaryDelegate
642 Type target_type = target.Type;
643 Type source_type = source.Type;
644 Binary b = source as Binary;
646 return base.ResolveConversions (ec);
648 // FIXME: Restrict only to predefined operators
651 // 1. if the source is explicitly convertible to the
654 source = Convert.ExplicitConversion (ec, source, target_type, loc);
656 original_source.Error_ValueCannotBeConverted (ec, loc, target_type, true);
661 // 2. and the original right side is implicitly convertible to
662 // the type of target
664 if (Convert.ImplicitConversionExists (ec, original_source, target_type))
668 // In the spec 2.4 they added: or if type of the target is int
669 // and the operator is a shift operator...
671 if (source_type == TypeManager.int32_type && (b.Oper & Binary.Operator.ShiftMask) != 0)
674 original_source.Error_ValueCannotBeConverted (ec, loc, target_type, false);
678 protected override void CloneTo (CloneContext clonectx, Expression t)
680 CompoundAssign ctarget = (CompoundAssign) t;
682 ctarget.original_source = ctarget.source = source.Clone (clonectx);
683 ctarget.target = target.Clone (clonectx);