2 // assign.cs: Assignments.
5 // Miguel de Icaza (miguel@ximian.com)
6 // Martin Baulig (martin@ximian.com)
8 // (C) 2001, 2002, 2003 Ximian, Inc.
9 // (C) 2004 Novell, Inc
12 using System.Reflection;
13 using System.Reflection.Emit;
15 namespace Mono.CSharp {
18 /// This interface is implemented by expressions that can be assigned to.
21 /// This interface is implemented by Expressions whose values can not
22 /// store the result on the top of the stack.
24 /// Expressions implementing this (Properties, Indexers and Arrays) would
25 /// perform an assignment of the Expression "source" into its final
28 /// No values on the top of the stack are expected to be left by
29 /// invoking this method.
31 public interface IAssignMethod {
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
37 void Emit (EmitContext ec, bool leave_copy);
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.
47 void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load);
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.
53 For compound assignments it gets complicated.
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:
59 this.EmitAssign (ec, source, false, true) ->
62 this.Emit (ec, false); ->
63 end this.Emit (ec, false); ->
66 end this.EmitAssign (ec, source, false, true)
69 When prepare_for_load is true, EmitAssign emits a `token' on the stack that
70 Emit will use for its state.
72 Let's take FieldExpr as an example. assume we are emitting f ().y += 1;
74 Here is the call tree again. This time, each call is annotated with the IL
77 this.EmitAssign (ec, source, false, true)
82 this.Emit (ec, false);
84 end this.Emit (ec, false);
94 end this.EmitAssign (ec, source, false, true)
97 1) EmitAssign left a token on the stack. It was the result of f ().
98 2) This token was used by Emit
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
104 this.EmitAssign (ec, source, true, true)
109 this.Emit (ec, false);
111 end this.Emit (ec, false);
124 end this.EmitAssign (ec, source, true, true)
126 And with it true in Emit
128 this.EmitAssign (ec, source, false, true)
133 this.Emit (ec, true);
137 end this.Emit (ec, true);
148 end this.EmitAssign (ec, source, false, true)
150 Note that these two examples are what happens for ++x and x++, respectively.
155 /// An Expression to hold a temporary value.
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.
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.
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.
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.
175 /// The `is_address' stuff is really just a hack. We need to come up with a better
176 /// way to handle it.
178 public class LocalTemporary : Expression, IMemoryLocation {
179 LocalBuilder builder;
182 public LocalTemporary (EmitContext ec, Type t) : this (ec, t, false) {}
184 public LocalTemporary (EmitContext ec, Type t, bool is_address)
187 eclass = ExprClass.Value;
189 builder = ec.GetTemporaryLocal (is_address ? TypeManager.GetReferenceType (t): t);
190 this.is_address = is_address;
193 public LocalTemporary (LocalBuilder b, Type t)
196 eclass = ExprClass.Value;
201 public void Release (EmitContext ec)
203 ec.FreeTemporaryLocal (builder, type);
207 public override Expression DoResolve (EmitContext ec)
212 public override void Emit (EmitContext ec)
214 ILGenerator ig = ec.ig;
216 ig.Emit (OpCodes.Ldloc, builder);
217 // we need to copy from the pointer
219 LoadFromPtr (ig, type);
222 // NB: if you have `is_address' on the stack there must
223 // be a managed pointer. Otherwise, it is the type from
225 public void Store (EmitContext ec)
227 ILGenerator ig = ec.ig;
228 ig.Emit (OpCodes.Stloc, builder);
231 public void AddressOf (EmitContext ec, AddressOp mode)
233 // if is_address, than this is just the address anyways,
234 // so we just return this.
235 ILGenerator ig = ec.ig;
238 ig.Emit (OpCodes.Ldloc, builder);
240 ig.Emit (OpCodes.Ldloca, builder);
243 public bool PointsToAddress {
251 /// The Assign node takes care of assigning the value of source into
252 /// the expression represented by target.
254 public class Assign : ExpressionStatement {
255 protected Expression target, source, real_source;
256 protected LocalTemporary temp = null, real_temp = null;
257 protected Assign embedded = null;
258 protected bool is_embedded = false;
259 protected bool must_free_temp = false;
261 public Assign (Expression target, Expression source, Location l)
263 this.target = target;
264 this.source = this.real_source = source;
268 protected Assign (Assign embedded, Location l)
269 : this (embedded.target, embedded.source, l)
271 this.is_embedded = true;
274 protected virtual Assign GetEmbeddedAssign (Location loc)
276 return new Assign (this, loc);
279 public Expression Target {
289 public Expression Source {
299 public static void error70 (EventInfo ei, Location l)
301 Report.Error (70, l, "The event '" + ei.Name +
302 "' can only appear on the left-side of a += or -= (except when" +
303 " used from within the type '" + ei.DeclaringType + "')");
307 // Will return either `this' or an instance of `New'.
309 public override Expression DoResolve (EmitContext ec)
311 // Create an embedded assignment if our source is an assignment.
312 if (source is Assign)
313 source = embedded = ((Assign) source).GetEmbeddedAssign (loc);
315 real_source = source = source.Resolve (ec);
316 if (source == null) {
317 // Ensure that we don't propagate the error as spurious "uninitialized variable" errors.
318 target = target.ResolveLValue (ec, EmptyExpression.Null);
323 // This is used in an embedded assignment.
324 // As an example, consider the statement "A = X = Y = Z".
326 if (is_embedded && !(source is Constant)) {
327 // If this is the innermost assignment (the "Y = Z" in our example),
328 // create a new temporary local, otherwise inherit that variable
329 // from our child (the "X = (Y = Z)" inherits the local from the
330 // "Y = Z" assignment).
332 if (embedded == null) {
333 if (this is CompoundAssign)
334 real_temp = temp = new LocalTemporary (ec, target.Type);
336 real_temp = temp = new LocalTemporary (ec, source.Type);
338 temp = embedded.temp;
340 // Set the source to the new temporary variable.
341 // This means that the following target.ResolveLValue () will tell
342 // the target to read it's source value from that variable.
346 // If we have an embedded assignment, use the embedded assignment's temporary
347 // local variable as source.
348 if (embedded != null)
349 source = (embedded.temp != null) ? embedded.temp : embedded.source;
351 target = target.ResolveLValue (ec, source);
356 if (source.Equals (target)) {
357 Report.Warning (1717, 3, loc, "Assignment made to same variable; did you mean to assign something else?");
360 Type target_type = target.Type;
361 Type source_type = real_source.Type;
363 // If we're an embedded assignment, our parent will reuse our source as its
364 // source, it won't read from our target.
369 eclass = ExprClass.Value;
371 if (target is EventExpr) {
372 EventInfo ei = ((EventExpr) target).EventInfo;
374 Expression ml = MemberLookup (
375 ec, ec.ContainerType, ei.Name,
376 MemberTypes.Event, AllBindingFlags | BindingFlags.DeclaredOnly, loc);
380 // If this is the case, then the Event does not belong
381 // to this Type and so, according to the spec
382 // is allowed to only appear on the left hand of
383 // the += and -= operators
385 // Note that target will not appear as an EventExpr
386 // in the case it is being referenced within the same type container;
387 // it will appear as a FieldExpr in that case.
390 if (!(source is BinaryDelegate)) {
397 FieldExpr field_exp = target as FieldExpr;
398 if (field_exp != null && field_exp.DeclaringType.IsValueType && !ec.IsConstructor && !ec.IsFieldInitializer) {
399 field_exp = field_exp.InstanceExpression as FieldExpr;
400 if (field_exp != null && field_exp.FieldInfo.IsInitOnly) {
401 if (field_exp.IsStatic) {
402 Report.Error (1650, loc, "Members of static readonly field '{0}' cannot be assigned to " +
403 "(except in a static constructor or a variable initializer)", TypeManager.GetFullNameSignature (field_exp.FieldInfo));
405 Report.Error (1648, loc, "Members of readonly field '{0}' cannot be assigned to " +
406 "(except in a constructor or a variable initializer)", TypeManager.GetFullNameSignature (field_exp.FieldInfo));
412 if (!(target is IAssignMethod) && (target.eclass != ExprClass.EventAccess)) {
413 Report.Error (131, loc,
414 "Left hand of an assignment must be a variable, " +
415 "a property or an indexer");
419 if ((source.eclass == ExprClass.Type) && (source is TypeExpr)) {
420 source.Error_UnexpectedKind ("variable or value", loc);
422 } else if ((RootContext.Version == LanguageVersion.ISO_1) &&
423 (source is MethodGroupExpr)){
424 ((MethodGroupExpr) source).ReportUsageError ();
429 if (target_type == source_type){
430 if (source is New && target_type.IsValueType &&
431 (target.eclass != ExprClass.IndexerAccess) && (target.eclass != ExprClass.PropertyAccess)){
432 New n = (New) source;
434 if (n.SetValueTypeVariable (target))
444 // If this assignemnt/operator was part of a compound binary
445 // operator, then we allow an explicit conversion, as detailed
449 if (this is CompoundAssign){
450 CompoundAssign a = (CompoundAssign) this;
452 Binary b = source as Binary;
455 // 1. if the source is explicitly convertible to the
459 source = Convert.ExplicitConversion (ec, source, target_type, loc);
461 Convert.Error_CannotImplicitConversion (loc, source_type, target_type);
466 // 2. and the original right side is implicitly convertible to
467 // the type of target
469 if (Convert.ImplicitStandardConversionExists (ec, a.original_source, target_type))
473 // In the spec 2.4 they added: or if type of the target is int
474 // and the operator is a shift operator...
476 if (source_type == TypeManager.int32_type &&
477 (b.Oper == Binary.Operator.LeftShift || b.Oper == Binary.Operator.RightShift))
480 Convert.Error_CannotImplicitConversion (loc, a.original_source.Type, target_type);
485 source = Convert.ImplicitConversionRequired (ec, source, target_type, loc);
489 // If we're an embedded assignment, we need to create a new temporary variable
490 // for the converted value. Our parent will use this new variable as its source.
491 // The same applies when we have an embedded assignment - in this case, we need
492 // to convert our embedded assignment's temporary local variable to the correct
493 // type and store it in a new temporary local.
494 if (is_embedded || embedded != null) {
496 temp = new LocalTemporary (ec, type);
497 must_free_temp = true;
503 Expression EmitEmbedded (EmitContext ec)
505 // Emit an embedded assignment.
507 if (real_temp != null) {
508 // If we're the innermost assignment, `real_source' is the right-hand
509 // expression which gets assigned to all the variables left of it.
510 // Emit this expression and store its result in real_temp.
511 real_source.Emit (ec);
512 real_temp.Store (ec);
515 if (embedded != null)
516 embedded.EmitEmbedded (ec);
518 // This happens when we've done a type conversion, in this case source will be
519 // the expression which does the type conversion from real_temp.
520 // So emit it and store the result in temp; this is the var which will be read
522 if (temp != real_temp) {
527 Expression temp_source = (temp != null) ? temp : source;
528 ((IAssignMethod) target).EmitAssign (ec, temp_source, false, false);
532 void ReleaseEmbedded (EmitContext ec)
534 if (embedded != null)
535 embedded.ReleaseEmbedded (ec);
537 if (real_temp != null)
538 real_temp.Release (ec);
544 void Emit (EmitContext ec, bool is_statement)
546 if (target is EventExpr) {
547 ((EventExpr) target).EmitAddOrRemove (ec, source);
551 IAssignMethod am = (IAssignMethod) target;
553 Expression temp_source;
554 if (embedded != null) {
555 temp_source = embedded.EmitEmbedded (ec);
563 temp_source = source;
565 am.EmitAssign (ec, temp_source, !is_statement, this is CompoundAssign);
567 if (embedded != null) {
570 embedded.ReleaseEmbedded (ec);
574 public override void Emit (EmitContext ec)
579 public override void EmitStatement (EmitContext ec)
587 // This class is used for compound assignments.
589 class CompoundAssign : Assign {
591 public Expression original_source;
593 public CompoundAssign (Binary.Operator op, Expression target, Expression source, Location l)
594 : base (target, source, l)
596 original_source = source;
600 protected CompoundAssign (CompoundAssign embedded, Location l)
601 : this (embedded.op, embedded.target, embedded.source, l)
603 this.is_embedded = true;
606 protected override Assign GetEmbeddedAssign (Location loc)
608 return new CompoundAssign (this, loc);
611 public Expression ResolveSource (EmitContext ec)
613 return original_source.Resolve (ec);
616 public override Expression DoResolve (EmitContext ec)
618 original_source = original_source.Resolve (ec);
619 if (original_source == null)
622 target = target.Resolve (ec);
627 // Only now we can decouple the original source/target
628 // into a tree, to guarantee that we do not have side
631 source = new Binary (op, target, original_source, loc);
632 return base.DoResolve (ec);