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 (Type t) : this (t, false) {}
184 public LocalTemporary (Type t, bool is_address)
187 eclass = ExprClass.Value;
188 this.is_address = is_address;
191 public LocalTemporary (LocalBuilder b, Type t)
194 eclass = ExprClass.Value;
199 public void Release (EmitContext ec)
201 ec.FreeTemporaryLocal (builder, type);
205 public override Expression DoResolve (EmitContext ec)
210 public override void Emit (EmitContext ec)
212 ILGenerator ig = ec.ig;
215 throw new InternalErrorException ("Emit without Store, or after Release");
217 ig.Emit (OpCodes.Ldloc, builder);
218 // we need to copy from the pointer
220 LoadFromPtr (ig, type);
223 // NB: if you have `is_address' on the stack there must
224 // be a managed pointer. Otherwise, it is the type from
226 public void Store (EmitContext ec)
228 ILGenerator ig = ec.ig;
230 builder = ec.GetTemporaryLocal (is_address ? TypeManager.GetReferenceType (type): type);
232 ig.Emit (OpCodes.Stloc, builder);
235 public void AddressOf (EmitContext ec, AddressOp mode)
238 builder = ec.GetTemporaryLocal (is_address ? TypeManager.GetReferenceType (type): type);
240 // if is_address, than this is just the address anyways,
241 // so we just return this.
242 ILGenerator ig = ec.ig;
245 ig.Emit (OpCodes.Ldloc, builder);
247 ig.Emit (OpCodes.Ldloca, builder);
250 public bool PointsToAddress {
258 /// The Assign node takes care of assigning the value of source into
259 /// the expression represented by target.
261 public class Assign : ExpressionStatement {
262 protected Expression target, source, real_source;
263 protected LocalTemporary temp = null, real_temp = null;
264 protected Assign embedded = null;
265 protected bool is_embedded = false;
266 protected bool must_free_temp = false;
268 public Assign (Expression target, Expression source)
269 : this (target, source, target.Location)
273 public Assign (Expression target, Expression source, Location l)
275 this.target = target;
276 this.source = this.real_source = source;
280 protected Assign (Assign embedded, Location l)
281 : this (embedded.target, embedded.source, l)
283 this.is_embedded = true;
286 protected virtual Assign GetEmbeddedAssign (Location loc)
288 return new Assign (this, loc);
291 public Expression Target {
301 public Expression Source {
311 public static void error70 (EventInfo ei, Location l)
313 Report.Error (70, l, "The event `" + TypeManager.CSharpSignature (ei) +
314 "' can only appear on the left hand side of += or -= (except when" +
315 " used from within the type `" + ei.DeclaringType + "')");
319 // Will return either `this' or an instance of `New'.
321 public override Expression DoResolve (EmitContext ec)
323 // Create an embedded assignment if our source is an assignment.
324 if (source is Assign)
325 source = embedded = ((Assign) source).GetEmbeddedAssign (loc);
327 real_source = source = source.Resolve (ec);
329 // Check for and handle varible type inference
330 LocalVariableReference l = target as LocalVariableReference;
332 VarExpr v = l.Block.GetVariableType(l.Name) as VarExpr;
333 if (v != null && !v.Handled) {
334 ((LocalInfo)l.Block.Variables[l.Name]).VariableType = real_source.Type;
339 if (source == null) {
340 // Ensure that we don't propagate the error as spurious "uninitialized variable" errors.
341 target = target.ResolveLValue (ec, EmptyExpression.Null, Location);
346 // This is used in an embedded assignment.
347 // As an example, consider the statement "A = X = Y = Z".
349 if (is_embedded && !(source is Constant)) {
350 // If this is the innermost assignment (the "Y = Z" in our example),
351 // create a new temporary local, otherwise inherit that variable
352 // from our child (the "X = (Y = Z)" inherits the local from the
353 // "Y = Z" assignment).
355 if (embedded == null) {
356 if (this is CompoundAssign)
357 real_temp = temp = new LocalTemporary (target.Type);
359 real_temp = temp = new LocalTemporary (source.Type);
361 temp = embedded.temp;
363 // Set the source to the new temporary variable.
364 // This means that the following target.ResolveLValue () will tell
365 // the target to read it's source value from that variable.
369 // If we have an embedded assignment, use the embedded assignment's temporary
370 // local variable as source.
371 if (embedded != null)
372 source = (embedded.temp != null) ? embedded.temp : embedded.source;
374 target = target.ResolveLValue (ec, source, Location);
379 // Handle initializations e.g. Person p = new Person () { Name = "Scott" };
380 IInitializable initializer = source as IInitializable;
381 if (initializer != null && !initializer.Initialize (ec, target))
384 bool same_assignment = (embedded != null) ? embedded.Target.Equals(target) : source.Equals (target);
385 if (same_assignment) {
386 Report.Warning (1717, 3, loc, "Assignment made to same variable; did you mean to assign something else?");
389 Type target_type = target.Type;
390 Type source_type = real_source.Type;
392 // If we're an embedded assignment, our parent will reuse our source as its
393 // source, it won't read from our target.
398 eclass = ExprClass.Value;
400 if (target is EventExpr) {
401 EventInfo ei = ((EventExpr) target).EventInfo;
403 Expression ml = MemberLookup (
404 ec.ContainerType, ec.ContainerType, ei.Name,
405 MemberTypes.Event, AllBindingFlags | BindingFlags.DeclaredOnly, loc);
409 // If this is the case, then the Event does not belong
410 // to this Type and so, according to the spec
411 // is allowed to only appear on the left hand of
412 // the += and -= operators
414 // Note that target will not appear as an EventExpr
415 // in the case it is being referenced within the same type container;
416 // it will appear as a FieldExpr in that case.
419 if (!(source is BinaryDelegate)) {
426 if (!(target is IAssignMethod) && (target.eclass != ExprClass.EventAccess)) {
427 Error_ValueAssignment (loc);
431 if ((source.eclass == ExprClass.Type) && (source is TypeExpr)) {
432 source.Error_UnexpectedKind (ec.DeclContainer, "variable or value", loc);
434 } else if ((RootContext.Version == LanguageVersion.ISO_1) &&
435 (source is MethodGroupExpr)){
436 ((MethodGroupExpr) source).ReportUsageError ();
441 if (target_type == source_type){
442 if (source is New && target_type.IsValueType &&
443 (target.eclass != ExprClass.IndexerAccess) && (target.eclass != ExprClass.PropertyAccess)){
444 New n = (New) source;
446 if (n.SetValueTypeVariable (target))
456 // If this assignment/operator was part of a compound binary
457 // operator, then we allow an explicit conversion, as detailed
461 if (this is CompoundAssign){
462 CompoundAssign a = (CompoundAssign) this;
464 Binary b = source as Binary;
467 // 1. if the source is explicitly convertible to the
471 source = Convert.ExplicitConversion (ec, source, target_type, loc);
473 a.original_source.Error_ValueCannotBeConverted (ec, loc, target_type, true);
478 // 2. and the original right side is implicitly convertible to
479 // the type of target
481 if (Convert.ImplicitConversionExists (ec, a.original_source, target_type))
485 // In the spec 2.4 they added: or if type of the target is int
486 // and the operator is a shift operator...
488 if (source_type == TypeManager.int32_type &&
489 (b.Oper == Binary.Operator.LeftShift || b.Oper == Binary.Operator.RightShift))
492 a.original_source.Error_ValueCannotBeConverted (ec, loc, target_type, false);
497 if (source.eclass == ExprClass.MethodGroup && !TypeManager.IsDelegateType (target_type)) {
498 Report.Error (428, source.Location, "Cannot convert method group `{0}' to non-delegate type `{1}'. Did you intend to invoke the method?",
499 ((MethodGroupExpr)source).Name, target.GetSignatureForError ());
503 source = Convert.ImplicitConversionRequired (ec, source, target_type, loc);
507 // If we're an embedded assignment, we need to create a new temporary variable
508 // for the converted value. Our parent will use this new variable as its source.
509 // The same applies when we have an embedded assignment - in this case, we need
510 // to convert our embedded assignment's temporary local variable to the correct
511 // type and store it in a new temporary local.
512 if (is_embedded || embedded != null) {
514 temp = new LocalTemporary (type);
515 must_free_temp = true;
521 Expression EmitEmbedded (EmitContext ec)
523 // Emit an embedded assignment.
525 if (real_temp != null) {
526 // If we're the innermost assignment, `real_source' is the right-hand
527 // expression which gets assigned to all the variables left of it.
528 // Emit this expression and store its result in real_temp.
529 real_source.Emit (ec);
530 real_temp.Store (ec);
533 if (embedded != null)
534 embedded.EmitEmbedded (ec);
536 // This happens when we've done a type conversion, in this case source will be
537 // the expression which does the type conversion from real_temp.
538 // So emit it and store the result in temp; this is the var which will be read
540 if (temp != real_temp) {
545 Expression temp_source = (temp != null) ? temp : source;
546 ((IAssignMethod) target).EmitAssign (ec, temp_source, false, false);
550 void ReleaseEmbedded (EmitContext ec)
552 if (embedded != null)
553 embedded.ReleaseEmbedded (ec);
555 if (real_temp != null)
556 real_temp.Release (ec);
562 void Emit (EmitContext ec, bool is_statement)
564 if (target is EventExpr) {
565 ((EventExpr) target).EmitAddOrRemove (ec, source);
569 IAssignMethod am = (IAssignMethod) target;
571 Expression temp_source;
572 if (embedded != null) {
573 temp_source = embedded.EmitEmbedded (ec);
581 temp_source = source;
583 am.EmitAssign (ec, temp_source, !is_statement, this is CompoundAssign);
585 if (embedded != null) {
588 embedded.ReleaseEmbedded (ec);
592 public override void Emit (EmitContext ec)
597 public override void EmitStatement (EmitContext ec)
602 protected override void CloneTo (CloneContext clonectx, Expression t)
604 Assign _target = (Assign) t;
606 _target.target = target.Clone (clonectx);
607 _target.source = source.Clone (clonectx);
612 // This class implements fields and events class initializers
613 public class FieldInitializer : Assign
615 public readonly DeclSpace TypeContainer;
617 public FieldInitializer (FieldBuilder field, Expression expression, DeclSpace container)
618 : base (new FieldExpr (field, expression.Location, true), expression)
620 this.TypeContainer = container;
622 ((FieldExpr)target).InstanceExpression = CompilerGeneratedThis.Instance;
625 public bool IsComplexInitializer {
627 if (embedded != null)
630 return !(source is Constant);
634 public bool IsDefaultInitializer {
636 Constant c = source as Constant;
640 FieldExpr fe = (FieldExpr)target;
641 return c.IsDefaultInitializer (fe.Type);
648 // This class is used for compound assignments.
650 class CompoundAssign : Assign {
652 public Expression original_source;
654 public CompoundAssign (Binary.Operator op, Expression target, Expression source)
655 : base (target, source, target.Location)
657 original_source = source;
661 protected CompoundAssign (CompoundAssign embedded, Location l)
662 : this (embedded.op, embedded.target, embedded.source)
664 this.is_embedded = true;
667 protected override Assign GetEmbeddedAssign (Location loc)
669 return new CompoundAssign (this, loc);
672 public override Expression DoResolve (EmitContext ec)
674 original_source = original_source.Resolve (ec);
675 if (original_source == null)
678 target = target.Resolve (ec);
682 if (target is MethodGroupExpr){
683 Error_CannotAssign (((MethodGroupExpr)target).Name, target.ExprClassName);
687 // Only now we can decouple the original source/target
688 // into a tree, to guarantee that we do not have side
691 source = new Binary (op, target, original_source);
692 return base.DoResolve (ec);
695 protected override void CloneTo (CloneContext clonectx, Expression t)
697 CompoundAssign target = (CompoundAssign) t;
699 target.original_source = original_source.Clone (clonectx);