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 ()
80 if (inside_try_block == null) {
81 resume_pc = machine_initializer.AddResumePoint (this);
83 resume_pc = inside_try_block.AddResumePoint (this, resume_pc, machine_initializer);
84 unwind_protect = true;
85 inside_try_block = null;
90 public class Yield : YieldStatement<Iterator>
92 public Yield (Expression expr, Location loc)
97 public static bool CheckContext (BlockContext bc, Location loc)
99 if (!bc.CurrentAnonymousMethod.IsIterator) {
100 bc.Report.Error (1621, loc,
101 "The yield statement cannot be used inside anonymous method blocks");
105 if (bc.HasSet (ResolveContext.Options.FinallyScope)) {
106 bc.Report.Error (1625, loc, "Cannot yield in the body of a finally clause");
113 public override bool Resolve (BlockContext bc)
115 if (!CheckContext (bc, loc))
118 if (bc.HasAny (ResolveContext.Options.TryWithCatchScope)) {
119 bc.Report.Error (1626, loc, "Cannot yield a value in the body of a try block with a catch clause");
122 if (bc.HasSet (ResolveContext.Options.CatchScope)) {
123 bc.Report.Error (1631, loc, "Cannot yield a value in the body of a catch clause");
126 if (!base.Resolve (bc))
129 var otype = bc.CurrentIterator.OriginalIteratorType;
130 if (expr.Type != otype) {
131 expr = Convert.ImplicitConversionRequired (bc, expr, otype, loc);
139 public override object Accept (StructuralVisitor visitor)
141 return visitor.Visit (this);
145 public class YieldBreak : ExitStatement
149 public YieldBreak (Location l)
154 protected override bool IsLocalExit {
160 protected override void CloneTo (CloneContext clonectx, Statement target)
162 throw new NotSupportedException ();
165 protected override bool DoResolve (BlockContext bc)
167 iterator = bc.CurrentIterator;
168 return Yield.CheckContext (bc, loc);
171 protected override void DoEmit (EmitContext ec)
173 iterator.EmitYieldBreak (ec, unwind_protect);
176 protected override bool DoFlowAnalysis (FlowAnalysisContext fc)
181 public override Reachability MarkReachable (Reachability rc)
183 base.MarkReachable (rc);
184 return Reachability.CreateUnreachable ();
187 public override object Accept (StructuralVisitor visitor)
189 return visitor.Visit (this);
193 public abstract class StateMachine : AnonymousMethodStorey
197 Running = -3, // Used only in CurrentPC, never stored into $PC
204 StateMachineMethod method;
206 protected StateMachine (ParametersBlock block, TypeDefinition parent, MemberBase host, TypeParameters tparams, string name, MemberKind kind)
207 : base (block, parent, host, tparams, name, kind)
209 OriginalTypeParameters = tparams;
214 public TypeParameters OriginalTypeParameters { get; private set; }
216 public StateMachineMethod StateMachineMethod {
230 public void AddEntryMethod (StateMachineMethod method)
232 if (this.method != null)
233 throw new InternalErrorException ();
235 this.method = method;
236 Members.Add (method);
239 protected override bool DoDefineMembers ()
241 pc_field = AddCompilerGeneratedField ("$PC", new TypeExpression (Compiler.BuiltinTypes.Int, Location));
243 return base.DoDefineMembers ();
246 protected override string GetVariableMangledName (ResolveContext rc, LocalVariable local_info)
248 if (local_info.IsCompilerGenerated)
249 return base.GetVariableMangledName (rc, local_info);
252 // Special format which encodes original variable name and
253 // it's scope to support lifted variables debugging. This
254 // is same what csc does and allows to correctly set fields
255 // scope information (like ambiguity, our of scope, etc).
257 var id = rc.CurrentBlock.Explicit.GetDebugSymbolScopeIndex ();
258 return "<" + local_info.Name + ">__" + id;
262 class IteratorStorey : StateMachine
264 class GetEnumeratorMethod : StateMachineMethod
266 sealed class GetEnumeratorStatement : Statement
268 readonly IteratorStorey host;
269 readonly StateMachineMethod host_method;
271 Expression new_storey;
273 public GetEnumeratorStatement (IteratorStorey host, StateMachineMethod host_method)
276 this.host_method = host_method;
277 loc = host_method.Location;
280 protected override void CloneTo (CloneContext clonectx, Statement target)
282 throw new NotSupportedException ();
285 public override bool Resolve (BlockContext ec)
287 TypeExpression storey_type_expr = new TypeExpression (host.Definition, loc);
288 List<Expression> init = null;
289 if (host.hoisted_this != null) {
290 init = new List<Expression> (host.hoisted_params == null ? 1 : host.HoistedParameters.Count + 1);
291 HoistedThis ht = host.hoisted_this;
292 FieldExpr from = new FieldExpr (ht.Field, loc);
293 from.InstanceExpression = new CompilerGeneratedThis (ec.CurrentType, loc);
294 init.Add (new ElementInitializer (ht.Field.Name, from, loc));
297 if (host.hoisted_params != null) {
299 init = new List<Expression> (host.HoistedParameters.Count);
301 for (int i = 0; i < host.hoisted_params.Count; ++i) {
302 HoistedParameter hp = host.hoisted_params [i];
303 HoistedParameter hp_cp = host.hoisted_params_copy [i] ?? hp;
305 FieldExpr from = new FieldExpr (hp_cp.Field, loc);
306 from.InstanceExpression = new CompilerGeneratedThis (ec.CurrentType, loc);
308 init.Add (new ElementInitializer (hp.Field.Name, from, loc));
313 new_storey = new NewInitialize (storey_type_expr, null,
314 new CollectionOrObjectInitializers (init, loc), loc);
316 new_storey = new New (storey_type_expr, null, loc);
319 new_storey = new_storey.Resolve (ec);
320 if (new_storey != null)
321 new_storey = Convert.ImplicitConversionRequired (ec, new_storey, host_method.MemberType, loc);
326 protected override void DoEmit (EmitContext ec)
328 Label label_init = ec.DefineLabel ();
331 ec.Emit (OpCodes.Ldflda, host.PC.Spec);
332 ec.EmitInt ((int) State.Start);
333 ec.EmitInt ((int) State.Uninitialized);
335 var m = ec.Module.PredefinedMembers.InterlockedCompareExchange.Resolve (loc);
337 ec.Emit (OpCodes.Call, m);
339 ec.EmitInt ((int) State.Uninitialized);
340 ec.Emit (OpCodes.Bne_Un_S, label_init);
343 ec.Emit (OpCodes.Ret);
345 ec.MarkLabel (label_init);
347 new_storey.Emit (ec);
348 ec.Emit (OpCodes.Ret);
351 protected override bool DoFlowAnalysis (FlowAnalysisContext fc)
353 throw new NotImplementedException ();
356 public override Reachability MarkReachable (Reachability rc)
358 base.MarkReachable (rc);
359 return Reachability.CreateUnreachable ();
363 GetEnumeratorMethod (IteratorStorey host, FullNamedExpression returnType, MemberName name)
364 : base (host, null, returnType, Modifiers.DEBUGGER_HIDDEN, name, ToplevelBlock.Flags.CompilerGenerated | ToplevelBlock.Flags.NoFlowAnalysis)
368 public static GetEnumeratorMethod Create (IteratorStorey host, FullNamedExpression returnType, MemberName name)
370 return Create (host, returnType, name, null);
373 public static GetEnumeratorMethod Create (IteratorStorey host, FullNamedExpression returnType, MemberName name, Statement statement)
375 var m = new GetEnumeratorMethod (host, returnType, name);
376 var stmt = statement ?? new GetEnumeratorStatement (host, m);
377 m.block.AddStatement (stmt);
382 class DisposeMethod : StateMachineMethod
384 sealed class DisposeMethodStatement : Statement
388 public DisposeMethodStatement (Iterator iterator)
390 this.iterator = iterator;
391 this.loc = iterator.Location;
394 protected override void CloneTo (CloneContext clonectx, Statement target)
396 throw new NotSupportedException ();
399 public override bool Resolve (BlockContext ec)
404 protected override void DoEmit (EmitContext ec)
406 ec.CurrentAnonymousMethod = iterator;
407 iterator.EmitDispose (ec);
410 protected override bool DoFlowAnalysis (FlowAnalysisContext fc)
412 throw new NotImplementedException ();
416 public DisposeMethod (IteratorStorey host)
417 : base (host, null, new TypeExpression (host.Compiler.BuiltinTypes.Void, host.Location), Modifiers.PUBLIC | Modifiers.DEBUGGER_HIDDEN,
418 new MemberName ("Dispose", host.Location), ToplevelBlock.Flags.CompilerGenerated | ToplevelBlock.Flags.NoFlowAnalysis)
420 host.Members.Add (this);
422 Block.AddStatement (new DisposeMethodStatement (host.Iterator));
427 // Uses Method as method info
429 class DynamicMethodGroupExpr : MethodGroupExpr
431 readonly Method method;
433 public DynamicMethodGroupExpr (Method method, Location loc)
434 : base ((IList<MemberSpec>) null, null, loc)
436 this.method = method;
437 eclass = ExprClass.Unresolved;
440 protected override Expression DoResolve (ResolveContext ec)
442 Methods = new List<MemberSpec> (1) { method.Spec };
443 type = method.Parent.Definition;
444 InstanceExpression = new CompilerGeneratedThis (type, Location);
445 return base.DoResolve (ec);
449 class DynamicFieldExpr : FieldExpr
451 readonly Field field;
453 public DynamicFieldExpr (Field field, Location loc)
459 protected override Expression DoResolve (ResolveContext ec)
462 type = spec.MemberType;
463 InstanceExpression = new CompilerGeneratedThis (type, Location);
464 return base.DoResolve (ec);
468 public readonly Iterator Iterator;
470 List<HoistedParameter> hoisted_params_copy;
472 TypeExpr iterator_type_expr;
474 Field disposing_field;
476 TypeSpec generic_enumerator_type;
477 TypeSpec generic_enumerable_type;
479 public IteratorStorey (Iterator iterator)
480 : base (iterator.Container.ParametersBlock, iterator.Host,
481 iterator.OriginalMethod as MemberBase, iterator.OriginalMethod.CurrentTypeParameters, "Iterator", MemberKind.Class)
483 this.Iterator = iterator;
486 public Field CurrentField {
488 return current_field;
492 public Field DisposingField {
494 return disposing_field;
498 public IList<HoistedParameter> HoistedParameters {
499 get { return hoisted_params; }
502 protected override Constructor DefineDefaultConstructor (bool is_static)
504 var ctor = base.DefineDefaultConstructor (is_static);
505 ctor.ModFlags |= Modifiers.DEBUGGER_HIDDEN;
509 protected override TypeSpec[] ResolveBaseTypes (out FullNamedExpression base_class)
511 var mtype = Iterator.OriginalIteratorType;
513 mtype = Mutator.Mutate (mtype);
515 iterator_type_expr = new TypeExpression (mtype, Location);
517 var ifaces = new List<TypeSpec> (5);
518 if (Iterator.IsEnumerable) {
519 ifaces.Add (Compiler.BuiltinTypes.IEnumerable);
521 if (Module.PredefinedTypes.IEnumerableGeneric.Define ()) {
522 generic_enumerable_type = Module.PredefinedTypes.IEnumerableGeneric.TypeSpec.MakeGenericType (Module, new[] { mtype });
523 ifaces.Add (generic_enumerable_type);
527 ifaces.Add (Compiler.BuiltinTypes.IEnumerator);
528 ifaces.Add (Compiler.BuiltinTypes.IDisposable);
530 var ienumerator_generic = Module.PredefinedTypes.IEnumeratorGeneric;
531 if (ienumerator_generic.Define ()) {
532 generic_enumerator_type = ienumerator_generic.TypeSpec.MakeGenericType (Module, new [] { mtype });
533 ifaces.Add (generic_enumerator_type);
538 base_type = Compiler.BuiltinTypes.Object;
539 return ifaces.ToArray ();
542 protected override bool DoDefineMembers ()
544 current_field = AddCompilerGeneratedField ("$current", iterator_type_expr);
545 disposing_field = AddCompilerGeneratedField ("$disposing", new TypeExpression (Compiler.BuiltinTypes.Bool, Location));
547 if (Iterator.IsEnumerable && hoisted_params != null) {
549 // Iterators are independent, each GetEnumerator call has to
550 // create same enumerator therefore we have to keep original values
551 // around for re-initialization
553 hoisted_params_copy = new List<HoistedParameter> (hoisted_params.Count);
554 foreach (HoistedParameter hp in hoisted_params) {
557 // Don't create field copy for unmodified captured parameters
559 HoistedParameter hp_copy;
561 hp_copy = new HoistedParameter (hp, "<$>" + hp.Field.Name);
566 hoisted_params_copy.Add (hp_copy);
570 if (generic_enumerator_type != null)
571 Define_Current (true);
573 Define_Current (false);
574 new DisposeMethod (this);
577 if (Iterator.IsEnumerable) {
578 FullNamedExpression explicit_iface = new TypeExpression (Compiler.BuiltinTypes.IEnumerable, Location);
579 var name = new MemberName ("GetEnumerator", null, explicit_iface, Location.Null);
581 if (generic_enumerator_type != null) {
582 explicit_iface = new TypeExpression (generic_enumerable_type, Location);
583 var gname = new MemberName ("GetEnumerator", null, explicit_iface, Location.Null);
584 Method gget_enumerator = GetEnumeratorMethod.Create (this, new TypeExpression (generic_enumerator_type, Location), gname);
587 // Just call generic GetEnumerator implementation
589 var stmt = new Return (new Invocation (new DynamicMethodGroupExpr (gget_enumerator, Location), null), Location);
590 Method get_enumerator = GetEnumeratorMethod.Create (this, new TypeExpression (Compiler.BuiltinTypes.IEnumerator, Location), name, stmt);
592 Members.Add (get_enumerator);
593 Members.Add (gget_enumerator);
595 Members.Add (GetEnumeratorMethod.Create (this, new TypeExpression (Compiler.BuiltinTypes.IEnumerator, Location), name));
599 return base.DoDefineMembers ();
602 void Define_Current (bool is_generic)
605 FullNamedExpression explicit_iface;
608 explicit_iface = new TypeExpression (generic_enumerator_type, Location);
609 type = iterator_type_expr;
611 explicit_iface = new TypeExpression (Module.Compiler.BuiltinTypes.IEnumerator, Location);
612 type = new TypeExpression (Compiler.BuiltinTypes.Object, Location);
615 var name = new MemberName ("Current", null, explicit_iface, Location);
617 ToplevelBlock get_block = new ToplevelBlock (Compiler, ParametersCompiled.EmptyReadOnlyParameters, Location,
618 Block.Flags.CompilerGenerated | Block.Flags.NoFlowAnalysis);
619 get_block.AddStatement (new Return (new DynamicFieldExpr (CurrentField, Location), Location));
621 Property current = new Property (this, type, Modifiers.DEBUGGER_HIDDEN | Modifiers.COMPILER_GENERATED, name, null);
622 current.Get = new Property.GetMethod (current, Modifiers.COMPILER_GENERATED, null, Location);
623 current.Get.Block = get_block;
625 Members.Add (current);
630 Method reset = new Method (
631 this, new TypeExpression (Compiler.BuiltinTypes.Void, Location),
632 Modifiers.PUBLIC | Modifiers.DEBUGGER_HIDDEN | Modifiers.COMPILER_GENERATED,
633 new MemberName ("Reset", Location),
634 ParametersCompiled.EmptyReadOnlyParameters, null);
637 reset.Block = new ToplevelBlock (Compiler, reset.ParameterInfo, Location,
638 Block.Flags.CompilerGenerated | Block.Flags.NoFlowAnalysis);
640 TypeSpec ex_type = Module.PredefinedTypes.NotSupportedException.Resolve ();
644 reset.Block.AddStatement (new Throw (new New (new TypeExpression (ex_type, Location), null, Location), Location));
647 protected override void EmitHoistedParameters (EmitContext ec, List<HoistedParameter> hoisted)
649 base.EmitHoistedParameters (ec, hoisted);
650 if (hoisted_params_copy != null)
651 base.EmitHoistedParameters (ec, hoisted_params_copy);
655 public class StateMachineMethod : Method
657 readonly StateMachineInitializer expr;
659 public StateMachineMethod (StateMachine host, StateMachineInitializer expr, FullNamedExpression returnType,
660 Modifiers mod, MemberName name, ToplevelBlock.Flags blockFlags)
661 : base (host, returnType, mod | Modifiers.COMPILER_GENERATED,
662 name, ParametersCompiled.EmptyReadOnlyParameters, null)
665 Block = new ToplevelBlock (host.Compiler, ParametersCompiled.EmptyReadOnlyParameters, Location.Null, blockFlags);
668 public override EmitContext CreateEmitContext (ILGenerator ig, SourceMethodBuilder sourceMethod)
670 EmitContext ec = new EmitContext (this, ig, MemberType, sourceMethod);
671 ec.CurrentAnonymousMethod = expr;
673 if (expr is AsyncInitializer)
674 ec.With (BuilderContext.Options.AsyncBody, true);
680 public abstract class StateMachineInitializer : AnonymousExpression
682 sealed class MoveNextBodyStatement : Statement
684 readonly StateMachineInitializer state_machine;
686 public MoveNextBodyStatement (StateMachineInitializer stateMachine)
688 this.state_machine = stateMachine;
689 this.loc = stateMachine.Location;
692 protected override void CloneTo (CloneContext clonectx, Statement target)
694 throw new NotSupportedException ();
697 public override bool Resolve (BlockContext ec)
702 protected override void DoEmit (EmitContext ec)
704 state_machine.EmitMoveNext (ec);
707 public override void Emit (EmitContext ec)
709 // Don't create sequence point
713 protected override bool DoFlowAnalysis (FlowAnalysisContext fc)
715 return state_machine.ReturnType.Kind != MemberKind.Void;
718 public override Reachability MarkReachable (Reachability rc)
720 base.MarkReachable (rc);
722 if (state_machine.ReturnType.Kind != MemberKind.Void)
723 rc = Reachability.CreateUnreachable ();
729 public readonly TypeDefinition Host;
730 protected StateMachine storey;
733 // The state as we generate the machine
735 protected Label move_next_ok;
736 protected Label move_next_error;
737 LocalBuilder skip_finally;
738 protected LocalBuilder current_pc;
739 protected List<ResumableStatement> resume_points;
741 protected StateMachineInitializer (ParametersBlock block, TypeDefinition host, TypeSpec returnType)
742 : base (block, returnType, block.StartLocation)
749 public Label BodyEnd { get; set; }
751 public LocalBuilder CurrentPC
758 public LocalBuilder SkipFinally {
764 public override AnonymousMethodStorey Storey {
772 public int AddResumePoint (ResumableStatement stmt)
774 if (resume_points == null)
775 resume_points = new List<ResumableStatement> ();
777 resume_points.Add (stmt);
778 return resume_points.Count;
781 public override Expression CreateExpressionTree (ResolveContext ec)
783 throw new NotSupportedException ("ET");
786 protected virtual BlockContext CreateBlockContext (BlockContext bc)
788 var ctx = new BlockContext (bc, block, bc.ReturnType);
789 ctx.CurrentAnonymousMethod = this;
791 ctx.AssignmentInfoOffset = bc.AssignmentInfoOffset;
792 ctx.EnclosingLoop = bc.EnclosingLoop;
793 ctx.EnclosingLoopOrSwitch = bc.EnclosingLoopOrSwitch;
794 ctx.Switch = bc.Switch;
799 protected override Expression DoResolve (ResolveContext rc)
801 var bc = (BlockContext) rc;
802 var ctx = CreateBlockContext (bc);
806 if (!rc.IsInProbingMode) {
807 var move_next = new StateMachineMethod (storey, this, new TypeExpression (ReturnType, loc), Modifiers.PUBLIC, new MemberName ("MoveNext", loc), 0);
808 move_next.Block.AddStatement (new MoveNextBodyStatement (this));
809 storey.AddEntryMethod (move_next);
812 bc.AssignmentInfoOffset = ctx.AssignmentInfoOffset;
813 eclass = ExprClass.Value;
817 public override void Emit (EmitContext ec)
820 // Load state machine instance
822 storey.Instance.Emit (ec);
825 void EmitMoveNext_NoResumePoints (EmitContext ec)
828 ec.Emit (OpCodes.Ldfld, storey.PC.Spec);
831 ec.EmitInt ((int) IteratorStorey.State.After);
832 ec.Emit (OpCodes.Stfld, storey.PC.Spec);
834 // We only care if the PC is zero (start executing) or non-zero (don't do anything)
835 ec.Emit (OpCodes.Brtrue, move_next_error);
837 BodyEnd = ec.DefineLabel ();
839 var async_init = this as AsyncInitializer;
840 if (async_init != null)
841 ec.BeginExceptionBlock ();
843 block.EmitEmbedded (ec);
845 if (async_init != null)
846 async_init.EmitCatchBlock (ec);
848 ec.MarkLabel (BodyEnd);
850 EmitMoveNextEpilogue (ec);
852 ec.MarkLabel (move_next_error);
854 if (ReturnType.Kind != MemberKind.Void) {
856 ec.Emit (OpCodes.Ret);
859 ec.MarkLabel (move_next_ok);
862 void EmitMoveNext (EmitContext ec)
864 move_next_ok = ec.DefineLabel ();
865 move_next_error = ec.DefineLabel ();
867 if (resume_points == null) {
868 EmitMoveNext_NoResumePoints (ec);
872 current_pc = ec.GetTemporaryLocal (ec.BuiltinTypes.UInt);
874 ec.Emit (OpCodes.Ldfld, storey.PC.Spec);
875 ec.Emit (OpCodes.Stloc, current_pc);
877 // We're actually in state 'running', but this is as good a PC value as any if there's an abnormal exit
879 ec.EmitInt ((int) IteratorStorey.State.After);
880 ec.Emit (OpCodes.Stfld, storey.PC.Spec);
882 Label[] labels = new Label[1 + resume_points.Count];
883 labels[0] = ec.DefineLabel ();
885 bool need_skip_finally = false;
886 for (int i = 0; i < resume_points.Count; ++i) {
887 ResumableStatement s = resume_points[i];
888 need_skip_finally |= s is ExceptionStatement;
889 labels[i + 1] = s.PrepareForEmit (ec);
892 if (need_skip_finally) {
893 skip_finally = ec.GetTemporaryLocal (ec.BuiltinTypes.Bool);
895 ec.Emit (OpCodes.Stloc, skip_finally);
898 var async_init = this as AsyncInitializer;
899 if (async_init != null)
900 ec.BeginExceptionBlock ();
902 ec.Emit (OpCodes.Ldloc, current_pc);
903 ec.Emit (OpCodes.Switch, labels);
905 ec.Emit (async_init != null ? OpCodes.Leave : OpCodes.Br, move_next_error);
907 ec.MarkLabel (labels[0]);
909 BodyEnd = ec.DefineLabel ();
911 block.EmitEmbedded (ec);
913 ec.MarkLabel (BodyEnd);
915 if (async_init != null) {
916 async_init.EmitCatchBlock (ec);
919 ec.Mark (Block.Original.EndLocation);
921 ec.EmitInt ((int) IteratorStorey.State.After);
922 ec.Emit (OpCodes.Stfld, storey.PC.Spec);
924 EmitMoveNextEpilogue (ec);
926 ec.MarkLabel (move_next_error);
928 if (ReturnType.Kind != MemberKind.Void) {
930 ec.Emit (OpCodes.Ret);
933 ec.MarkLabel (move_next_ok);
935 if (ReturnType.Kind != MemberKind.Void) {
937 ec.Emit (OpCodes.Ret);
941 protected virtual void EmitMoveNextEpilogue (EmitContext ec)
945 public void EmitLeave (EmitContext ec, bool unwind_protect)
948 ec.Emit (unwind_protect ? OpCodes.Leave : OpCodes.Br, move_next_ok);
952 // Called back from YieldStatement
954 public virtual void InjectYield (EmitContext ec, Expression expr, int resume_pc, bool unwind_protect, Label resume_point)
957 // Guard against being disposed meantime
959 Label disposed = ec.DefineLabel ();
960 var iterator = storey as IteratorStorey;
961 if (iterator != null) {
963 ec.Emit (OpCodes.Ldfld, iterator.DisposingField.Spec);
964 ec.Emit (OpCodes.Brtrue_S, disposed);
968 // store resume program-counter
971 ec.EmitInt (resume_pc);
972 ec.Emit (OpCodes.Stfld, storey.PC.Spec);
974 if (iterator != null) {
975 ec.MarkLabel (disposed);
978 // mark finally blocks as disabled
979 if (unwind_protect && skip_finally != null) {
981 ec.Emit (OpCodes.Stloc, skip_finally);
985 public void SetStateMachine (StateMachine stateMachine)
987 this.storey = stateMachine;
992 // Iterators are implemented as state machine blocks
994 public class Iterator : StateMachineInitializer
996 sealed class TryFinallyBlockProxyStatement : Statement
998 TryFinallyBlock block;
1001 public TryFinallyBlockProxyStatement (Iterator iterator, TryFinallyBlock block)
1003 this.iterator = iterator;
1007 protected override void CloneTo (CloneContext clonectx, Statement target)
1009 throw new NotSupportedException ();
1012 protected override bool DoFlowAnalysis (FlowAnalysisContext fc)
1014 throw new NotSupportedException ();
1017 protected override void DoEmit (EmitContext ec)
1020 // Restore redirection for any captured variables
1022 ec.CurrentAnonymousMethod = iterator;
1024 using (ec.With (BuilderContext.Options.OmitDebugInfo, !ec.HasMethodSymbolBuilder)) {
1025 block.EmitFinallyBody (ec);
1030 public readonly IMethodData OriginalMethod;
1031 public readonly bool IsEnumerable;
1032 public readonly TypeSpec OriginalIteratorType;
1033 int finally_hosts_counter;
1035 public Iterator (ParametersBlock block, IMethodData method, TypeDefinition host, TypeSpec iterator_type, bool is_enumerable)
1036 : base (block, host, host.Compiler.BuiltinTypes.Bool)
1038 this.OriginalMethod = method;
1039 this.OriginalIteratorType = iterator_type;
1040 this.IsEnumerable = is_enumerable;
1041 this.type = method.ReturnType;
1046 public ToplevelBlock Container {
1047 get { return OriginalMethod.Block; }
1050 public override string ContainerType {
1051 get { return "iterator"; }
1054 public override bool IsIterator {
1055 get { return true; }
1060 public Method CreateFinallyHost (TryFinallyBlock block)
1062 var method = new Method (storey, new TypeExpression (storey.Compiler.BuiltinTypes.Void, loc),
1063 Modifiers.COMPILER_GENERATED, new MemberName (CompilerGeneratedContainer.MakeName (null, null, "Finally", finally_hosts_counter++), loc),
1064 ParametersCompiled.EmptyReadOnlyParameters, null);
1066 method.Block = new ToplevelBlock (method.Compiler, method.ParameterInfo, loc,
1067 ToplevelBlock.Flags.CompilerGenerated | ToplevelBlock.Flags.NoFlowAnalysis);
1068 method.Block.AddStatement (new TryFinallyBlockProxyStatement (this, block));
1070 // Cannot it add to storey because it'd be emitted before nested
1071 // anonoymous methods which could capture shared variable
1076 public void EmitYieldBreak (EmitContext ec, bool unwind_protect)
1078 ec.Emit (unwind_protect ? OpCodes.Leave : OpCodes.Br, move_next_error);
1081 public override string GetSignatureForError ()
1083 return OriginalMethod.GetSignatureForError ();
1086 public override void Emit (EmitContext ec)
1089 // Load Iterator storey instance
1091 storey.Instance.Emit (ec);
1094 // Initialize iterator PC when it's unitialized
1097 ec.Emit (OpCodes.Dup);
1098 ec.EmitInt ((int)IteratorStorey.State.Uninitialized);
1100 var field = storey.PC.Spec;
1101 if (storey.MemberName.IsGeneric) {
1102 field = MemberCache.GetMember (Storey.Instance.Type, field);
1105 ec.Emit (OpCodes.Stfld, field);
1109 public void EmitDispose (EmitContext ec)
1111 if (resume_points == null)
1114 Label end = ec.DefineLabel ();
1116 Label[] labels = null;
1117 for (int i = 0; i < resume_points.Count; ++i) {
1118 ResumableStatement s = resume_points[i];
1119 Label ret = s.PrepareForDispose (ec, end);
1120 if (ret.Equals (end) && labels == null)
1122 if (labels == null) {
1123 labels = new Label[resume_points.Count + 1];
1124 for (int j = 0; j <= i; ++j)
1128 labels[i + 1] = ret;
1131 if (labels != null) {
1132 current_pc = ec.GetTemporaryLocal (ec.BuiltinTypes.UInt);
1134 ec.Emit (OpCodes.Ldfld, storey.PC.Spec);
1135 ec.Emit (OpCodes.Stloc, current_pc);
1140 ec.Emit (OpCodes.Stfld, ((IteratorStorey) storey).DisposingField.Spec);
1143 ec.EmitInt ((int) IteratorStorey.State.After);
1144 ec.Emit (OpCodes.Stfld, storey.PC.Spec);
1146 if (labels != null) {
1147 //SymbolWriter.StartIteratorDispatcher (ec.ig);
1148 ec.Emit (OpCodes.Ldloc, current_pc);
1149 ec.Emit (OpCodes.Switch, labels);
1150 //SymbolWriter.EndIteratorDispatcher (ec.ig);
1152 foreach (ResumableStatement s in resume_points)
1153 s.EmitForDispose (ec, current_pc, end, true);
1159 public override void EmitStatement (EmitContext ec)
1161 throw new NotImplementedException ();
1164 public override void InjectYield (EmitContext ec, Expression expr, int resume_pc, bool unwind_protect, Label resume_point)
1166 // Store the new value into current
1167 var fe = new FieldExpr (((IteratorStorey) storey).CurrentField, loc);
1168 fe.InstanceExpression = new CompilerGeneratedThis (storey.CurrentType, loc);
1169 fe.EmitAssign (ec, expr, false, false);
1171 base.InjectYield (ec, expr, resume_pc, unwind_protect, resume_point);
1173 EmitLeave (ec, unwind_protect);
1175 ec.MarkLabel (resume_point);
1178 public static void CreateIterator (IMethodData method, TypeDefinition parent, Modifiers modifiers)
1181 TypeSpec iterator_type;
1183 TypeSpec ret = method.ReturnType;
1187 if (!CheckType (ret, parent, out iterator_type, out is_enumerable)) {
1188 parent.Compiler.Report.Error (1624, method.Location,
1189 "The body of `{0}' cannot be an iterator block " +
1190 "because `{1}' is not an iterator interface type",
1191 method.GetSignatureForError (),
1192 ret.GetSignatureForError ());
1196 ParametersCompiled parameters = method.ParameterInfo;
1197 for (int i = 0; i < parameters.Count; i++) {
1198 Parameter p = parameters [i];
1199 Parameter.Modifier mod = p.ModFlags;
1200 if ((mod & Parameter.Modifier.RefOutMask) != 0) {
1201 parent.Compiler.Report.Error (1623, p.Location,
1202 "Iterators cannot have ref or out parameters");
1206 if (p is ArglistParameter) {
1207 parent.Compiler.Report.Error (1636, method.Location,
1208 "__arglist is not allowed in parameter list of iterators");
1212 if (parameters.Types [i].IsPointer) {
1213 parent.Compiler.Report.Error (1637, p.Location,
1214 "Iterators cannot have unsafe parameters or yield types");
1219 if ((modifiers & Modifiers.UNSAFE) != 0) {
1220 parent.Compiler.Report.Error (1629, method.Location, "Unsafe code may not appear in iterators");
1223 method.Block = method.Block.ConvertToIterator (method, parent, iterator_type, is_enumerable);
1226 static bool CheckType (TypeSpec ret, TypeContainer parent, out TypeSpec original_iterator_type, out bool is_enumerable)
1228 original_iterator_type = null;
1229 is_enumerable = false;
1231 if (ret.BuiltinType == BuiltinTypeSpec.Type.IEnumerable) {
1232 original_iterator_type = parent.Compiler.BuiltinTypes.Object;
1233 is_enumerable = true;
1236 if (ret.BuiltinType == BuiltinTypeSpec.Type.IEnumerator) {
1237 original_iterator_type = parent.Compiler.BuiltinTypes.Object;
1238 is_enumerable = false;
1242 InflatedTypeSpec inflated = ret as InflatedTypeSpec;
1243 if (inflated == null)
1246 var member_definition = inflated.MemberDefinition;
1247 PredefinedType ptype = parent.Module.PredefinedTypes.IEnumerableGeneric;
1249 if (ptype.Define () && ptype.TypeSpec.MemberDefinition == member_definition) {
1250 original_iterator_type = inflated.TypeArguments[0];
1251 is_enumerable = true;
1255 ptype = parent.Module.PredefinedTypes.IEnumeratorGeneric;
1256 if (ptype.Define () && ptype.TypeSpec.MemberDefinition == member_definition) {
1257 original_iterator_type = inflated.TypeArguments[0];
1258 is_enumerable = false;