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 (ResolveContext ec
)
211 Arguments args
= new Arguments (1);
212 args
.Add (new Argument (this));
213 return CreateExpressionFactoryCall ("Constant", args
);
216 public override Expression
DoResolve (ResolveContext ec
)
221 public override Expression
DoResolveLValue (ResolveContext 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 ();
264 public LocalBuilder Builder
{
265 get { return builder; }
268 // NB: if you have `is_address' on the stack there must
269 // be a managed pointer. Otherwise, it is the type from
271 public void Store (EmitContext ec
)
273 ILGenerator ig
= ec
.ig
;
275 builder
= ec
.GetTemporaryLocal (is_address
? TypeManager
.GetReferenceType (type
): type
);
277 ig
.Emit (OpCodes
.Stloc
, builder
);
280 public void AddressOf (EmitContext ec
, AddressOp mode
)
283 builder
= ec
.GetTemporaryLocal (is_address
? TypeManager
.GetReferenceType (type
): type
);
285 // if is_address, than this is just the address anyways,
286 // so we just return this.
287 ILGenerator ig
= ec
.ig
;
290 ig
.Emit (OpCodes
.Ldloc
, builder
);
292 ig
.Emit (OpCodes
.Ldloca
, builder
);
295 public override void MutateHoistedGenericType (AnonymousMethodStorey storey
)
297 type
= storey
.MutateType (type
);
300 public bool PointsToAddress
{
308 /// The Assign node takes care of assigning the value of source into
309 /// the expression represented by target.
311 public class Assign
: ExpressionStatement
{
312 protected Expression target
, source
;
314 protected Assign (Expression target
, Expression source
, Location loc
)
316 this.target
= target
;
317 this.source
= source
;
321 public override Expression
CreateExpressionTree (ResolveContext ec
)
323 Report
.Error (832, loc
, "An expression tree cannot contain an assignment operator");
327 public Expression Target
{
328 get { return target; }
331 public Expression Source
{
332 get { return source; }
335 public override Expression
DoResolve (ResolveContext ec
)
338 source
= source
.Resolve (ec
);
340 if (source
== null) {
342 source
= EmptyExpression
.Null
;
345 target
= target
.ResolveLValue (ec
, source
);
347 if (target
== null || !ok
)
350 Type target_type
= target
.Type
;
351 Type source_type
= source
.Type
;
353 eclass
= ExprClass
.Value
;
356 if (!(target
is IAssignMethod
)) {
357 Error_ValueAssignment (loc
);
361 if ((RootContext
.Version
== LanguageVersion
.ISO_1
) &&
362 (source
is MethodGroupExpr
)){
363 ((MethodGroupExpr
) source
).ReportUsageError ();
367 if (!TypeManager
.IsEqual (target_type
, source_type
)) {
368 if (TypeManager
.IsDynamicType (source_type
)) {
369 Arguments args
= new Arguments (1);
370 args
.Add (new Argument (source
));
371 return new DynamicConversion (target_type
, false, args
, loc
).Resolve (ec
);
374 Expression resolved
= ResolveConversions (ec
);
376 if (resolved
!= this)
383 public override void MutateHoistedGenericType (AnonymousMethodStorey storey
)
385 source
.MutateHoistedGenericType (storey
);
386 target
.MutateHoistedGenericType (storey
);
387 type
= storey
.MutateType (type
);
390 protected virtual Expression
ResolveConversions (ResolveContext ec
)
392 source
= Convert
.ImplicitConversionRequired (ec
, source
, target
.Type
, loc
);
399 void Emit (EmitContext ec
, bool is_statement
)
401 IAssignMethod t
= (IAssignMethod
) target
;
402 t
.EmitAssign (ec
, source
, !is_statement
, this is CompoundAssign
);
405 public override void Emit (EmitContext ec
)
410 public override void EmitStatement (EmitContext ec
)
415 protected override void CloneTo (CloneContext clonectx
, Expression t
)
417 Assign _target
= (Assign
) t
;
419 _target
.target
= target
.Clone (clonectx
);
420 _target
.source
= source
.Clone (clonectx
);
424 class SimpleAssign
: Assign
{
425 public SimpleAssign (Expression target
, Expression source
)
426 : this (target
, source
, target
.Location
)
430 public SimpleAssign (Expression target
, Expression source
, Location loc
)
431 : base (target
, source
, loc
)
435 bool CheckEqualAssign (Expression t
)
437 if (source
is Assign
) {
438 Assign a
= (Assign
) source
;
439 if (t
.Equals (a
.Target
))
441 return a
is SimpleAssign
&& ((SimpleAssign
) a
).CheckEqualAssign (t
);
443 return t
.Equals (source
);
446 public override Expression
DoResolve (ResolveContext ec
)
448 Expression e
= base.DoResolve (ec
);
449 if (e
== null || e
!= this)
452 if (CheckEqualAssign (target
))
453 Report
.Warning (1717, 3, loc
, "Assignment made to same variable; did you mean to assign something else?");
459 // This class implements fields and events class initializers
460 public class FieldInitializer
: Assign
463 // Keep resolved value because field initializers have their own rules
465 ExpressionStatement resolved
;
468 public FieldInitializer (FieldBuilder field
, Expression expression
, IMemberContext rc
)
469 : base (new FieldExpr (field
, expression
.Location
), expression
, expression
.Location
)
473 ((FieldExpr
)target
).InstanceExpression
= CompilerGeneratedThis
.Instance
;
476 public override Expression
DoResolve (ResolveContext ec
)
478 // Field initializer can be resolved (fail) many times
482 if (resolved
== null) {
484 // Field initializers are tricky for partial classes. They have to
485 // share same costructor (block) but they have they own resolve scope.
488 IMemberContext old
= ec
.MemberContext
;
489 ec
.MemberContext
= rc
;
491 using (ec
.Set (ResolveContext
.Options
.FieldInitializerScope
)) {
492 resolved
= base.DoResolve (ec
) as ExpressionStatement
;
495 ec
.MemberContext
= old
;
501 public override void EmitStatement (EmitContext ec
)
503 if (resolved
== null)
506 if (resolved
!= this)
507 resolved
.EmitStatement (ec
);
509 base.EmitStatement (ec
);
512 public bool IsComplexInitializer
{
513 get { return !(source is Constant); }
516 public bool IsDefaultInitializer
{
518 Constant c
= source
as Constant
;
522 FieldExpr fe
= (FieldExpr
)target
;
523 return c
.IsDefaultInitializer (fe
.Type
);
528 class EventAddOrRemove
: ExpressionStatement
{
533 public EventAddOrRemove (Expression target
, Binary
.Operator op
, Expression source
, Location loc
)
535 this.target
= target
as EventExpr
;
537 this.source
= source
;
541 public override Expression
CreateExpressionTree (ResolveContext ec
)
543 return new SimpleAssign (target
, source
).CreateExpressionTree (ec
);
546 public override Expression
DoResolve (ResolveContext ec
)
548 if (op
!= Binary
.Operator
.Addition
&& op
!= Binary
.Operator
.Subtraction
)
549 target
.Error_AssignmentEventOnly ();
551 source
= source
.Resolve (ec
);
555 source
= Convert
.ImplicitConversionRequired (ec
, source
, target
.Type
, loc
);
559 eclass
= ExprClass
.Value
;
560 type
= TypeManager
.void_type
;
564 public override void Emit (EmitContext ec
)
566 if (RootContext
.EvalMode
)
569 throw new InternalErrorException ("don't know what to emit");
572 public override void EmitStatement (EmitContext ec
)
574 target
.EmitAddOrRemove (ec
, op
== Binary
.Operator
.Addition
, source
);
579 // This class is used for compound assignments.
581 class CompoundAssign
: Assign
{
583 Expression original_source
;
585 public CompoundAssign (Binary
.Operator op
, Expression target
, Expression source
)
586 : base (target
, source
, target
.Location
)
588 original_source
= source
;
592 public sealed class TargetExpression
: Expression
{
594 public TargetExpression (Expression child
)
597 this.loc
= child
.Location
;
600 public override Expression
CreateExpressionTree (ResolveContext ec
)
602 throw new NotSupportedException ("ET");
605 public override Expression
DoResolve (ResolveContext ec
)
607 child
= child
.Resolve (ec
);
611 eclass
= ExprClass
.Value
;
615 public override void Emit (EmitContext ec
)
621 public override Expression
DoResolve (ResolveContext ec
)
623 original_source
= original_source
.Resolve (ec
);
624 if (original_source
== null)
627 MemberAccess ma
= target
as MemberAccess
;
628 using (ec
.Set (ResolveContext
.Options
.CompoundAssignmentScope
)) {
629 target
= target
.Resolve (ec
);
635 if (target
is MethodGroupExpr
){
636 Error_CannotAssign (((MethodGroupExpr
)target
).Name
, target
.ExprClassName
);
640 if (target
is EventExpr
)
641 return new EventAddOrRemove (target
, op
, original_source
, loc
).DoResolve (ec
);
644 // Only now we can decouple the original source/target
645 // into a tree, to guarantee that we do not have side
648 source
= new Binary (op
, new TargetExpression (target
), original_source
, true);
650 // TODO: TargetExpression breaks MemberAccess composition
651 if (target
is DynamicMemberBinder
) {
652 Arguments targs
= ((DynamicMemberBinder
) target
).Arguments
;
653 source
= source
.Resolve (ec
);
655 Arguments args
= new Arguments (2);
656 args
.AddRange (targs
);
657 args
.Add (new Argument (source
));
658 source
= new DynamicMemberBinder (true, ma
.Name
, args
, loc
).Resolve (ec
);
660 // Handles possible event addition/subtraction
661 if (op
== Binary
.Operator
.Addition
|| op
== Binary
.Operator
.Subtraction
) {
662 args
= new Arguments (2);
663 args
.AddRange (targs
);
664 args
.Add (new Argument (original_source
));
665 string method_prefix
= op
== Binary
.Operator
.Addition
?
666 Event
.AEventAccessor
.AddPrefix
: Event
.AEventAccessor
.RemovePrefix
;
668 Expression invoke
= new DynamicInvocation (
669 new MemberAccess (original_source
, method_prefix
+ ma
.Name
, loc
), args
, loc
).Resolve (ec
);
671 args
= new Arguments (1);
672 args
.AddRange (targs
);
673 source
= new DynamicEventCompoundAssign (ma
.Name
, args
,
674 (ExpressionStatement
) source
, (ExpressionStatement
) invoke
, loc
).Resolve (ec
);
680 return base.DoResolve (ec
);
683 protected override Expression
ResolveConversions (ResolveContext ec
)
685 Type target_type
= target
.Type
;
688 // 1. the return type is implicitly convertible to the type of target
690 if (Convert
.ImplicitConversionExists (ec
, source
, target_type
)) {
691 source
= Convert
.ImplicitConversion (ec
, source
, target_type
, loc
);
696 // Otherwise, if the selected operator is a predefined operator
698 Binary b
= source
as Binary
;
701 // 2a. the operator is a shift operator
703 // 2b. the return type is explicitly convertible to the type of x, and
704 // y is implicitly convertible to the type of x
706 if ((b
.Oper
& Binary
.Operator
.ShiftMask
) != 0 ||
707 Convert
.ImplicitConversionExists (ec
, original_source
, target_type
)) {
708 source
= Convert
.ExplicitConversion (ec
, source
, target_type
, loc
);
713 original_source
.Error_ValueCannotBeConverted (ec
, loc
, target_type
, false);
717 protected override void CloneTo (CloneContext clonectx
, Expression t
)
719 CompoundAssign ctarget
= (CompoundAssign
) t
;
721 ctarget
.original_source
= ctarget
.source
= source
.Clone (clonectx
);
722 ctarget
.target
= target
.Clone (clonectx
);