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;
207 protected StateMachine (ParametersBlock block, TypeDefinition parent, MemberBase host, TypeParameters tparams, string name, MemberKind kind)
208 : base (block, parent, host, tparams, name, kind)
210 OriginalTypeParameters = tparams;
215 public TypeParameters OriginalTypeParameters { get; private set; }
217 public StateMachineMethod StateMachineMethod {
231 public void AddEntryMethod (StateMachineMethod method)
233 if (this.method != null)
234 throw new InternalErrorException ();
236 this.method = method;
237 Members.Add (method);
240 protected override bool DoDefineMembers ()
242 pc_field = AddCompilerGeneratedField ("$PC", new TypeExpression (Compiler.BuiltinTypes.Int, Location));
244 return base.DoDefineMembers ();
247 protected override string GetVariableMangledName (LocalVariable local_info)
249 if (local_info.IsCompilerGenerated)
250 return base.GetVariableMangledName (local_info);
252 return "<" + local_info.Name + ">__" + local_name_idx++.ToString ("X");
256 class IteratorStorey : StateMachine
258 class GetEnumeratorMethod : StateMachineMethod
260 sealed class GetEnumeratorStatement : Statement
262 readonly IteratorStorey host;
263 readonly StateMachineMethod host_method;
265 Expression new_storey;
267 public GetEnumeratorStatement (IteratorStorey host, StateMachineMethod host_method)
270 this.host_method = host_method;
271 loc = host_method.Location;
274 protected override void CloneTo (CloneContext clonectx, Statement target)
276 throw new NotSupportedException ();
279 public override bool Resolve (BlockContext ec)
281 TypeExpression storey_type_expr = new TypeExpression (host.Definition, loc);
282 List<Expression> init = null;
283 if (host.hoisted_this != null) {
284 init = new List<Expression> (host.hoisted_params == null ? 1 : host.HoistedParameters.Count + 1);
285 HoistedThis ht = host.hoisted_this;
286 FieldExpr from = new FieldExpr (ht.Field, loc);
287 from.InstanceExpression = new CompilerGeneratedThis (ec.CurrentType, loc);
288 init.Add (new ElementInitializer (ht.Field.Name, from, loc));
291 if (host.hoisted_params != null) {
293 init = new List<Expression> (host.HoistedParameters.Count);
295 for (int i = 0; i < host.hoisted_params.Count; ++i) {
296 HoistedParameter hp = host.hoisted_params [i];
297 HoistedParameter hp_cp = host.hoisted_params_copy [i] ?? hp;
299 FieldExpr from = new FieldExpr (hp_cp.Field, loc);
300 from.InstanceExpression = new CompilerGeneratedThis (ec.CurrentType, loc);
302 init.Add (new ElementInitializer (hp.Field.Name, from, loc));
307 new_storey = new NewInitialize (storey_type_expr, null,
308 new CollectionOrObjectInitializers (init, loc), loc);
310 new_storey = new New (storey_type_expr, null, loc);
313 new_storey = new_storey.Resolve (ec);
314 if (new_storey != null)
315 new_storey = Convert.ImplicitConversionRequired (ec, new_storey, host_method.MemberType, loc);
320 protected override void DoEmit (EmitContext ec)
322 Label label_init = ec.DefineLabel ();
325 ec.Emit (OpCodes.Ldflda, host.PC.Spec);
326 ec.EmitInt ((int) State.Start);
327 ec.EmitInt ((int) State.Uninitialized);
329 var m = ec.Module.PredefinedMembers.InterlockedCompareExchange.Resolve (loc);
331 ec.Emit (OpCodes.Call, m);
333 ec.EmitInt ((int) State.Uninitialized);
334 ec.Emit (OpCodes.Bne_Un_S, label_init);
337 ec.Emit (OpCodes.Ret);
339 ec.MarkLabel (label_init);
341 new_storey.Emit (ec);
342 ec.Emit (OpCodes.Ret);
345 protected override bool DoFlowAnalysis (FlowAnalysisContext fc)
347 throw new NotImplementedException ();
350 public override Reachability MarkReachable (Reachability rc)
352 base.MarkReachable (rc);
353 return Reachability.CreateUnreachable ();
357 GetEnumeratorMethod (IteratorStorey host, FullNamedExpression returnType, MemberName name)
358 : base (host, null, returnType, Modifiers.DEBUGGER_HIDDEN, name, ToplevelBlock.Flags.CompilerGenerated | ToplevelBlock.Flags.NoFlowAnalysis)
362 public static GetEnumeratorMethod Create (IteratorStorey host, FullNamedExpression returnType, MemberName name)
364 return Create (host, returnType, name, null);
367 public static GetEnumeratorMethod Create (IteratorStorey host, FullNamedExpression returnType, MemberName name, Statement statement)
369 var m = new GetEnumeratorMethod (host, returnType, name);
370 var stmt = statement ?? new GetEnumeratorStatement (host, m);
371 m.block.AddStatement (stmt);
376 class DisposeMethod : StateMachineMethod
378 sealed class DisposeMethodStatement : Statement
382 public DisposeMethodStatement (Iterator iterator)
384 this.iterator = iterator;
385 this.loc = iterator.Location;
388 protected override void CloneTo (CloneContext clonectx, Statement target)
390 throw new NotSupportedException ();
393 public override bool Resolve (BlockContext ec)
398 protected override void DoEmit (EmitContext ec)
400 ec.CurrentAnonymousMethod = iterator;
401 iterator.EmitDispose (ec);
404 protected override bool DoFlowAnalysis (FlowAnalysisContext fc)
406 throw new NotImplementedException ();
410 public DisposeMethod (IteratorStorey host)
411 : base (host, null, new TypeExpression (host.Compiler.BuiltinTypes.Void, host.Location), Modifiers.PUBLIC | Modifiers.DEBUGGER_HIDDEN,
412 new MemberName ("Dispose", host.Location), ToplevelBlock.Flags.CompilerGenerated | ToplevelBlock.Flags.NoFlowAnalysis)
414 host.Members.Add (this);
416 Block.AddStatement (new DisposeMethodStatement (host.Iterator));
421 // Uses Method as method info
423 class DynamicMethodGroupExpr : MethodGroupExpr
425 readonly Method method;
427 public DynamicMethodGroupExpr (Method method, Location loc)
428 : base ((IList<MemberSpec>) null, null, loc)
430 this.method = method;
431 eclass = ExprClass.Unresolved;
434 protected override Expression DoResolve (ResolveContext ec)
436 Methods = new List<MemberSpec> (1) { method.Spec };
437 type = method.Parent.Definition;
438 InstanceExpression = new CompilerGeneratedThis (type, Location);
439 return base.DoResolve (ec);
443 class DynamicFieldExpr : FieldExpr
445 readonly Field field;
447 public DynamicFieldExpr (Field field, Location loc)
453 protected override Expression DoResolve (ResolveContext ec)
456 type = spec.MemberType;
457 InstanceExpression = new CompilerGeneratedThis (type, Location);
458 return base.DoResolve (ec);
462 public readonly Iterator Iterator;
464 List<HoistedParameter> hoisted_params_copy;
466 TypeExpr iterator_type_expr;
468 Field disposing_field;
470 TypeSpec generic_enumerator_type;
471 TypeSpec generic_enumerable_type;
473 public IteratorStorey (Iterator iterator)
474 : base (iterator.Container.ParametersBlock, iterator.Host,
475 iterator.OriginalMethod as MemberBase, iterator.OriginalMethod.CurrentTypeParameters, "Iterator", MemberKind.Class)
477 this.Iterator = iterator;
480 public Field CurrentField {
482 return current_field;
486 public Field DisposingField {
488 return disposing_field;
492 public IList<HoistedParameter> HoistedParameters {
493 get { return hoisted_params; }
496 protected override Constructor DefineDefaultConstructor (bool is_static)
498 var ctor = base.DefineDefaultConstructor (is_static);
499 ctor.ModFlags |= Modifiers.DEBUGGER_HIDDEN;
503 protected override TypeSpec[] ResolveBaseTypes (out FullNamedExpression base_class)
505 var mtype = Iterator.OriginalIteratorType;
507 mtype = Mutator.Mutate (mtype);
509 iterator_type_expr = new TypeExpression (mtype, Location);
511 var ifaces = new List<TypeSpec> (5);
512 if (Iterator.IsEnumerable) {
513 ifaces.Add (Compiler.BuiltinTypes.IEnumerable);
515 if (Module.PredefinedTypes.IEnumerableGeneric.Define ()) {
516 generic_enumerable_type = Module.PredefinedTypes.IEnumerableGeneric.TypeSpec.MakeGenericType (Module, new[] { mtype });
517 ifaces.Add (generic_enumerable_type);
521 ifaces.Add (Compiler.BuiltinTypes.IEnumerator);
522 ifaces.Add (Compiler.BuiltinTypes.IDisposable);
524 var ienumerator_generic = Module.PredefinedTypes.IEnumeratorGeneric;
525 if (ienumerator_generic.Define ()) {
526 generic_enumerator_type = ienumerator_generic.TypeSpec.MakeGenericType (Module, new [] { mtype });
527 ifaces.Add (generic_enumerator_type);
532 base_type = Compiler.BuiltinTypes.Object;
533 return ifaces.ToArray ();
536 protected override bool DoDefineMembers ()
538 current_field = AddCompilerGeneratedField ("$current", iterator_type_expr);
539 disposing_field = AddCompilerGeneratedField ("$disposing", new TypeExpression (Compiler.BuiltinTypes.Bool, Location));
541 if (Iterator.IsEnumerable && hoisted_params != null) {
543 // Iterators are independent, each GetEnumerator call has to
544 // create same enumerator therefore we have to keep original values
545 // around for re-initialization
547 hoisted_params_copy = new List<HoistedParameter> (hoisted_params.Count);
548 foreach (HoistedParameter hp in hoisted_params) {
551 // Don't create field copy for unmodified captured parameters
553 HoistedParameter hp_copy;
555 hp_copy = new HoistedParameter (hp, "<$>" + hp.Field.Name);
560 hoisted_params_copy.Add (hp_copy);
564 if (generic_enumerator_type != null)
565 Define_Current (true);
567 Define_Current (false);
568 new DisposeMethod (this);
571 if (Iterator.IsEnumerable) {
572 FullNamedExpression explicit_iface = new TypeExpression (Compiler.BuiltinTypes.IEnumerable, Location);
573 var name = new MemberName ("GetEnumerator", null, explicit_iface, Location.Null);
575 if (generic_enumerator_type != null) {
576 explicit_iface = new TypeExpression (generic_enumerable_type, Location);
577 var gname = new MemberName ("GetEnumerator", null, explicit_iface, Location.Null);
578 Method gget_enumerator = GetEnumeratorMethod.Create (this, new TypeExpression (generic_enumerator_type, Location), gname);
581 // Just call generic GetEnumerator implementation
583 var stmt = new Return (new Invocation (new DynamicMethodGroupExpr (gget_enumerator, Location), null), Location);
584 Method get_enumerator = GetEnumeratorMethod.Create (this, new TypeExpression (Compiler.BuiltinTypes.IEnumerator, Location), name, stmt);
586 Members.Add (get_enumerator);
587 Members.Add (gget_enumerator);
589 Members.Add (GetEnumeratorMethod.Create (this, new TypeExpression (Compiler.BuiltinTypes.IEnumerator, Location), name));
593 return base.DoDefineMembers ();
596 void Define_Current (bool is_generic)
599 FullNamedExpression explicit_iface;
602 explicit_iface = new TypeExpression (generic_enumerator_type, Location);
603 type = iterator_type_expr;
605 explicit_iface = new TypeExpression (Module.Compiler.BuiltinTypes.IEnumerator, Location);
606 type = new TypeExpression (Compiler.BuiltinTypes.Object, Location);
609 var name = new MemberName ("Current", null, explicit_iface, Location);
611 ToplevelBlock get_block = new ToplevelBlock (Compiler, ParametersCompiled.EmptyReadOnlyParameters, Location,
612 Block.Flags.CompilerGenerated | Block.Flags.NoFlowAnalysis);
613 get_block.AddStatement (new Return (new DynamicFieldExpr (CurrentField, Location), Location));
615 Property current = new Property (this, type, Modifiers.DEBUGGER_HIDDEN | Modifiers.COMPILER_GENERATED, name, null);
616 current.Get = new Property.GetMethod (current, Modifiers.COMPILER_GENERATED, null, Location);
617 current.Get.Block = get_block;
619 Members.Add (current);
624 Method reset = new Method (
625 this, new TypeExpression (Compiler.BuiltinTypes.Void, Location),
626 Modifiers.PUBLIC | Modifiers.DEBUGGER_HIDDEN | Modifiers.COMPILER_GENERATED,
627 new MemberName ("Reset", Location),
628 ParametersCompiled.EmptyReadOnlyParameters, null);
631 reset.Block = new ToplevelBlock (Compiler, reset.ParameterInfo, Location,
632 Block.Flags.CompilerGenerated | Block.Flags.NoFlowAnalysis);
634 TypeSpec ex_type = Module.PredefinedTypes.NotSupportedException.Resolve ();
638 reset.Block.AddStatement (new Throw (new New (new TypeExpression (ex_type, Location), null, Location), Location));
641 protected override void EmitHoistedParameters (EmitContext ec, List<HoistedParameter> hoisted)
643 base.EmitHoistedParameters (ec, hoisted);
644 if (hoisted_params_copy != null)
645 base.EmitHoistedParameters (ec, hoisted_params_copy);
649 public class StateMachineMethod : Method
651 readonly StateMachineInitializer expr;
653 public StateMachineMethod (StateMachine host, StateMachineInitializer expr, FullNamedExpression returnType,
654 Modifiers mod, MemberName name, ToplevelBlock.Flags blockFlags)
655 : base (host, returnType, mod | Modifiers.COMPILER_GENERATED,
656 name, ParametersCompiled.EmptyReadOnlyParameters, null)
659 Block = new ToplevelBlock (host.Compiler, ParametersCompiled.EmptyReadOnlyParameters, Location.Null, blockFlags);
662 public override EmitContext CreateEmitContext (ILGenerator ig, SourceMethodBuilder sourceMethod)
664 EmitContext ec = new EmitContext (this, ig, MemberType, sourceMethod);
665 ec.CurrentAnonymousMethod = expr;
667 if (expr is AsyncInitializer)
668 ec.With (BuilderContext.Options.AsyncBody, true);
674 public abstract class StateMachineInitializer : AnonymousExpression
676 sealed class MoveNextBodyStatement : Statement
678 readonly StateMachineInitializer state_machine;
680 public MoveNextBodyStatement (StateMachineInitializer stateMachine)
682 this.state_machine = stateMachine;
683 this.loc = stateMachine.Location;
686 protected override void CloneTo (CloneContext clonectx, Statement target)
688 throw new NotSupportedException ();
691 public override bool Resolve (BlockContext ec)
696 protected override void DoEmit (EmitContext ec)
698 state_machine.EmitMoveNext (ec);
701 public override void Emit (EmitContext ec)
703 // Don't create sequence point
707 protected override bool DoFlowAnalysis (FlowAnalysisContext fc)
709 return state_machine.ReturnType.Kind != MemberKind.Void;
712 public override Reachability MarkReachable (Reachability rc)
714 base.MarkReachable (rc);
716 if (state_machine.ReturnType.Kind != MemberKind.Void)
717 rc = Reachability.CreateUnreachable ();
723 public readonly TypeDefinition Host;
724 protected StateMachine storey;
727 // The state as we generate the machine
729 protected Label move_next_ok;
730 protected Label move_next_error;
731 LocalBuilder skip_finally;
732 protected LocalBuilder current_pc;
733 protected List<ResumableStatement> resume_points;
735 protected StateMachineInitializer (ParametersBlock block, TypeDefinition host, TypeSpec returnType)
736 : base (block, returnType, block.StartLocation)
743 public Label BodyEnd { get; set; }
745 public LocalBuilder CurrentPC
752 public LocalBuilder SkipFinally {
758 public override AnonymousMethodStorey Storey {
766 public int AddResumePoint (ResumableStatement stmt)
768 if (resume_points == null)
769 resume_points = new List<ResumableStatement> ();
771 resume_points.Add (stmt);
772 return resume_points.Count;
775 public override Expression CreateExpressionTree (ResolveContext ec)
777 throw new NotSupportedException ("ET");
780 protected virtual BlockContext CreateBlockContext (BlockContext bc)
782 var ctx = new BlockContext (bc, block, bc.ReturnType);
783 ctx.CurrentAnonymousMethod = this;
785 ctx.AssignmentInfoOffset = bc.AssignmentInfoOffset;
786 ctx.EnclosingLoop = bc.EnclosingLoop;
787 ctx.EnclosingLoopOrSwitch = bc.EnclosingLoopOrSwitch;
788 ctx.Switch = bc.Switch;
793 protected override Expression DoResolve (ResolveContext rc)
795 var bc = (BlockContext) rc;
796 var ctx = CreateBlockContext (bc);
800 if (!rc.IsInProbingMode) {
801 var move_next = new StateMachineMethod (storey, this, new TypeExpression (ReturnType, loc), Modifiers.PUBLIC, new MemberName ("MoveNext", loc), 0);
802 move_next.Block.AddStatement (new MoveNextBodyStatement (this));
803 storey.AddEntryMethod (move_next);
806 bc.AssignmentInfoOffset = ctx.AssignmentInfoOffset;
807 eclass = ExprClass.Value;
811 public override void Emit (EmitContext ec)
814 // Load state machine instance
816 storey.Instance.Emit (ec);
819 void EmitMoveNext_NoResumePoints (EmitContext ec)
822 ec.Emit (OpCodes.Ldfld, storey.PC.Spec);
825 ec.EmitInt ((int) IteratorStorey.State.After);
826 ec.Emit (OpCodes.Stfld, storey.PC.Spec);
828 // We only care if the PC is zero (start executing) or non-zero (don't do anything)
829 ec.Emit (OpCodes.Brtrue, move_next_error);
831 BodyEnd = ec.DefineLabel ();
833 var async_init = this as AsyncInitializer;
834 if (async_init != null)
835 ec.BeginExceptionBlock ();
837 block.EmitEmbedded (ec);
839 if (async_init != null)
840 async_init.EmitCatchBlock (ec);
842 ec.MarkLabel (BodyEnd);
844 EmitMoveNextEpilogue (ec);
846 ec.MarkLabel (move_next_error);
848 if (ReturnType.Kind != MemberKind.Void) {
850 ec.Emit (OpCodes.Ret);
853 ec.MarkLabel (move_next_ok);
856 void EmitMoveNext (EmitContext ec)
858 move_next_ok = ec.DefineLabel ();
859 move_next_error = ec.DefineLabel ();
861 if (resume_points == null) {
862 EmitMoveNext_NoResumePoints (ec);
866 current_pc = ec.GetTemporaryLocal (ec.BuiltinTypes.UInt);
868 ec.Emit (OpCodes.Ldfld, storey.PC.Spec);
869 ec.Emit (OpCodes.Stloc, current_pc);
871 // We're actually in state 'running', but this is as good a PC value as any if there's an abnormal exit
873 ec.EmitInt ((int) IteratorStorey.State.After);
874 ec.Emit (OpCodes.Stfld, storey.PC.Spec);
876 Label[] labels = new Label[1 + resume_points.Count];
877 labels[0] = ec.DefineLabel ();
879 bool need_skip_finally = false;
880 for (int i = 0; i < resume_points.Count; ++i) {
881 ResumableStatement s = resume_points[i];
882 need_skip_finally |= s is ExceptionStatement;
883 labels[i + 1] = s.PrepareForEmit (ec);
886 if (need_skip_finally) {
887 skip_finally = ec.GetTemporaryLocal (ec.BuiltinTypes.Bool);
889 ec.Emit (OpCodes.Stloc, skip_finally);
892 var async_init = this as AsyncInitializer;
893 if (async_init != null)
894 ec.BeginExceptionBlock ();
896 ec.Emit (OpCodes.Ldloc, current_pc);
897 ec.Emit (OpCodes.Switch, labels);
899 ec.Emit (async_init != null ? OpCodes.Leave : OpCodes.Br, move_next_error);
901 ec.MarkLabel (labels[0]);
903 BodyEnd = ec.DefineLabel ();
905 block.EmitEmbedded (ec);
907 ec.MarkLabel (BodyEnd);
909 if (async_init != null) {
910 async_init.EmitCatchBlock (ec);
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;