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)
211 public StateMachineMethod StateMachineMethod {
225 public void AddEntryMethod (StateMachineMethod method)
227 if (this.method != null)
228 throw new InternalErrorException ();
230 this.method = method;
231 Members.Add (method);
234 protected override bool DoDefineMembers ()
236 pc_field = AddCompilerGeneratedField ("$PC", new TypeExpression (Compiler.BuiltinTypes.Int, Location));
238 return base.DoDefineMembers ();
241 protected override string GetVariableMangledName (LocalVariable local_info)
243 if (local_info.IsCompilerGenerated)
244 return base.GetVariableMangledName (local_info);
246 return "<" + local_info.Name + ">__" + local_name_idx++.ToString ("X");
250 class IteratorStorey : StateMachine
252 class GetEnumeratorMethod : StateMachineMethod
254 sealed class GetEnumeratorStatement : Statement
256 readonly IteratorStorey host;
257 readonly StateMachineMethod host_method;
259 Expression new_storey;
261 public GetEnumeratorStatement (IteratorStorey host, StateMachineMethod host_method)
264 this.host_method = host_method;
265 loc = host_method.Location;
268 protected override void CloneTo (CloneContext clonectx, Statement target)
270 throw new NotSupportedException ();
273 public override bool Resolve (BlockContext ec)
275 TypeExpression storey_type_expr = new TypeExpression (host.Definition, loc);
276 List<Expression> init = null;
277 if (host.hoisted_this != null) {
278 init = new List<Expression> (host.hoisted_params == null ? 1 : host.HoistedParameters.Count + 1);
279 HoistedThis ht = host.hoisted_this;
280 FieldExpr from = new FieldExpr (ht.Field, loc);
281 from.InstanceExpression = new CompilerGeneratedThis (ec.CurrentType, loc);
282 init.Add (new ElementInitializer (ht.Field.Name, from, loc));
285 if (host.hoisted_params != null) {
287 init = new List<Expression> (host.HoistedParameters.Count);
289 for (int i = 0; i < host.hoisted_params.Count; ++i) {
290 HoistedParameter hp = host.hoisted_params [i];
291 HoistedParameter hp_cp = host.hoisted_params_copy [i] ?? hp;
293 FieldExpr from = new FieldExpr (hp_cp.Field, loc);
294 from.InstanceExpression = new CompilerGeneratedThis (ec.CurrentType, loc);
296 init.Add (new ElementInitializer (hp.Field.Name, from, loc));
301 new_storey = new NewInitialize (storey_type_expr, null,
302 new CollectionOrObjectInitializers (init, loc), loc);
304 new_storey = new New (storey_type_expr, null, loc);
307 new_storey = new_storey.Resolve (ec);
308 if (new_storey != null)
309 new_storey = Convert.ImplicitConversionRequired (ec, new_storey, host_method.MemberType, loc);
314 protected override void DoEmit (EmitContext ec)
316 Label label_init = ec.DefineLabel ();
319 ec.Emit (OpCodes.Ldflda, host.PC.Spec);
320 ec.EmitInt ((int) State.Start);
321 ec.EmitInt ((int) State.Uninitialized);
323 var m = ec.Module.PredefinedMembers.InterlockedCompareExchange.Resolve (loc);
325 ec.Emit (OpCodes.Call, m);
327 ec.EmitInt ((int) State.Uninitialized);
328 ec.Emit (OpCodes.Bne_Un_S, label_init);
331 ec.Emit (OpCodes.Ret);
333 ec.MarkLabel (label_init);
335 new_storey.Emit (ec);
336 ec.Emit (OpCodes.Ret);
339 protected override bool DoFlowAnalysis (FlowAnalysisContext fc)
341 throw new NotImplementedException ();
344 public override Reachability MarkReachable (Reachability rc)
346 base.MarkReachable (rc);
347 return Reachability.CreateUnreachable ();
351 GetEnumeratorMethod (IteratorStorey host, FullNamedExpression returnType, MemberName name)
352 : base (host, null, returnType, Modifiers.DEBUGGER_HIDDEN, name, ToplevelBlock.Flags.CompilerGenerated | ToplevelBlock.Flags.NoFlowAnalysis)
356 public static GetEnumeratorMethod Create (IteratorStorey host, FullNamedExpression returnType, MemberName name)
358 return Create (host, returnType, name, null);
361 public static GetEnumeratorMethod Create (IteratorStorey host, FullNamedExpression returnType, MemberName name, Statement statement)
363 var m = new GetEnumeratorMethod (host, returnType, name);
364 var stmt = statement ?? new GetEnumeratorStatement (host, m);
365 m.block.AddStatement (stmt);
370 class DisposeMethod : StateMachineMethod
372 sealed class DisposeMethodStatement : Statement
376 public DisposeMethodStatement (Iterator iterator)
378 this.iterator = iterator;
379 this.loc = iterator.Location;
382 protected override void CloneTo (CloneContext clonectx, Statement target)
384 throw new NotSupportedException ();
387 public override bool Resolve (BlockContext ec)
392 protected override void DoEmit (EmitContext ec)
394 ec.CurrentAnonymousMethod = iterator;
395 iterator.EmitDispose (ec);
398 protected override bool DoFlowAnalysis (FlowAnalysisContext fc)
400 throw new NotImplementedException ();
404 public DisposeMethod (IteratorStorey host)
405 : base (host, null, new TypeExpression (host.Compiler.BuiltinTypes.Void, host.Location), Modifiers.PUBLIC | Modifiers.DEBUGGER_HIDDEN,
406 new MemberName ("Dispose", host.Location), ToplevelBlock.Flags.CompilerGenerated | ToplevelBlock.Flags.NoFlowAnalysis)
408 host.Members.Add (this);
410 Block.AddStatement (new DisposeMethodStatement (host.Iterator));
415 // Uses Method as method info
417 class DynamicMethodGroupExpr : MethodGroupExpr
419 readonly Method method;
421 public DynamicMethodGroupExpr (Method method, Location loc)
422 : base ((IList<MemberSpec>) null, null, loc)
424 this.method = method;
425 eclass = ExprClass.Unresolved;
428 protected override Expression DoResolve (ResolveContext ec)
430 Methods = new List<MemberSpec> (1) { method.Spec };
431 type = method.Parent.Definition;
432 InstanceExpression = new CompilerGeneratedThis (type, Location);
433 return base.DoResolve (ec);
437 class DynamicFieldExpr : FieldExpr
439 readonly Field field;
441 public DynamicFieldExpr (Field field, Location loc)
447 protected override Expression DoResolve (ResolveContext ec)
450 type = spec.MemberType;
451 InstanceExpression = new CompilerGeneratedThis (type, Location);
452 return base.DoResolve (ec);
456 public readonly Iterator Iterator;
458 List<HoistedParameter> hoisted_params_copy;
460 TypeExpr iterator_type_expr;
462 Field disposing_field;
464 TypeSpec generic_enumerator_type;
465 TypeSpec generic_enumerable_type;
467 public IteratorStorey (Iterator iterator)
468 : base (iterator.Container.ParametersBlock, iterator.Host,
469 iterator.OriginalMethod as MemberBase, iterator.OriginalMethod.CurrentTypeParameters, "Iterator", MemberKind.Class)
471 this.Iterator = iterator;
474 public Field CurrentField {
476 return current_field;
480 public Field DisposingField {
482 return disposing_field;
486 public IList<HoistedParameter> HoistedParameters {
487 get { return hoisted_params; }
490 protected override Constructor DefineDefaultConstructor (bool is_static)
492 var ctor = base.DefineDefaultConstructor (is_static);
493 ctor.ModFlags |= Modifiers.DEBUGGER_HIDDEN;
497 protected override TypeSpec[] ResolveBaseTypes (out FullNamedExpression base_class)
499 var mtype = Iterator.OriginalIteratorType;
501 mtype = Mutator.Mutate (mtype);
503 iterator_type_expr = new TypeExpression (mtype, Location);
505 var ifaces = new List<TypeSpec> (5);
506 if (Iterator.IsEnumerable) {
507 ifaces.Add (Compiler.BuiltinTypes.IEnumerable);
509 if (Module.PredefinedTypes.IEnumerableGeneric.Define ()) {
510 generic_enumerable_type = Module.PredefinedTypes.IEnumerableGeneric.TypeSpec.MakeGenericType (Module, new[] { mtype });
511 ifaces.Add (generic_enumerable_type);
515 ifaces.Add (Compiler.BuiltinTypes.IEnumerator);
516 ifaces.Add (Compiler.BuiltinTypes.IDisposable);
518 var ienumerator_generic = Module.PredefinedTypes.IEnumeratorGeneric;
519 if (ienumerator_generic.Define ()) {
520 generic_enumerator_type = ienumerator_generic.TypeSpec.MakeGenericType (Module, new [] { mtype });
521 ifaces.Add (generic_enumerator_type);
526 base_type = Compiler.BuiltinTypes.Object;
527 return ifaces.ToArray ();
530 protected override bool DoDefineMembers ()
532 current_field = AddCompilerGeneratedField ("$current", iterator_type_expr);
533 disposing_field = AddCompilerGeneratedField ("$disposing", new TypeExpression (Compiler.BuiltinTypes.Bool, Location));
535 if (Iterator.IsEnumerable && hoisted_params != null) {
537 // Iterators are independent, each GetEnumerator call has to
538 // create same enumerator therefore we have to keep original values
539 // around for re-initialization
541 hoisted_params_copy = new List<HoistedParameter> (hoisted_params.Count);
542 foreach (HoistedParameter hp in hoisted_params) {
545 // Don't create field copy for unmodified captured parameters
547 HoistedParameter hp_copy;
549 hp_copy = new HoistedParameter (hp, "<$>" + hp.Field.Name);
554 hoisted_params_copy.Add (hp_copy);
558 if (generic_enumerator_type != null)
559 Define_Current (true);
561 Define_Current (false);
562 new DisposeMethod (this);
565 if (Iterator.IsEnumerable) {
566 FullNamedExpression explicit_iface = new TypeExpression (Compiler.BuiltinTypes.IEnumerable, Location);
567 var name = new MemberName ("GetEnumerator", null, explicit_iface, Location.Null);
569 if (generic_enumerator_type != null) {
570 explicit_iface = new TypeExpression (generic_enumerable_type, Location);
571 var gname = new MemberName ("GetEnumerator", null, explicit_iface, Location.Null);
572 Method gget_enumerator = GetEnumeratorMethod.Create (this, new TypeExpression (generic_enumerator_type, Location), gname);
575 // Just call generic GetEnumerator implementation
577 var stmt = new Return (new Invocation (new DynamicMethodGroupExpr (gget_enumerator, Location), null), Location);
578 Method get_enumerator = GetEnumeratorMethod.Create (this, new TypeExpression (Compiler.BuiltinTypes.IEnumerator, Location), name, stmt);
580 Members.Add (get_enumerator);
581 Members.Add (gget_enumerator);
583 Members.Add (GetEnumeratorMethod.Create (this, new TypeExpression (Compiler.BuiltinTypes.IEnumerator, Location), name));
587 return base.DoDefineMembers ();
590 void Define_Current (bool is_generic)
593 FullNamedExpression explicit_iface;
596 explicit_iface = new TypeExpression (generic_enumerator_type, Location);
597 type = iterator_type_expr;
599 explicit_iface = new TypeExpression (Module.Compiler.BuiltinTypes.IEnumerator, Location);
600 type = new TypeExpression (Compiler.BuiltinTypes.Object, Location);
603 var name = new MemberName ("Current", null, explicit_iface, Location);
605 ToplevelBlock get_block = new ToplevelBlock (Compiler, ParametersCompiled.EmptyReadOnlyParameters, Location,
606 Block.Flags.CompilerGenerated | Block.Flags.NoFlowAnalysis);
607 get_block.AddStatement (new Return (new DynamicFieldExpr (CurrentField, Location), Location));
609 Property current = new Property (this, type, Modifiers.DEBUGGER_HIDDEN | Modifiers.COMPILER_GENERATED, name, null);
610 current.Get = new Property.GetMethod (current, Modifiers.COMPILER_GENERATED, null, Location);
611 current.Get.Block = get_block;
613 Members.Add (current);
618 Method reset = new Method (
619 this, new TypeExpression (Compiler.BuiltinTypes.Void, Location),
620 Modifiers.PUBLIC | Modifiers.DEBUGGER_HIDDEN | Modifiers.COMPILER_GENERATED,
621 new MemberName ("Reset", Location),
622 ParametersCompiled.EmptyReadOnlyParameters, null);
625 reset.Block = new ToplevelBlock (Compiler, reset.ParameterInfo, Location,
626 Block.Flags.CompilerGenerated | Block.Flags.NoFlowAnalysis);
628 TypeSpec ex_type = Module.PredefinedTypes.NotSupportedException.Resolve ();
632 reset.Block.AddStatement (new Throw (new New (new TypeExpression (ex_type, Location), null, Location), Location));
635 protected override void EmitHoistedParameters (EmitContext ec, List<HoistedParameter> hoisted)
637 base.EmitHoistedParameters (ec, hoisted);
638 if (hoisted_params_copy != null)
639 base.EmitHoistedParameters (ec, hoisted_params_copy);
643 public class StateMachineMethod : Method
645 readonly StateMachineInitializer expr;
647 public StateMachineMethod (StateMachine host, StateMachineInitializer expr, FullNamedExpression returnType,
648 Modifiers mod, MemberName name, ToplevelBlock.Flags blockFlags)
649 : base (host, returnType, mod | Modifiers.COMPILER_GENERATED,
650 name, ParametersCompiled.EmptyReadOnlyParameters, null)
653 Block = new ToplevelBlock (host.Compiler, ParametersCompiled.EmptyReadOnlyParameters, Location.Null, blockFlags);
656 public override EmitContext CreateEmitContext (ILGenerator ig, SourceMethodBuilder sourceMethod)
658 EmitContext ec = new EmitContext (this, ig, MemberType, sourceMethod);
659 ec.CurrentAnonymousMethod = expr;
661 if (expr is AsyncInitializer)
662 ec.With (BuilderContext.Options.AsyncBody, true);
668 public abstract class StateMachineInitializer : AnonymousExpression
670 sealed class MoveNextBodyStatement : Statement
672 readonly StateMachineInitializer state_machine;
674 public MoveNextBodyStatement (StateMachineInitializer stateMachine)
676 this.state_machine = stateMachine;
677 this.loc = stateMachine.Location;
680 protected override void CloneTo (CloneContext clonectx, Statement target)
682 throw new NotSupportedException ();
685 public override bool Resolve (BlockContext ec)
690 protected override void DoEmit (EmitContext ec)
692 state_machine.EmitMoveNext (ec);
695 public override void Emit (EmitContext ec)
697 // Don't create sequence point
701 protected override bool DoFlowAnalysis (FlowAnalysisContext fc)
703 return state_machine.ReturnType.Kind != MemberKind.Void;
706 public override Reachability MarkReachable (Reachability rc)
708 base.MarkReachable (rc);
710 if (state_machine.ReturnType.Kind != MemberKind.Void)
711 rc = Reachability.CreateUnreachable ();
717 public readonly TypeDefinition Host;
718 protected StateMachine storey;
721 // The state as we generate the machine
724 Label iterator_body_end;
725 protected Label move_next_error;
726 LocalBuilder skip_finally;
727 protected LocalBuilder current_pc;
728 protected List<ResumableStatement> resume_points;
730 protected StateMachineInitializer (ParametersBlock block, TypeDefinition host, TypeSpec returnType)
731 : base (block, returnType, block.StartLocation)
738 public Label BodyEnd {
740 return iterator_body_end;
744 public LocalBuilder CurrentPC
751 public LocalBuilder SkipFinally {
757 public override AnonymousMethodStorey Storey {
765 public int AddResumePoint (ResumableStatement stmt)
767 if (resume_points == null)
768 resume_points = new List<ResumableStatement> ();
770 resume_points.Add (stmt);
771 return resume_points.Count;
774 public override Expression CreateExpressionTree (ResolveContext ec)
776 throw new NotSupportedException ("ET");
779 protected virtual BlockContext CreateBlockContext (BlockContext bc)
781 var ctx = new BlockContext (bc, block, bc.ReturnType);
782 ctx.CurrentAnonymousMethod = this;
784 ctx.AssignmentInfoOffset = bc.AssignmentInfoOffset;
785 ctx.EnclosingLoop = bc.EnclosingLoop;
786 ctx.EnclosingLoopOrSwitch = bc.EnclosingLoopOrSwitch;
787 ctx.Switch = bc.Switch;
792 protected override Expression DoResolve (ResolveContext rc)
794 var bc = (BlockContext) rc;
795 var ctx = CreateBlockContext (bc);
799 if (!rc.IsInProbingMode) {
800 var move_next = new StateMachineMethod (storey, this, new TypeExpression (ReturnType, loc), Modifiers.PUBLIC, new MemberName ("MoveNext", loc), 0);
801 move_next.Block.AddStatement (new MoveNextBodyStatement (this));
802 storey.AddEntryMethod (move_next);
805 bc.AssignmentInfoOffset = ctx.AssignmentInfoOffset;
806 eclass = ExprClass.Value;
810 public override void Emit (EmitContext ec)
813 // Load state machine instance
815 storey.Instance.Emit (ec);
818 void EmitMoveNext_NoResumePoints (EmitContext ec)
821 ec.Emit (OpCodes.Ldfld, storey.PC.Spec);
824 ec.EmitInt ((int) IteratorStorey.State.After);
825 ec.Emit (OpCodes.Stfld, storey.PC.Spec);
827 // We only care if the PC is zero (start executing) or non-zero (don't do anything)
828 ec.Emit (OpCodes.Brtrue, move_next_error);
830 iterator_body_end = ec.DefineLabel ();
832 block.EmitEmbedded (ec);
834 ec.MarkLabel (iterator_body_end);
836 EmitMoveNextEpilogue (ec);
838 ec.MarkLabel (move_next_error);
840 if (ReturnType.Kind != MemberKind.Void) {
842 ec.Emit (OpCodes.Ret);
846 void EmitMoveNext (EmitContext ec)
848 move_next_ok = ec.DefineLabel ();
849 move_next_error = ec.DefineLabel ();
851 if (resume_points == null) {
852 EmitMoveNext_NoResumePoints (ec);
856 current_pc = ec.GetTemporaryLocal (ec.BuiltinTypes.UInt);
858 ec.Emit (OpCodes.Ldfld, storey.PC.Spec);
859 ec.Emit (OpCodes.Stloc, current_pc);
861 // We're actually in state 'running', but this is as good a PC value as any if there's an abnormal exit
863 ec.EmitInt ((int) IteratorStorey.State.After);
864 ec.Emit (OpCodes.Stfld, storey.PC.Spec);
866 Label[] labels = new Label[1 + resume_points.Count];
867 labels[0] = ec.DefineLabel ();
869 bool need_skip_finally = false;
870 for (int i = 0; i < resume_points.Count; ++i) {
871 ResumableStatement s = resume_points[i];
872 need_skip_finally |= s is ExceptionStatement;
873 labels[i + 1] = s.PrepareForEmit (ec);
876 if (need_skip_finally) {
877 skip_finally = ec.GetTemporaryLocal (ec.BuiltinTypes.Bool);
879 ec.Emit (OpCodes.Stloc, skip_finally);
882 var async_init = this as AsyncInitializer;
883 if (async_init != null)
884 ec.BeginExceptionBlock ();
886 ec.Emit (OpCodes.Ldloc, current_pc);
887 ec.Emit (OpCodes.Switch, labels);
889 ec.Emit (async_init != null ? OpCodes.Leave : OpCodes.Br, move_next_error);
891 ec.MarkLabel (labels[0]);
893 iterator_body_end = ec.DefineLabel ();
895 block.EmitEmbedded (ec);
897 ec.MarkLabel (iterator_body_end);
899 if (async_init != null) {
900 var catch_value = LocalVariable.CreateCompilerGenerated (ec.Module.Compiler.BuiltinTypes.Exception, block, Location);
902 ec.BeginCatchBlock (catch_value.Type);
903 catch_value.EmitAssign (ec);
906 ec.EmitInt ((int) IteratorStorey.State.After);
907 ec.Emit (OpCodes.Stfld, storey.PC.Spec);
909 ((AsyncTaskStorey) async_init.Storey).EmitSetException (ec, new LocalVariableReference (catch_value, Location));
911 ec.Emit (OpCodes.Leave, move_next_ok);
912 ec.EndExceptionBlock ();
915 ec.Mark (Block.Original.EndLocation);
917 ec.EmitInt ((int) IteratorStorey.State.After);
918 ec.Emit (OpCodes.Stfld, storey.PC.Spec);
920 EmitMoveNextEpilogue (ec);
922 ec.MarkLabel (move_next_error);
924 if (ReturnType.Kind != MemberKind.Void) {
926 ec.Emit (OpCodes.Ret);
929 ec.MarkLabel (move_next_ok);
931 if (ReturnType.Kind != MemberKind.Void) {
933 ec.Emit (OpCodes.Ret);
937 protected virtual void EmitMoveNextEpilogue (EmitContext ec)
941 public void EmitLeave (EmitContext ec, bool unwind_protect)
944 ec.Emit (unwind_protect ? OpCodes.Leave : OpCodes.Br, move_next_ok);
948 // Called back from YieldStatement
950 public virtual void InjectYield (EmitContext ec, Expression expr, int resume_pc, bool unwind_protect, Label resume_point)
953 // Guard against being disposed meantime
955 Label disposed = ec.DefineLabel ();
956 var iterator = storey as IteratorStorey;
957 if (iterator != null) {
959 ec.Emit (OpCodes.Ldfld, iterator.DisposingField.Spec);
960 ec.Emit (OpCodes.Brtrue_S, disposed);
964 // store resume program-counter
967 ec.EmitInt (resume_pc);
968 ec.Emit (OpCodes.Stfld, storey.PC.Spec);
970 if (iterator != null) {
971 ec.MarkLabel (disposed);
974 // mark finally blocks as disabled
975 if (unwind_protect && skip_finally != null) {
977 ec.Emit (OpCodes.Stloc, skip_finally);
981 public void SetStateMachine (StateMachine stateMachine)
983 this.storey = stateMachine;
988 // Iterators are implemented as state machine blocks
990 public class Iterator : StateMachineInitializer
992 sealed class TryFinallyBlockProxyStatement : Statement
994 TryFinallyBlock block;
997 public TryFinallyBlockProxyStatement (Iterator iterator, TryFinallyBlock block)
999 this.iterator = iterator;
1003 protected override void CloneTo (CloneContext clonectx, Statement target)
1005 throw new NotSupportedException ();
1008 protected override bool DoFlowAnalysis (FlowAnalysisContext fc)
1010 throw new NotSupportedException ();
1013 protected override void DoEmit (EmitContext ec)
1016 // Restore redirection for any captured variables
1018 ec.CurrentAnonymousMethod = iterator;
1020 using (ec.With (BuilderContext.Options.OmitDebugInfo, !ec.HasMethodSymbolBuilder)) {
1021 block.EmitFinallyBody (ec);
1026 public readonly IMethodData OriginalMethod;
1027 public readonly bool IsEnumerable;
1028 public readonly TypeSpec OriginalIteratorType;
1029 int finally_hosts_counter;
1031 public Iterator (ParametersBlock block, IMethodData method, TypeDefinition host, TypeSpec iterator_type, bool is_enumerable)
1032 : base (block, host, host.Compiler.BuiltinTypes.Bool)
1034 this.OriginalMethod = method;
1035 this.OriginalIteratorType = iterator_type;
1036 this.IsEnumerable = is_enumerable;
1037 this.type = method.ReturnType;
1042 public ToplevelBlock Container {
1043 get { return OriginalMethod.Block; }
1046 public override string ContainerType {
1047 get { return "iterator"; }
1050 public override bool IsIterator {
1051 get { return true; }
1056 public Method CreateFinallyHost (TryFinallyBlock block)
1058 var method = new Method (storey, new TypeExpression (storey.Compiler.BuiltinTypes.Void, loc),
1059 Modifiers.COMPILER_GENERATED, new MemberName (CompilerGeneratedContainer.MakeName (null, null, "Finally", finally_hosts_counter++), loc),
1060 ParametersCompiled.EmptyReadOnlyParameters, null);
1062 method.Block = new ToplevelBlock (method.Compiler, method.ParameterInfo, loc,
1063 ToplevelBlock.Flags.CompilerGenerated | ToplevelBlock.Flags.NoFlowAnalysis);
1064 method.Block.AddStatement (new TryFinallyBlockProxyStatement (this, block));
1066 // Cannot it add to storey because it'd be emitted before nested
1067 // anonoymous methods which could capture shared variable
1072 public void EmitYieldBreak (EmitContext ec, bool unwind_protect)
1074 ec.Emit (unwind_protect ? OpCodes.Leave : OpCodes.Br, move_next_error);
1077 public override string GetSignatureForError ()
1079 return OriginalMethod.GetSignatureForError ();
1082 public override void Emit (EmitContext ec)
1085 // Load Iterator storey instance
1087 storey.Instance.Emit (ec);
1090 // Initialize iterator PC when it's unitialized
1093 ec.Emit (OpCodes.Dup);
1094 ec.EmitInt ((int)IteratorStorey.State.Uninitialized);
1096 var field = storey.PC.Spec;
1097 if (storey.MemberName.IsGeneric) {
1098 field = MemberCache.GetMember (Storey.Instance.Type, field);
1101 ec.Emit (OpCodes.Stfld, field);
1105 public void EmitDispose (EmitContext ec)
1107 if (resume_points == null)
1110 Label end = ec.DefineLabel ();
1112 Label[] labels = null;
1113 for (int i = 0; i < resume_points.Count; ++i) {
1114 ResumableStatement s = resume_points[i];
1115 Label ret = s.PrepareForDispose (ec, end);
1116 if (ret.Equals (end) && labels == null)
1118 if (labels == null) {
1119 labels = new Label[resume_points.Count + 1];
1120 for (int j = 0; j <= i; ++j)
1124 labels[i + 1] = ret;
1127 if (labels != null) {
1128 current_pc = ec.GetTemporaryLocal (ec.BuiltinTypes.UInt);
1130 ec.Emit (OpCodes.Ldfld, storey.PC.Spec);
1131 ec.Emit (OpCodes.Stloc, current_pc);
1136 ec.Emit (OpCodes.Stfld, ((IteratorStorey) storey).DisposingField.Spec);
1139 ec.EmitInt ((int) IteratorStorey.State.After);
1140 ec.Emit (OpCodes.Stfld, storey.PC.Spec);
1142 if (labels != null) {
1143 //SymbolWriter.StartIteratorDispatcher (ec.ig);
1144 ec.Emit (OpCodes.Ldloc, current_pc);
1145 ec.Emit (OpCodes.Switch, labels);
1146 //SymbolWriter.EndIteratorDispatcher (ec.ig);
1148 foreach (ResumableStatement s in resume_points)
1149 s.EmitForDispose (ec, current_pc, end, true);
1155 public override void EmitStatement (EmitContext ec)
1157 throw new NotImplementedException ();
1160 public override void InjectYield (EmitContext ec, Expression expr, int resume_pc, bool unwind_protect, Label resume_point)
1162 // Store the new value into current
1163 var fe = new FieldExpr (((IteratorStorey) storey).CurrentField, loc);
1164 fe.InstanceExpression = new CompilerGeneratedThis (storey.CurrentType, loc);
1165 fe.EmitAssign (ec, expr, false, false);
1167 base.InjectYield (ec, expr, resume_pc, unwind_protect, resume_point);
1169 EmitLeave (ec, unwind_protect);
1171 ec.MarkLabel (resume_point);
1174 public static void CreateIterator (IMethodData method, TypeDefinition parent, Modifiers modifiers)
1177 TypeSpec iterator_type;
1179 TypeSpec ret = method.ReturnType;
1183 if (!CheckType (ret, parent, out iterator_type, out is_enumerable)) {
1184 parent.Compiler.Report.Error (1624, method.Location,
1185 "The body of `{0}' cannot be an iterator block " +
1186 "because `{1}' is not an iterator interface type",
1187 method.GetSignatureForError (),
1188 ret.GetSignatureForError ());
1192 ParametersCompiled parameters = method.ParameterInfo;
1193 for (int i = 0; i < parameters.Count; i++) {
1194 Parameter p = parameters [i];
1195 Parameter.Modifier mod = p.ModFlags;
1196 if ((mod & Parameter.Modifier.RefOutMask) != 0) {
1197 parent.Compiler.Report.Error (1623, p.Location,
1198 "Iterators cannot have ref or out parameters");
1202 if (p is ArglistParameter) {
1203 parent.Compiler.Report.Error (1636, method.Location,
1204 "__arglist is not allowed in parameter list of iterators");
1208 if (parameters.Types [i].IsPointer) {
1209 parent.Compiler.Report.Error (1637, p.Location,
1210 "Iterators cannot have unsafe parameters or yield types");
1215 if ((modifiers & Modifiers.UNSAFE) != 0) {
1216 parent.Compiler.Report.Error (1629, method.Location, "Unsafe code may not appear in iterators");
1219 method.Block = method.Block.ConvertToIterator (method, parent, iterator_type, is_enumerable);
1222 static bool CheckType (TypeSpec ret, TypeContainer parent, out TypeSpec original_iterator_type, out bool is_enumerable)
1224 original_iterator_type = null;
1225 is_enumerable = false;
1227 if (ret.BuiltinType == BuiltinTypeSpec.Type.IEnumerable) {
1228 original_iterator_type = parent.Compiler.BuiltinTypes.Object;
1229 is_enumerable = true;
1232 if (ret.BuiltinType == BuiltinTypeSpec.Type.IEnumerator) {
1233 original_iterator_type = parent.Compiler.BuiltinTypes.Object;
1234 is_enumerable = false;
1238 InflatedTypeSpec inflated = ret as InflatedTypeSpec;
1239 if (inflated == null)
1242 var member_definition = inflated.MemberDefinition;
1243 PredefinedType ptype = parent.Module.PredefinedTypes.IEnumerableGeneric;
1245 if (ptype.Define () && ptype.TypeSpec.MemberDefinition == member_definition) {
1246 original_iterator_type = inflated.TypeArguments[0];
1247 is_enumerable = true;
1251 ptype = parent.Module.PredefinedTypes.IEnumeratorGeneric;
1252 if (ptype.Define () && ptype.TypeSpec.MemberDefinition == member_definition) {
1253 original_iterator_type = inflated.TypeArguments[0];
1254 is_enumerable = false;