2 // iterators.cs: Support for implementing iterators
5 // Miguel de Icaza (miguel@ximian.com)
6 // Marek Safar (marek.safar@gmail.com)
8 // Dual licensed under the terms of the MIT X11 or GNU GPL
9 // Copyright 2003 Ximian, Inc.
10 // Copyright 2003-2008 Novell, Inc.
11 // Copyright 2011 Xamarin Inc.
15 using System.Collections.Generic;
16 using Mono.CompilerServices.SymbolWriter;
19 using IKVM.Reflection.Emit;
21 using System.Reflection.Emit;
26 public abstract class YieldStatement<T> : ResumableStatement where T : StateMachineInitializer
28 protected Expression expr;
29 protected bool unwind_protect;
30 protected T machine_initializer;
32 ExceptionStatement inside_try_block;
34 protected YieldStatement (Expression expr, Location l)
40 public Expression Expr {
41 get { return this.expr; }
44 protected override void CloneTo (CloneContext clonectx, Statement t)
46 var target = (YieldStatement<T>) t;
47 target.expr = expr.Clone (clonectx);
50 protected override void DoEmit (EmitContext ec)
52 machine_initializer.InjectYield (ec, expr, resume_pc, unwind_protect, resume_point);
55 protected override bool DoFlowAnalysis (FlowAnalysisContext fc)
57 expr.FlowAnalysis (fc);
59 RegisterResumePoint ();
64 public override bool Resolve (BlockContext bc)
66 expr = expr.Resolve (bc);
70 machine_initializer = bc.CurrentAnonymousMethod as T;
71 inside_try_block = bc.CurrentTryBlock;
75 public void RegisterResumePoint ()
77 if (inside_try_block == null) {
78 resume_pc = machine_initializer.AddResumePoint (this);
80 resume_pc = inside_try_block.AddResumePoint (this, resume_pc, machine_initializer);
81 unwind_protect = true;
82 inside_try_block = null;
87 public class Yield : YieldStatement<Iterator>
89 public Yield (Expression expr, Location loc)
94 public static bool CheckContext (BlockContext bc, Location loc)
96 if (!bc.CurrentAnonymousMethod.IsIterator) {
97 bc.Report.Error (1621, loc,
98 "The yield statement cannot be used inside anonymous method blocks");
102 if (bc.HasSet (ResolveContext.Options.FinallyScope)) {
103 bc.Report.Error (1625, loc, "Cannot yield in the body of a finally clause");
110 public override bool Resolve (BlockContext bc)
112 if (!CheckContext (bc, loc))
115 if (bc.HasAny (ResolveContext.Options.TryWithCatchScope)) {
116 bc.Report.Error (1626, loc, "Cannot yield a value in the body of a try block with a catch clause");
119 if (bc.HasSet (ResolveContext.Options.CatchScope)) {
120 bc.Report.Error (1631, loc, "Cannot yield a value in the body of a catch clause");
123 if (!base.Resolve (bc))
126 var otype = bc.CurrentIterator.OriginalIteratorType;
127 if (expr.Type != otype) {
128 expr = Convert.ImplicitConversionRequired (bc, expr, otype, loc);
136 public override object Accept (StructuralVisitor visitor)
138 return visitor.Visit (this);
142 public class YieldBreak : ExitStatement
146 public YieldBreak (Location l)
151 protected override bool IsLocalExit {
157 protected override void CloneTo (CloneContext clonectx, Statement target)
159 throw new NotSupportedException ();
162 protected override bool DoResolve (BlockContext bc)
164 iterator = bc.CurrentIterator;
165 return Yield.CheckContext (bc, loc);
168 protected override void DoEmit (EmitContext ec)
170 iterator.EmitYieldBreak (ec, unwind_protect);
173 protected override bool DoFlowAnalysis (FlowAnalysisContext fc)
178 public override Reachability MarkReachable (Reachability rc)
180 base.MarkReachable (rc);
181 return Reachability.CreateUnreachable ();
184 public override object Accept (StructuralVisitor visitor)
186 return visitor.Visit (this);
190 public abstract class StateMachine : AnonymousMethodStorey
194 Running = -3, // Used only in CurrentPC, never stored into $PC
201 StateMachineMethod method;
204 protected StateMachine (ParametersBlock block, TypeDefinition parent, MemberBase host, TypeParameters tparams, string name, MemberKind kind)
205 : base (block, parent, host, tparams, name, kind)
207 OriginalTypeParameters = tparams;
212 public TypeParameters OriginalTypeParameters { get; private set; }
214 public StateMachineMethod StateMachineMethod {
228 public void AddEntryMethod (StateMachineMethod method)
230 if (this.method != null)
231 throw new InternalErrorException ();
233 this.method = method;
234 Members.Add (method);
237 protected override bool DoDefineMembers ()
239 pc_field = AddCompilerGeneratedField ("$PC", new TypeExpression (Compiler.BuiltinTypes.Int, Location));
241 return base.DoDefineMembers ();
244 protected override string GetVariableMangledName (LocalVariable local_info)
246 if (local_info.IsCompilerGenerated)
247 return base.GetVariableMangledName (local_info);
249 return "<" + local_info.Name + ">__" + local_name_idx++.ToString ("X");
253 class IteratorStorey : StateMachine
255 class GetEnumeratorMethod : StateMachineMethod
257 sealed class GetEnumeratorStatement : Statement
259 readonly IteratorStorey host;
260 readonly StateMachineMethod host_method;
262 Expression new_storey;
264 public GetEnumeratorStatement (IteratorStorey host, StateMachineMethod host_method)
267 this.host_method = host_method;
268 loc = host_method.Location;
271 protected override void CloneTo (CloneContext clonectx, Statement target)
273 throw new NotSupportedException ();
276 public override bool Resolve (BlockContext ec)
278 TypeExpression storey_type_expr = new TypeExpression (host.Definition, loc);
279 List<Expression> init = null;
280 if (host.hoisted_this != null) {
281 init = new List<Expression> (host.hoisted_params == null ? 1 : host.HoistedParameters.Count + 1);
282 HoistedThis ht = host.hoisted_this;
283 FieldExpr from = new FieldExpr (ht.Field, loc);
284 from.InstanceExpression = new CompilerGeneratedThis (ec.CurrentType, loc);
285 init.Add (new ElementInitializer (ht.Field.Name, from, loc));
288 if (host.hoisted_params != null) {
290 init = new List<Expression> (host.HoistedParameters.Count);
292 for (int i = 0; i < host.hoisted_params.Count; ++i) {
293 HoistedParameter hp = host.hoisted_params [i];
294 HoistedParameter hp_cp = host.hoisted_params_copy [i] ?? hp;
296 FieldExpr from = new FieldExpr (hp_cp.Field, loc);
297 from.InstanceExpression = new CompilerGeneratedThis (ec.CurrentType, loc);
299 init.Add (new ElementInitializer (hp.Field.Name, from, loc));
304 new_storey = new NewInitialize (storey_type_expr, null,
305 new CollectionOrObjectInitializers (init, loc), loc);
307 new_storey = new New (storey_type_expr, null, loc);
310 new_storey = new_storey.Resolve (ec);
311 if (new_storey != null)
312 new_storey = Convert.ImplicitConversionRequired (ec, new_storey, host_method.MemberType, loc);
317 protected override void DoEmit (EmitContext ec)
319 Label label_init = ec.DefineLabel ();
322 ec.Emit (OpCodes.Ldflda, host.PC.Spec);
323 ec.EmitInt ((int) State.Start);
324 ec.EmitInt ((int) State.Uninitialized);
326 var m = ec.Module.PredefinedMembers.InterlockedCompareExchange.Resolve (loc);
328 ec.Emit (OpCodes.Call, m);
330 ec.EmitInt ((int) State.Uninitialized);
331 ec.Emit (OpCodes.Bne_Un_S, label_init);
334 ec.Emit (OpCodes.Ret);
336 ec.MarkLabel (label_init);
338 new_storey.Emit (ec);
339 ec.Emit (OpCodes.Ret);
342 protected override bool DoFlowAnalysis (FlowAnalysisContext fc)
344 throw new NotImplementedException ();
347 public override Reachability MarkReachable (Reachability rc)
349 base.MarkReachable (rc);
350 return Reachability.CreateUnreachable ();
354 GetEnumeratorMethod (IteratorStorey host, FullNamedExpression returnType, MemberName name)
355 : base (host, null, returnType, Modifiers.DEBUGGER_HIDDEN, name, ToplevelBlock.Flags.CompilerGenerated | ToplevelBlock.Flags.NoFlowAnalysis)
359 public static GetEnumeratorMethod Create (IteratorStorey host, FullNamedExpression returnType, MemberName name)
361 return Create (host, returnType, name, null);
364 public static GetEnumeratorMethod Create (IteratorStorey host, FullNamedExpression returnType, MemberName name, Statement statement)
366 var m = new GetEnumeratorMethod (host, returnType, name);
367 var stmt = statement ?? new GetEnumeratorStatement (host, m);
368 m.block.AddStatement (stmt);
373 class DisposeMethod : StateMachineMethod
375 sealed class DisposeMethodStatement : Statement
379 public DisposeMethodStatement (Iterator iterator)
381 this.iterator = iterator;
382 this.loc = iterator.Location;
385 protected override void CloneTo (CloneContext clonectx, Statement target)
387 throw new NotSupportedException ();
390 public override bool Resolve (BlockContext ec)
395 protected override void DoEmit (EmitContext ec)
397 ec.CurrentAnonymousMethod = iterator;
398 iterator.EmitDispose (ec);
401 protected override bool DoFlowAnalysis (FlowAnalysisContext fc)
403 throw new NotImplementedException ();
407 public DisposeMethod (IteratorStorey host)
408 : base (host, null, new TypeExpression (host.Compiler.BuiltinTypes.Void, host.Location), Modifiers.PUBLIC | Modifiers.DEBUGGER_HIDDEN,
409 new MemberName ("Dispose", host.Location), ToplevelBlock.Flags.CompilerGenerated | ToplevelBlock.Flags.NoFlowAnalysis)
411 host.Members.Add (this);
413 Block.AddStatement (new DisposeMethodStatement (host.Iterator));
418 // Uses Method as method info
420 class DynamicMethodGroupExpr : MethodGroupExpr
422 readonly Method method;
424 public DynamicMethodGroupExpr (Method method, Location loc)
425 : base ((IList<MemberSpec>) null, null, loc)
427 this.method = method;
428 eclass = ExprClass.Unresolved;
431 protected override Expression DoResolve (ResolveContext ec)
433 Methods = new List<MemberSpec> (1) { method.Spec };
434 type = method.Parent.Definition;
435 InstanceExpression = new CompilerGeneratedThis (type, Location);
436 return base.DoResolve (ec);
440 class DynamicFieldExpr : FieldExpr
442 readonly Field field;
444 public DynamicFieldExpr (Field field, Location loc)
450 protected override Expression DoResolve (ResolveContext ec)
453 type = spec.MemberType;
454 InstanceExpression = new CompilerGeneratedThis (type, Location);
455 return base.DoResolve (ec);
459 public readonly Iterator Iterator;
461 List<HoistedParameter> hoisted_params_copy;
463 TypeExpr iterator_type_expr;
465 Field disposing_field;
467 TypeSpec generic_enumerator_type;
468 TypeSpec generic_enumerable_type;
470 public IteratorStorey (Iterator iterator)
471 : base (iterator.Container.ParametersBlock, iterator.Host,
472 iterator.OriginalMethod as MemberBase, iterator.OriginalMethod.CurrentTypeParameters, "Iterator", MemberKind.Class)
474 this.Iterator = iterator;
477 public Field CurrentField {
479 return current_field;
483 public Field DisposingField {
485 return disposing_field;
489 public IList<HoistedParameter> HoistedParameters {
490 get { return hoisted_params; }
493 protected override Constructor DefineDefaultConstructor (bool is_static)
495 var ctor = base.DefineDefaultConstructor (is_static);
496 ctor.ModFlags |= Modifiers.DEBUGGER_HIDDEN;
500 protected override TypeSpec[] ResolveBaseTypes (out FullNamedExpression base_class)
502 var mtype = Iterator.OriginalIteratorType;
504 mtype = Mutator.Mutate (mtype);
506 iterator_type_expr = new TypeExpression (mtype, Location);
508 var ifaces = new List<TypeSpec> (5);
509 if (Iterator.IsEnumerable) {
510 ifaces.Add (Compiler.BuiltinTypes.IEnumerable);
512 if (Module.PredefinedTypes.IEnumerableGeneric.Define ()) {
513 generic_enumerable_type = Module.PredefinedTypes.IEnumerableGeneric.TypeSpec.MakeGenericType (Module, new[] { mtype });
514 ifaces.Add (generic_enumerable_type);
518 ifaces.Add (Compiler.BuiltinTypes.IEnumerator);
519 ifaces.Add (Compiler.BuiltinTypes.IDisposable);
521 var ienumerator_generic = Module.PredefinedTypes.IEnumeratorGeneric;
522 if (ienumerator_generic.Define ()) {
523 generic_enumerator_type = ienumerator_generic.TypeSpec.MakeGenericType (Module, new [] { mtype });
524 ifaces.Add (generic_enumerator_type);
529 base_type = Compiler.BuiltinTypes.Object;
530 return ifaces.ToArray ();
533 protected override bool DoDefineMembers ()
535 current_field = AddCompilerGeneratedField ("$current", iterator_type_expr);
536 disposing_field = AddCompilerGeneratedField ("$disposing", new TypeExpression (Compiler.BuiltinTypes.Bool, Location));
538 if (Iterator.IsEnumerable && hoisted_params != null) {
540 // Iterators are independent, each GetEnumerator call has to
541 // create same enumerator therefore we have to keep original values
542 // around for re-initialization
544 hoisted_params_copy = new List<HoistedParameter> (hoisted_params.Count);
545 foreach (HoistedParameter hp in hoisted_params) {
548 // Don't create field copy for unmodified captured parameters
550 HoistedParameter hp_copy;
552 hp_copy = new HoistedParameter (hp, "<$>" + hp.Field.Name);
557 hoisted_params_copy.Add (hp_copy);
561 if (generic_enumerator_type != null)
562 Define_Current (true);
564 Define_Current (false);
565 new DisposeMethod (this);
568 if (Iterator.IsEnumerable) {
569 FullNamedExpression explicit_iface = new TypeExpression (Compiler.BuiltinTypes.IEnumerable, Location);
570 var name = new MemberName ("GetEnumerator", null, explicit_iface, Location.Null);
572 if (generic_enumerator_type != null) {
573 explicit_iface = new TypeExpression (generic_enumerable_type, Location);
574 var gname = new MemberName ("GetEnumerator", null, explicit_iface, Location.Null);
575 Method gget_enumerator = GetEnumeratorMethod.Create (this, new TypeExpression (generic_enumerator_type, Location), gname);
578 // Just call generic GetEnumerator implementation
580 var stmt = new Return (new Invocation (new DynamicMethodGroupExpr (gget_enumerator, Location), null), Location);
581 Method get_enumerator = GetEnumeratorMethod.Create (this, new TypeExpression (Compiler.BuiltinTypes.IEnumerator, Location), name, stmt);
583 Members.Add (get_enumerator);
584 Members.Add (gget_enumerator);
586 Members.Add (GetEnumeratorMethod.Create (this, new TypeExpression (Compiler.BuiltinTypes.IEnumerator, Location), name));
590 return base.DoDefineMembers ();
593 void Define_Current (bool is_generic)
596 FullNamedExpression explicit_iface;
599 explicit_iface = new TypeExpression (generic_enumerator_type, Location);
600 type = iterator_type_expr;
602 explicit_iface = new TypeExpression (Module.Compiler.BuiltinTypes.IEnumerator, Location);
603 type = new TypeExpression (Compiler.BuiltinTypes.Object, Location);
606 var name = new MemberName ("Current", null, explicit_iface, Location);
608 ToplevelBlock get_block = new ToplevelBlock (Compiler, ParametersCompiled.EmptyReadOnlyParameters, Location,
609 Block.Flags.CompilerGenerated | Block.Flags.NoFlowAnalysis);
610 get_block.AddStatement (new Return (new DynamicFieldExpr (CurrentField, Location), Location));
612 Property current = new Property (this, type, Modifiers.DEBUGGER_HIDDEN | Modifiers.COMPILER_GENERATED, name, null);
613 current.Get = new Property.GetMethod (current, Modifiers.COMPILER_GENERATED, null, Location);
614 current.Get.Block = get_block;
616 Members.Add (current);
621 Method reset = new Method (
622 this, new TypeExpression (Compiler.BuiltinTypes.Void, Location),
623 Modifiers.PUBLIC | Modifiers.DEBUGGER_HIDDEN | Modifiers.COMPILER_GENERATED,
624 new MemberName ("Reset", Location),
625 ParametersCompiled.EmptyReadOnlyParameters, null);
628 reset.Block = new ToplevelBlock (Compiler, reset.ParameterInfo, Location,
629 Block.Flags.CompilerGenerated | Block.Flags.NoFlowAnalysis);
631 TypeSpec ex_type = Module.PredefinedTypes.NotSupportedException.Resolve ();
635 reset.Block.AddStatement (new Throw (new New (new TypeExpression (ex_type, Location), null, Location), Location));
638 protected override void EmitHoistedParameters (EmitContext ec, List<HoistedParameter> hoisted)
640 base.EmitHoistedParameters (ec, hoisted);
641 if (hoisted_params_copy != null)
642 base.EmitHoistedParameters (ec, hoisted_params_copy);
646 public class StateMachineMethod : Method
648 readonly StateMachineInitializer expr;
650 public StateMachineMethod (StateMachine host, StateMachineInitializer expr, FullNamedExpression returnType,
651 Modifiers mod, MemberName name, ToplevelBlock.Flags blockFlags)
652 : base (host, returnType, mod | Modifiers.COMPILER_GENERATED,
653 name, ParametersCompiled.EmptyReadOnlyParameters, null)
656 Block = new ToplevelBlock (host.Compiler, ParametersCompiled.EmptyReadOnlyParameters, Location.Null, blockFlags);
659 public override EmitContext CreateEmitContext (ILGenerator ig, SourceMethodBuilder sourceMethod)
661 EmitContext ec = new EmitContext (this, ig, MemberType, sourceMethod);
662 ec.CurrentAnonymousMethod = expr;
664 if (expr is AsyncInitializer)
665 ec.With (BuilderContext.Options.AsyncBody, true);
671 public abstract class StateMachineInitializer : AnonymousExpression
673 sealed class MoveNextBodyStatement : Statement
675 readonly StateMachineInitializer state_machine;
677 public MoveNextBodyStatement (StateMachineInitializer stateMachine)
679 this.state_machine = stateMachine;
680 this.loc = stateMachine.Location;
683 protected override void CloneTo (CloneContext clonectx, Statement target)
685 throw new NotSupportedException ();
688 public override bool Resolve (BlockContext ec)
693 protected override void DoEmit (EmitContext ec)
695 state_machine.EmitMoveNext (ec);
698 public override void Emit (EmitContext ec)
700 // Don't create sequence point
704 protected override bool DoFlowAnalysis (FlowAnalysisContext fc)
706 return state_machine.ReturnType.Kind != MemberKind.Void;
709 public override Reachability MarkReachable (Reachability rc)
711 base.MarkReachable (rc);
713 if (state_machine.ReturnType.Kind != MemberKind.Void)
714 rc = Reachability.CreateUnreachable ();
720 public readonly TypeDefinition Host;
721 protected StateMachine storey;
724 // The state as we generate the machine
727 protected Label move_next_error;
728 LocalBuilder skip_finally;
729 protected LocalBuilder current_pc;
730 protected List<ResumableStatement> resume_points;
732 protected StateMachineInitializer (ParametersBlock block, TypeDefinition host, TypeSpec returnType)
733 : base (block, returnType, block.StartLocation)
740 public Label BodyEnd { get; set; }
742 public LocalBuilder CurrentPC
749 public LocalBuilder SkipFinally {
755 public override AnonymousMethodStorey Storey {
763 public int AddResumePoint (ResumableStatement stmt)
765 if (resume_points == null)
766 resume_points = new List<ResumableStatement> ();
768 resume_points.Add (stmt);
769 return resume_points.Count;
772 public override Expression CreateExpressionTree (ResolveContext ec)
774 throw new NotSupportedException ("ET");
777 protected virtual BlockContext CreateBlockContext (BlockContext bc)
779 var ctx = new BlockContext (bc, block, bc.ReturnType);
780 ctx.CurrentAnonymousMethod = this;
782 ctx.AssignmentInfoOffset = bc.AssignmentInfoOffset;
783 ctx.EnclosingLoop = bc.EnclosingLoop;
784 ctx.EnclosingLoopOrSwitch = bc.EnclosingLoopOrSwitch;
785 ctx.Switch = bc.Switch;
790 protected override Expression DoResolve (ResolveContext rc)
792 var bc = (BlockContext) rc;
793 var ctx = CreateBlockContext (bc);
797 if (!rc.IsInProbingMode) {
798 var move_next = new StateMachineMethod (storey, this, new TypeExpression (ReturnType, loc), Modifiers.PUBLIC, new MemberName ("MoveNext", loc), 0);
799 move_next.Block.AddStatement (new MoveNextBodyStatement (this));
800 storey.AddEntryMethod (move_next);
803 bc.AssignmentInfoOffset = ctx.AssignmentInfoOffset;
804 eclass = ExprClass.Value;
808 public override void Emit (EmitContext ec)
811 // Load state machine instance
813 storey.Instance.Emit (ec);
816 void EmitMoveNext_NoResumePoints (EmitContext ec)
819 ec.Emit (OpCodes.Ldfld, storey.PC.Spec);
822 ec.EmitInt ((int) IteratorStorey.State.After);
823 ec.Emit (OpCodes.Stfld, storey.PC.Spec);
825 // We only care if the PC is zero (start executing) or non-zero (don't do anything)
826 ec.Emit (OpCodes.Brtrue, move_next_error);
828 BodyEnd = ec.DefineLabel ();
830 block.EmitEmbedded (ec);
832 ec.MarkLabel (BodyEnd);
834 EmitMoveNextEpilogue (ec);
836 ec.MarkLabel (move_next_error);
838 if (ReturnType.Kind != MemberKind.Void) {
840 ec.Emit (OpCodes.Ret);
844 void EmitMoveNext (EmitContext ec)
846 move_next_ok = ec.DefineLabel ();
847 move_next_error = ec.DefineLabel ();
849 if (resume_points == null) {
850 EmitMoveNext_NoResumePoints (ec);
854 current_pc = ec.GetTemporaryLocal (ec.BuiltinTypes.UInt);
856 ec.Emit (OpCodes.Ldfld, storey.PC.Spec);
857 ec.Emit (OpCodes.Stloc, current_pc);
859 // We're actually in state 'running', but this is as good a PC value as any if there's an abnormal exit
861 ec.EmitInt ((int) IteratorStorey.State.After);
862 ec.Emit (OpCodes.Stfld, storey.PC.Spec);
864 Label[] labels = new Label[1 + resume_points.Count];
865 labels[0] = ec.DefineLabel ();
867 bool need_skip_finally = false;
868 for (int i = 0; i < resume_points.Count; ++i) {
869 ResumableStatement s = resume_points[i];
870 need_skip_finally |= s is ExceptionStatement;
871 labels[i + 1] = s.PrepareForEmit (ec);
874 if (need_skip_finally) {
875 skip_finally = ec.GetTemporaryLocal (ec.BuiltinTypes.Bool);
877 ec.Emit (OpCodes.Stloc, skip_finally);
880 var async_init = this as AsyncInitializer;
881 if (async_init != null)
882 ec.BeginExceptionBlock ();
884 ec.Emit (OpCodes.Ldloc, current_pc);
885 ec.Emit (OpCodes.Switch, labels);
887 ec.Emit (async_init != null ? OpCodes.Leave : OpCodes.Br, move_next_error);
889 ec.MarkLabel (labels[0]);
891 BodyEnd = ec.DefineLabel ();
893 block.EmitEmbedded (ec);
895 ec.MarkLabel (BodyEnd);
897 if (async_init != null) {
898 var catch_value = LocalVariable.CreateCompilerGenerated (ec.Module.Compiler.BuiltinTypes.Exception, block, Location);
900 ec.BeginCatchBlock (catch_value.Type);
901 catch_value.EmitAssign (ec);
904 ec.EmitInt ((int) IteratorStorey.State.After);
905 ec.Emit (OpCodes.Stfld, storey.PC.Spec);
907 ((AsyncTaskStorey) async_init.Storey).EmitSetException (ec, new LocalVariableReference (catch_value, Location));
909 ec.Emit (OpCodes.Leave, move_next_ok);
910 ec.EndExceptionBlock ();
913 ec.Mark (Block.Original.EndLocation);
915 ec.EmitInt ((int) IteratorStorey.State.After);
916 ec.Emit (OpCodes.Stfld, storey.PC.Spec);
918 EmitMoveNextEpilogue (ec);
920 ec.MarkLabel (move_next_error);
922 if (ReturnType.Kind != MemberKind.Void) {
924 ec.Emit (OpCodes.Ret);
927 ec.MarkLabel (move_next_ok);
929 if (ReturnType.Kind != MemberKind.Void) {
931 ec.Emit (OpCodes.Ret);
935 protected virtual void EmitMoveNextEpilogue (EmitContext ec)
939 public void EmitLeave (EmitContext ec, bool unwind_protect)
942 ec.Emit (unwind_protect ? OpCodes.Leave : OpCodes.Br, move_next_ok);
946 // Called back from YieldStatement
948 public virtual void InjectYield (EmitContext ec, Expression expr, int resume_pc, bool unwind_protect, Label resume_point)
951 // Guard against being disposed meantime
953 Label disposed = ec.DefineLabel ();
954 var iterator = storey as IteratorStorey;
955 if (iterator != null) {
957 ec.Emit (OpCodes.Ldfld, iterator.DisposingField.Spec);
958 ec.Emit (OpCodes.Brtrue_S, disposed);
962 // store resume program-counter
965 ec.EmitInt (resume_pc);
966 ec.Emit (OpCodes.Stfld, storey.PC.Spec);
968 if (iterator != null) {
969 ec.MarkLabel (disposed);
972 // mark finally blocks as disabled
973 if (unwind_protect && skip_finally != null) {
975 ec.Emit (OpCodes.Stloc, skip_finally);
979 public void SetStateMachine (StateMachine stateMachine)
981 this.storey = stateMachine;
986 // Iterators are implemented as state machine blocks
988 public class Iterator : StateMachineInitializer
990 sealed class TryFinallyBlockProxyStatement : Statement
992 TryFinallyBlock block;
995 public TryFinallyBlockProxyStatement (Iterator iterator, TryFinallyBlock block)
997 this.iterator = iterator;
1001 protected override void CloneTo (CloneContext clonectx, Statement target)
1003 throw new NotSupportedException ();
1006 protected override bool DoFlowAnalysis (FlowAnalysisContext fc)
1008 throw new NotSupportedException ();
1011 protected override void DoEmit (EmitContext ec)
1014 // Restore redirection for any captured variables
1016 ec.CurrentAnonymousMethod = iterator;
1018 using (ec.With (BuilderContext.Options.OmitDebugInfo, !ec.HasMethodSymbolBuilder)) {
1019 block.EmitFinallyBody (ec);
1024 public readonly IMethodData OriginalMethod;
1025 public readonly bool IsEnumerable;
1026 public readonly TypeSpec OriginalIteratorType;
1027 int finally_hosts_counter;
1029 public Iterator (ParametersBlock block, IMethodData method, TypeDefinition host, TypeSpec iterator_type, bool is_enumerable)
1030 : base (block, host, host.Compiler.BuiltinTypes.Bool)
1032 this.OriginalMethod = method;
1033 this.OriginalIteratorType = iterator_type;
1034 this.IsEnumerable = is_enumerable;
1035 this.type = method.ReturnType;
1040 public ToplevelBlock Container {
1041 get { return OriginalMethod.Block; }
1044 public override string ContainerType {
1045 get { return "iterator"; }
1048 public override bool IsIterator {
1049 get { return true; }
1054 public Method CreateFinallyHost (TryFinallyBlock block)
1056 var method = new Method (storey, new TypeExpression (storey.Compiler.BuiltinTypes.Void, loc),
1057 Modifiers.COMPILER_GENERATED, new MemberName (CompilerGeneratedContainer.MakeName (null, null, "Finally", finally_hosts_counter++), loc),
1058 ParametersCompiled.EmptyReadOnlyParameters, null);
1060 method.Block = new ToplevelBlock (method.Compiler, method.ParameterInfo, loc,
1061 ToplevelBlock.Flags.CompilerGenerated | ToplevelBlock.Flags.NoFlowAnalysis);
1062 method.Block.AddStatement (new TryFinallyBlockProxyStatement (this, block));
1064 // Cannot it add to storey because it'd be emitted before nested
1065 // anonoymous methods which could capture shared variable
1070 public void EmitYieldBreak (EmitContext ec, bool unwind_protect)
1072 ec.Emit (unwind_protect ? OpCodes.Leave : OpCodes.Br, move_next_error);
1075 public override string GetSignatureForError ()
1077 return OriginalMethod.GetSignatureForError ();
1080 public override void Emit (EmitContext ec)
1083 // Load Iterator storey instance
1085 storey.Instance.Emit (ec);
1088 // Initialize iterator PC when it's unitialized
1091 ec.Emit (OpCodes.Dup);
1092 ec.EmitInt ((int)IteratorStorey.State.Uninitialized);
1094 var field = storey.PC.Spec;
1095 if (storey.MemberName.IsGeneric) {
1096 field = MemberCache.GetMember (Storey.Instance.Type, field);
1099 ec.Emit (OpCodes.Stfld, field);
1103 public void EmitDispose (EmitContext ec)
1105 if (resume_points == null)
1108 Label end = ec.DefineLabel ();
1110 Label[] labels = null;
1111 for (int i = 0; i < resume_points.Count; ++i) {
1112 ResumableStatement s = resume_points[i];
1113 Label ret = s.PrepareForDispose (ec, end);
1114 if (ret.Equals (end) && labels == null)
1116 if (labels == null) {
1117 labels = new Label[resume_points.Count + 1];
1118 for (int j = 0; j <= i; ++j)
1122 labels[i + 1] = ret;
1125 if (labels != null) {
1126 current_pc = ec.GetTemporaryLocal (ec.BuiltinTypes.UInt);
1128 ec.Emit (OpCodes.Ldfld, storey.PC.Spec);
1129 ec.Emit (OpCodes.Stloc, current_pc);
1134 ec.Emit (OpCodes.Stfld, ((IteratorStorey) storey).DisposingField.Spec);
1137 ec.EmitInt ((int) IteratorStorey.State.After);
1138 ec.Emit (OpCodes.Stfld, storey.PC.Spec);
1140 if (labels != null) {
1141 //SymbolWriter.StartIteratorDispatcher (ec.ig);
1142 ec.Emit (OpCodes.Ldloc, current_pc);
1143 ec.Emit (OpCodes.Switch, labels);
1144 //SymbolWriter.EndIteratorDispatcher (ec.ig);
1146 foreach (ResumableStatement s in resume_points)
1147 s.EmitForDispose (ec, current_pc, end, true);
1153 public override void EmitStatement (EmitContext ec)
1155 throw new NotImplementedException ();
1158 public override void InjectYield (EmitContext ec, Expression expr, int resume_pc, bool unwind_protect, Label resume_point)
1160 // Store the new value into current
1161 var fe = new FieldExpr (((IteratorStorey) storey).CurrentField, loc);
1162 fe.InstanceExpression = new CompilerGeneratedThis (storey.CurrentType, loc);
1163 fe.EmitAssign (ec, expr, false, false);
1165 base.InjectYield (ec, expr, resume_pc, unwind_protect, resume_point);
1167 EmitLeave (ec, unwind_protect);
1169 ec.MarkLabel (resume_point);
1172 public static void CreateIterator (IMethodData method, TypeDefinition parent, Modifiers modifiers)
1175 TypeSpec iterator_type;
1177 TypeSpec ret = method.ReturnType;
1181 if (!CheckType (ret, parent, out iterator_type, out is_enumerable)) {
1182 parent.Compiler.Report.Error (1624, method.Location,
1183 "The body of `{0}' cannot be an iterator block " +
1184 "because `{1}' is not an iterator interface type",
1185 method.GetSignatureForError (),
1186 ret.GetSignatureForError ());
1190 ParametersCompiled parameters = method.ParameterInfo;
1191 for (int i = 0; i < parameters.Count; i++) {
1192 Parameter p = parameters [i];
1193 Parameter.Modifier mod = p.ModFlags;
1194 if ((mod & Parameter.Modifier.RefOutMask) != 0) {
1195 parent.Compiler.Report.Error (1623, p.Location,
1196 "Iterators cannot have ref or out parameters");
1200 if (p is ArglistParameter) {
1201 parent.Compiler.Report.Error (1636, method.Location,
1202 "__arglist is not allowed in parameter list of iterators");
1206 if (parameters.Types [i].IsPointer) {
1207 parent.Compiler.Report.Error (1637, p.Location,
1208 "Iterators cannot have unsafe parameters or yield types");
1213 if ((modifiers & Modifiers.UNSAFE) != 0) {
1214 parent.Compiler.Report.Error (1629, method.Location, "Unsafe code may not appear in iterators");
1217 method.Block = method.Block.ConvertToIterator (method, parent, iterator_type, is_enumerable);
1220 static bool CheckType (TypeSpec ret, TypeContainer parent, out TypeSpec original_iterator_type, out bool is_enumerable)
1222 original_iterator_type = null;
1223 is_enumerable = false;
1225 if (ret.BuiltinType == BuiltinTypeSpec.Type.IEnumerable) {
1226 original_iterator_type = parent.Compiler.BuiltinTypes.Object;
1227 is_enumerable = true;
1230 if (ret.BuiltinType == BuiltinTypeSpec.Type.IEnumerator) {
1231 original_iterator_type = parent.Compiler.BuiltinTypes.Object;
1232 is_enumerable = false;
1236 InflatedTypeSpec inflated = ret as InflatedTypeSpec;
1237 if (inflated == null)
1240 var member_definition = inflated.MemberDefinition;
1241 PredefinedType ptype = parent.Module.PredefinedTypes.IEnumerableGeneric;
1243 if (ptype.Define () && ptype.TypeSpec.MemberDefinition == member_definition) {
1244 original_iterator_type = inflated.TypeArguments[0];
1245 is_enumerable = true;
1249 ptype = parent.Module.PredefinedTypes.IEnumeratorGeneric;
1250 if (ptype.Define () && ptype.TypeSpec.MemberDefinition == member_definition) {
1251 original_iterator_type = inflated.TypeArguments[0];
1252 is_enumerable = false;