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;
33 TryCatch inside_catch_block;
35 protected YieldStatement (Expression expr, Location l)
41 public Expression Expr {
42 get { return this.expr; }
45 protected override void CloneTo (CloneContext clonectx, Statement t)
47 var target = (YieldStatement<T>) t;
48 target.expr = expr.Clone (clonectx);
51 protected override void DoEmit (EmitContext ec)
53 machine_initializer.InjectYield (ec, expr, resume_pc, unwind_protect, resume_point);
56 protected override bool DoFlowAnalysis (FlowAnalysisContext fc)
58 expr.FlowAnalysis (fc);
60 RegisterResumePoint ();
65 public override bool Resolve (BlockContext bc)
67 expr = expr.Resolve (bc);
71 machine_initializer = bc.CurrentAnonymousMethod as T;
72 inside_try_block = bc.CurrentTryBlock;
73 inside_catch_block = bc.CurrentTryCatch;
77 public void RegisterResumePoint ()
82 if (inside_try_block == null) {
83 resume_pc = machine_initializer.AddResumePoint (this);
85 resume_pc = inside_try_block.AddResumePoint (this, resume_pc, machine_initializer, inside_catch_block);
86 unwind_protect = true;
87 inside_try_block = null;
92 public class Yield : YieldStatement<Iterator>
94 public Yield (Expression expr, Location loc)
99 public static bool CheckContext (BlockContext bc, Location loc)
101 if (!bc.CurrentAnonymousMethod.IsIterator) {
102 bc.Report.Error (1621, loc,
103 "The yield statement cannot be used inside anonymous method blocks");
107 if (bc.HasSet (ResolveContext.Options.FinallyScope)) {
108 bc.Report.Error (1625, loc, "Cannot yield in the body of a finally clause");
115 public override bool Resolve (BlockContext bc)
117 if (!CheckContext (bc, loc))
120 if (bc.HasAny (ResolveContext.Options.TryWithCatchScope)) {
121 bc.Report.Error (1626, loc, "Cannot yield a value in the body of a try block with a catch clause");
124 if (bc.HasSet (ResolveContext.Options.CatchScope)) {
125 bc.Report.Error (1631, loc, "Cannot yield a value in the body of a catch clause");
128 if (!base.Resolve (bc))
131 var otype = bc.CurrentIterator.OriginalIteratorType;
132 if (expr.Type != otype) {
133 expr = Convert.ImplicitConversionRequired (bc, expr, otype, loc);
141 public override object Accept (StructuralVisitor visitor)
143 return visitor.Visit (this);
147 public class YieldBreak : ExitStatement
151 public YieldBreak (Location l)
156 protected override bool IsLocalExit {
162 protected override void CloneTo (CloneContext clonectx, Statement target)
164 throw new NotSupportedException ();
167 protected override bool DoResolve (BlockContext bc)
169 iterator = bc.CurrentIterator;
170 return Yield.CheckContext (bc, loc);
173 protected override void DoEmit (EmitContext ec)
175 iterator.EmitYieldBreak (ec, unwind_protect);
178 protected override bool DoFlowAnalysis (FlowAnalysisContext fc)
183 public override Reachability MarkReachable (Reachability rc)
185 base.MarkReachable (rc);
186 return Reachability.CreateUnreachable ();
189 public override object Accept (StructuralVisitor visitor)
191 return visitor.Visit (this);
195 public abstract class StateMachine : AnonymousMethodStorey
199 Running = -3, // Used only in CurrentPC, never stored into $PC
206 StateMachineMethod method;
208 protected StateMachine (ParametersBlock block, TypeDefinition parent, MemberBase host, TypeParameters tparams, string name, MemberKind kind)
209 : base (block, parent, host, tparams, name, kind)
211 OriginalTypeParameters = tparams;
216 public TypeParameters OriginalTypeParameters { get; private set; }
218 public StateMachineMethod StateMachineMethod {
232 public void AddEntryMethod (StateMachineMethod method)
234 if (this.method != null)
235 throw new InternalErrorException ();
237 this.method = method;
238 Members.Add (method);
241 protected override bool DoDefineMembers ()
243 pc_field = AddCompilerGeneratedField ("$PC", new TypeExpression (Compiler.BuiltinTypes.Int, Location));
245 return base.DoDefineMembers ();
248 protected override string GetVariableMangledName (ResolveContext rc, LocalVariable local_info)
250 if (local_info.IsCompilerGenerated)
251 return base.GetVariableMangledName (rc, local_info);
254 // Special format which encodes original variable name and
255 // it's scope to support lifted variables debugging. This
256 // is same what csc does and allows to correctly set fields
257 // scope information (like ambiguity, out of scope, etc).
259 var id = rc.CurrentBlock.Explicit.GetDebugSymbolScopeIndex ();
260 return "<" + local_info.Name + ">__" + id;
264 class IteratorStorey : StateMachine
266 class GetEnumeratorMethod : StateMachineMethod
268 sealed class GetEnumeratorStatement : Statement
270 readonly IteratorStorey host;
271 readonly StateMachineMethod host_method;
273 Expression new_storey;
275 public GetEnumeratorStatement (IteratorStorey host, StateMachineMethod host_method)
278 this.host_method = host_method;
279 loc = host_method.Location;
282 protected override void CloneTo (CloneContext clonectx, Statement target)
284 throw new NotSupportedException ();
287 public override bool Resolve (BlockContext ec)
289 TypeExpression storey_type_expr = new TypeExpression (host.Definition, loc);
290 List<Expression> init = null;
291 if (host.hoisted_this != null) {
292 init = new List<Expression> (host.hoisted_params == null ? 1 : host.HoistedParameters.Count + 1);
293 HoistedThis ht = host.hoisted_this;
294 FieldExpr from = new FieldExpr (ht.Field, loc);
295 from.InstanceExpression = new CompilerGeneratedThis (ec.CurrentType, loc);
296 init.Add (new ElementInitializer (ht.Field.Name, from, loc));
299 if (host.hoisted_params != null) {
301 init = new List<Expression> (host.HoistedParameters.Count);
303 for (int i = 0; i < host.hoisted_params.Count; ++i) {
304 HoistedParameter hp = host.hoisted_params [i];
305 HoistedParameter hp_cp = host.hoisted_params_copy [i] ?? hp;
307 FieldExpr from = new FieldExpr (hp_cp.Field, loc);
308 from.InstanceExpression = new CompilerGeneratedThis (ec.CurrentType, loc);
310 init.Add (new ElementInitializer (hp.Field.Name, from, loc));
315 new_storey = new NewInitialize (storey_type_expr, null,
316 new CollectionOrObjectInitializers (init, loc), loc);
318 new_storey = new New (storey_type_expr, null, loc);
321 new_storey = new_storey.Resolve (ec);
322 if (new_storey != null)
323 new_storey = Convert.ImplicitConversionRequired (ec, new_storey, host_method.MemberType, loc);
328 protected override void DoEmit (EmitContext ec)
330 Label label_init = ec.DefineLabel ();
333 ec.Emit (OpCodes.Ldflda, host.PC.Spec);
334 ec.EmitInt ((int) State.Start);
335 ec.EmitInt ((int) State.Uninitialized);
337 var m = ec.Module.PredefinedMembers.InterlockedCompareExchange.Resolve (loc);
339 ec.Emit (OpCodes.Call, m);
341 ec.EmitInt ((int) State.Uninitialized);
342 ec.Emit (OpCodes.Bne_Un_S, label_init);
345 ec.Emit (OpCodes.Ret);
347 ec.MarkLabel (label_init);
349 new_storey.Emit (ec);
350 ec.Emit (OpCodes.Ret);
353 protected override bool DoFlowAnalysis (FlowAnalysisContext fc)
355 throw new NotImplementedException ();
358 public override Reachability MarkReachable (Reachability rc)
360 base.MarkReachable (rc);
361 return Reachability.CreateUnreachable ();
365 GetEnumeratorMethod (IteratorStorey host, FullNamedExpression returnType, MemberName name)
366 : base (host, null, returnType, Modifiers.DEBUGGER_HIDDEN, name, ToplevelBlock.Flags.CompilerGenerated | ToplevelBlock.Flags.NoFlowAnalysis)
370 public static GetEnumeratorMethod Create (IteratorStorey host, FullNamedExpression returnType, MemberName name)
372 return Create (host, returnType, name, null);
375 public static GetEnumeratorMethod Create (IteratorStorey host, FullNamedExpression returnType, MemberName name, Statement statement)
377 var m = new GetEnumeratorMethod (host, returnType, name);
378 var stmt = statement ?? new GetEnumeratorStatement (host, m);
379 m.block.AddStatement (stmt);
384 class DisposeMethod : StateMachineMethod
386 sealed class DisposeMethodStatement : Statement
390 public DisposeMethodStatement (Iterator iterator)
392 this.iterator = iterator;
393 this.loc = iterator.Location;
396 protected override void CloneTo (CloneContext clonectx, Statement target)
398 throw new NotSupportedException ();
401 public override bool Resolve (BlockContext ec)
406 protected override void DoEmit (EmitContext ec)
408 ec.CurrentAnonymousMethod = iterator;
409 iterator.EmitDispose (ec);
412 protected override bool DoFlowAnalysis (FlowAnalysisContext fc)
414 throw new NotImplementedException ();
418 public DisposeMethod (IteratorStorey host)
419 : base (host, null, new TypeExpression (host.Compiler.BuiltinTypes.Void, host.Location), Modifiers.PUBLIC | Modifiers.DEBUGGER_HIDDEN,
420 new MemberName ("Dispose", host.Location), ToplevelBlock.Flags.CompilerGenerated | ToplevelBlock.Flags.NoFlowAnalysis)
422 host.Members.Add (this);
424 Block.AddStatement (new DisposeMethodStatement (host.Iterator));
429 // Uses Method as method info
431 class DynamicMethodGroupExpr : MethodGroupExpr
433 readonly Method method;
435 public DynamicMethodGroupExpr (Method method, Location loc)
436 : base ((IList<MemberSpec>) null, null, loc)
438 this.method = method;
439 eclass = ExprClass.Unresolved;
442 protected override Expression DoResolve (ResolveContext ec)
444 Methods = new List<MemberSpec> (1) { method.Spec };
445 type = method.Parent.Definition;
446 InstanceExpression = new CompilerGeneratedThis (type, Location);
447 return base.DoResolve (ec);
451 class DynamicFieldExpr : FieldExpr
453 readonly Field field;
455 public DynamicFieldExpr (Field field, Location loc)
461 protected override Expression DoResolve (ResolveContext ec)
464 type = spec.MemberType;
465 InstanceExpression = new CompilerGeneratedThis (type, Location);
466 return base.DoResolve (ec);
470 public readonly Iterator Iterator;
472 List<HoistedParameter> hoisted_params_copy;
474 TypeExpr iterator_type_expr;
476 Field disposing_field;
478 TypeSpec generic_enumerator_type;
479 TypeSpec generic_enumerable_type;
481 public IteratorStorey (Iterator iterator)
482 : base (iterator.Container.ParametersBlock, iterator.Host,
483 iterator.OriginalMethod as MemberBase, iterator.OriginalMethod.CurrentTypeParameters, "Iterator", MemberKind.Class)
485 this.Iterator = iterator;
488 public Field CurrentField {
490 return current_field;
494 public Field DisposingField {
496 return disposing_field;
500 public IList<HoistedParameter> HoistedParameters {
501 get { return hoisted_params; }
504 protected override Constructor DefineDefaultConstructor (bool is_static)
506 var ctor = base.DefineDefaultConstructor (is_static);
507 ctor.ModFlags |= Modifiers.DEBUGGER_HIDDEN;
511 protected override TypeSpec[] ResolveBaseTypes (out FullNamedExpression base_class)
513 var mtype = Iterator.OriginalIteratorType;
515 mtype = Mutator.Mutate (mtype);
517 iterator_type_expr = new TypeExpression (mtype, Location);
519 var ifaces = new List<TypeSpec> (5);
520 if (Iterator.IsEnumerable) {
521 ifaces.Add (Compiler.BuiltinTypes.IEnumerable);
523 if (Module.PredefinedTypes.IEnumerableGeneric.Define ()) {
524 generic_enumerable_type = Module.PredefinedTypes.IEnumerableGeneric.TypeSpec.MakeGenericType (Module, new[] { mtype });
525 ifaces.Add (generic_enumerable_type);
529 ifaces.Add (Compiler.BuiltinTypes.IEnumerator);
530 ifaces.Add (Compiler.BuiltinTypes.IDisposable);
532 var ienumerator_generic = Module.PredefinedTypes.IEnumeratorGeneric;
533 if (ienumerator_generic.Define ()) {
534 generic_enumerator_type = ienumerator_generic.TypeSpec.MakeGenericType (Module, new [] { mtype });
535 ifaces.Add (generic_enumerator_type);
540 base_type = Compiler.BuiltinTypes.Object;
541 return ifaces.ToArray ();
544 protected override bool DoDefineMembers ()
546 current_field = AddCompilerGeneratedField ("$current", iterator_type_expr);
547 disposing_field = AddCompilerGeneratedField ("$disposing", new TypeExpression (Compiler.BuiltinTypes.Bool, Location));
549 if (Iterator.IsEnumerable && hoisted_params != null) {
551 // Iterators are independent, each GetEnumerator call has to
552 // create same enumerator therefore we have to keep original values
553 // around for re-initialization
555 hoisted_params_copy = new List<HoistedParameter> (hoisted_params.Count);
556 foreach (HoistedParameter hp in hoisted_params) {
559 // Don't create field copy for unmodified captured parameters
561 HoistedParameter hp_copy;
563 hp_copy = new HoistedParameter (hp, "<$>" + hp.Field.Name);
568 hoisted_params_copy.Add (hp_copy);
572 if (generic_enumerator_type != null)
573 Define_Current (true);
575 Define_Current (false);
576 new DisposeMethod (this);
579 if (Iterator.IsEnumerable) {
580 FullNamedExpression explicit_iface = new TypeExpression (Compiler.BuiltinTypes.IEnumerable, Location);
581 var name = new MemberName ("GetEnumerator", null, explicit_iface, Location.Null);
583 if (generic_enumerator_type != null) {
584 explicit_iface = new TypeExpression (generic_enumerable_type, Location);
585 var gname = new MemberName ("GetEnumerator", null, explicit_iface, Location.Null);
586 Method gget_enumerator = GetEnumeratorMethod.Create (this, new TypeExpression (generic_enumerator_type, Location), gname);
589 // Just call generic GetEnumerator implementation
591 var stmt = new Return (new Invocation (new DynamicMethodGroupExpr (gget_enumerator, Location), null), Location);
592 Method get_enumerator = GetEnumeratorMethod.Create (this, new TypeExpression (Compiler.BuiltinTypes.IEnumerator, Location), name, stmt);
594 Members.Add (get_enumerator);
595 Members.Add (gget_enumerator);
597 Members.Add (GetEnumeratorMethod.Create (this, new TypeExpression (Compiler.BuiltinTypes.IEnumerator, Location), name));
601 return base.DoDefineMembers ();
604 void Define_Current (bool is_generic)
607 FullNamedExpression explicit_iface;
610 explicit_iface = new TypeExpression (generic_enumerator_type, Location);
611 type = iterator_type_expr;
613 explicit_iface = new TypeExpression (Module.Compiler.BuiltinTypes.IEnumerator, Location);
614 type = new TypeExpression (Compiler.BuiltinTypes.Object, Location);
617 var name = new MemberName ("Current", null, explicit_iface, Location);
619 ToplevelBlock get_block = new ToplevelBlock (Compiler, ParametersCompiled.EmptyReadOnlyParameters, Location,
620 Block.Flags.CompilerGenerated | Block.Flags.NoFlowAnalysis);
621 get_block.AddStatement (new Return (new DynamicFieldExpr (CurrentField, Location), Location));
623 Property current = new Property (this, type, Modifiers.DEBUGGER_HIDDEN | Modifiers.COMPILER_GENERATED, name, null);
624 current.Get = new Property.GetMethod (current, Modifiers.COMPILER_GENERATED, null, Location);
625 current.Get.Block = get_block;
627 Members.Add (current);
632 Method reset = new Method (
633 this, new TypeExpression (Compiler.BuiltinTypes.Void, Location),
634 Modifiers.PUBLIC | Modifiers.DEBUGGER_HIDDEN | Modifiers.COMPILER_GENERATED,
635 new MemberName ("Reset", Location),
636 ParametersCompiled.EmptyReadOnlyParameters, null);
639 reset.Block = new ToplevelBlock (Compiler, reset.ParameterInfo, Location,
640 Block.Flags.CompilerGenerated | Block.Flags.NoFlowAnalysis);
642 TypeSpec ex_type = Module.PredefinedTypes.NotSupportedException.Resolve ();
646 reset.Block.AddStatement (new Throw (new New (new TypeExpression (ex_type, Location), null, Location), Location));
649 protected override void EmitHoistedParameters (EmitContext ec, List<HoistedParameter> hoisted)
651 base.EmitHoistedParameters (ec, hoisted);
652 if (hoisted_params_copy != null)
653 base.EmitHoistedParameters (ec, hoisted_params_copy);
657 public class StateMachineMethod : Method
659 readonly StateMachineInitializer expr;
661 public StateMachineMethod (StateMachine host, StateMachineInitializer expr, FullNamedExpression returnType,
662 Modifiers mod, MemberName name, ToplevelBlock.Flags blockFlags)
663 : base (host, returnType, mod | Modifiers.COMPILER_GENERATED,
664 name, ParametersCompiled.EmptyReadOnlyParameters, null)
667 Block = new ToplevelBlock (host.Compiler, ParametersCompiled.EmptyReadOnlyParameters, Location.Null, blockFlags);
670 public override EmitContext CreateEmitContext (ILGenerator ig, SourceMethodBuilder sourceMethod)
672 EmitContext ec = new EmitContext (this, ig, MemberType, sourceMethod);
673 ec.CurrentAnonymousMethod = expr;
675 if (expr is AsyncInitializer)
676 ec.With (BuilderContext.Options.AsyncBody, true);
682 public abstract class StateMachineInitializer : AnonymousExpression
684 sealed class MoveNextBodyStatement : Statement
686 readonly StateMachineInitializer state_machine;
688 public MoveNextBodyStatement (StateMachineInitializer stateMachine)
690 this.state_machine = stateMachine;
691 this.loc = stateMachine.Location;
694 protected override void CloneTo (CloneContext clonectx, Statement target)
696 throw new NotSupportedException ();
699 public override bool Resolve (BlockContext ec)
704 protected override void DoEmit (EmitContext ec)
706 state_machine.EmitMoveNext (ec);
709 public override void Emit (EmitContext ec)
711 // Don't create sequence point
715 protected override bool DoFlowAnalysis (FlowAnalysisContext fc)
717 return state_machine.ReturnType.Kind != MemberKind.Void;
720 public override Reachability MarkReachable (Reachability rc)
722 base.MarkReachable (rc);
724 if (state_machine.ReturnType.Kind != MemberKind.Void)
725 rc = Reachability.CreateUnreachable ();
731 public readonly TypeDefinition Host;
732 protected StateMachine storey;
735 // The state as we generate the machine
737 protected Label move_next_ok;
738 protected Label move_next_error;
739 LocalBuilder skip_finally;
740 protected LocalBuilder current_pc;
741 protected List<ResumableStatement> resume_points;
743 protected StateMachineInitializer (ParametersBlock block, TypeDefinition host, TypeSpec returnType)
744 : base (block, returnType, block.StartLocation)
751 public Label BodyEnd { get; set; }
753 public LocalBuilder CurrentPC
760 public LocalBuilder SkipFinally {
766 public override AnonymousMethodStorey Storey {
774 public int AddResumePoint (ResumableStatement stmt)
776 if (resume_points == null)
777 resume_points = new List<ResumableStatement> ();
779 resume_points.Add (stmt);
780 return resume_points.Count;
783 public override Expression CreateExpressionTree (ResolveContext ec)
785 throw new NotSupportedException ("ET");
788 protected virtual BlockContext CreateBlockContext (BlockContext bc)
790 var ctx = new BlockContext (bc, block, bc.ReturnType);
791 ctx.CurrentAnonymousMethod = this;
793 ctx.AssignmentInfoOffset = bc.AssignmentInfoOffset;
794 ctx.EnclosingLoop = bc.EnclosingLoop;
795 ctx.EnclosingLoopOrSwitch = bc.EnclosingLoopOrSwitch;
796 ctx.Switch = bc.Switch;
801 protected override Expression DoResolve (ResolveContext rc)
803 var bc = (BlockContext) rc;
804 var ctx = CreateBlockContext (bc);
808 if (!rc.IsInProbingMode) {
809 var move_next = new StateMachineMethod (storey, this, new TypeExpression (ReturnType, loc), Modifiers.PUBLIC, new MemberName ("MoveNext", loc), 0);
810 move_next.Block.AddStatement (new MoveNextBodyStatement (this));
811 storey.AddEntryMethod (move_next);
814 bc.AssignmentInfoOffset = ctx.AssignmentInfoOffset;
815 eclass = ExprClass.Value;
819 public override void Emit (EmitContext ec)
822 // Load state machine instance
824 storey.Instance.Emit (ec);
827 void EmitMoveNext_NoResumePoints (EmitContext ec)
830 ec.Emit (OpCodes.Ldfld, storey.PC.Spec);
833 ec.EmitInt ((int) IteratorStorey.State.After);
834 ec.Emit (OpCodes.Stfld, storey.PC.Spec);
836 // We only care if the PC is zero (start executing) or non-zero (don't do anything)
837 ec.Emit (OpCodes.Brtrue, move_next_error);
839 BodyEnd = ec.DefineLabel ();
841 var async_init = this as AsyncInitializer;
842 if (async_init != null)
843 ec.BeginExceptionBlock ();
845 block.EmitEmbedded (ec);
847 if (async_init != null)
848 async_init.EmitCatchBlock (ec);
850 ec.MarkLabel (BodyEnd);
852 EmitMoveNextEpilogue (ec);
854 ec.MarkLabel (move_next_error);
856 if (ReturnType.Kind != MemberKind.Void) {
858 ec.Emit (OpCodes.Ret);
861 ec.MarkLabel (move_next_ok);
864 void EmitMoveNext (EmitContext ec)
866 move_next_ok = ec.DefineLabel ();
867 move_next_error = ec.DefineLabel ();
869 if (resume_points == null) {
870 EmitMoveNext_NoResumePoints (ec);
874 current_pc = ec.GetTemporaryLocal (ec.BuiltinTypes.UInt);
876 ec.Emit (OpCodes.Ldfld, storey.PC.Spec);
877 ec.Emit (OpCodes.Stloc, current_pc);
879 // We're actually in state 'running', but this is as good a PC value as any if there's an abnormal exit
881 ec.EmitInt ((int) IteratorStorey.State.After);
882 ec.Emit (OpCodes.Stfld, storey.PC.Spec);
884 Label[] labels = new Label[1 + resume_points.Count];
885 labels[0] = ec.DefineLabel ();
887 bool need_skip_finally = false;
888 for (int i = 0; i < resume_points.Count; ++i) {
889 ResumableStatement s = resume_points[i];
890 need_skip_finally |= s is ExceptionStatement;
891 labels[i + 1] = s.PrepareForEmit (ec);
894 if (need_skip_finally) {
895 skip_finally = ec.GetTemporaryLocal (ec.BuiltinTypes.Bool);
897 ec.Emit (OpCodes.Stloc, skip_finally);
900 var async_init = this as AsyncInitializer;
901 if (async_init != null)
902 ec.BeginExceptionBlock ();
904 ec.Emit (OpCodes.Ldloc, current_pc);
905 ec.Emit (OpCodes.Switch, labels);
907 ec.Emit (async_init != null ? OpCodes.Leave : OpCodes.Br, move_next_error);
909 ec.MarkLabel (labels[0]);
911 BodyEnd = ec.DefineLabel ();
913 block.EmitEmbedded (ec);
915 ec.MarkLabel (BodyEnd);
917 if (async_init != null) {
918 async_init.EmitCatchBlock (ec);
921 ec.Mark (Block.Original.EndLocation);
923 ec.EmitInt ((int) IteratorStorey.State.After);
924 ec.Emit (OpCodes.Stfld, storey.PC.Spec);
926 EmitMoveNextEpilogue (ec);
928 ec.MarkLabel (move_next_error);
930 if (ReturnType.Kind != MemberKind.Void) {
932 ec.Emit (OpCodes.Ret);
935 ec.MarkLabel (move_next_ok);
937 if (ReturnType.Kind != MemberKind.Void) {
939 ec.Emit (OpCodes.Ret);
943 protected virtual void EmitMoveNextEpilogue (EmitContext ec)
947 public void EmitLeave (EmitContext ec, bool unwind_protect)
950 ec.Emit (unwind_protect ? OpCodes.Leave : OpCodes.Br, move_next_ok);
954 // Called back from YieldStatement
956 public virtual void InjectYield (EmitContext ec, Expression expr, int resume_pc, bool unwind_protect, Label resume_point)
959 // Guard against being disposed meantime
961 Label disposed = ec.DefineLabel ();
962 var iterator = storey as IteratorStorey;
963 if (iterator != null) {
965 ec.Emit (OpCodes.Ldfld, iterator.DisposingField.Spec);
966 ec.Emit (OpCodes.Brtrue_S, disposed);
970 // store resume program-counter
973 ec.EmitInt (resume_pc);
974 ec.Emit (OpCodes.Stfld, storey.PC.Spec);
976 if (iterator != null) {
977 ec.MarkLabel (disposed);
980 // mark finally blocks as disabled
981 if (unwind_protect && skip_finally != null) {
983 ec.Emit (OpCodes.Stloc, skip_finally);
987 public void SetStateMachine (StateMachine stateMachine)
989 this.storey = stateMachine;
994 // Iterators are implemented as state machine blocks
996 public class Iterator : StateMachineInitializer
998 sealed class TryFinallyBlockProxyStatement : Statement
1000 TryFinallyBlock block;
1003 public TryFinallyBlockProxyStatement (Iterator iterator, TryFinallyBlock block)
1005 this.iterator = iterator;
1009 protected override void CloneTo (CloneContext clonectx, Statement target)
1011 throw new NotSupportedException ();
1014 protected override bool DoFlowAnalysis (FlowAnalysisContext fc)
1016 throw new NotSupportedException ();
1019 protected override void DoEmit (EmitContext ec)
1022 // Restore redirection for any captured variables
1024 ec.CurrentAnonymousMethod = iterator;
1026 using (ec.With (BuilderContext.Options.OmitDebugInfo, !ec.HasMethodSymbolBuilder)) {
1027 block.EmitFinallyBody (ec);
1032 public readonly IMethodData OriginalMethod;
1033 public readonly bool IsEnumerable;
1034 public readonly TypeSpec OriginalIteratorType;
1035 int finally_hosts_counter;
1037 public Iterator (ParametersBlock block, IMethodData method, TypeDefinition host, TypeSpec iterator_type, bool is_enumerable)
1038 : base (block, host, host.Compiler.BuiltinTypes.Bool)
1040 this.OriginalMethod = method;
1041 this.OriginalIteratorType = iterator_type;
1042 this.IsEnumerable = is_enumerable;
1043 this.type = method.ReturnType;
1048 public ToplevelBlock Container {
1049 get { return OriginalMethod.Block; }
1052 public override string ContainerType {
1053 get { return "iterator"; }
1056 public override bool IsIterator {
1057 get { return true; }
1062 public Method CreateFinallyHost (TryFinallyBlock block)
1064 var method = new Method (storey, new TypeExpression (storey.Compiler.BuiltinTypes.Void, loc),
1065 Modifiers.COMPILER_GENERATED, new MemberName (CompilerGeneratedContainer.MakeName (null, null, "Finally", finally_hosts_counter++), loc),
1066 ParametersCompiled.EmptyReadOnlyParameters, null);
1068 method.Block = new ToplevelBlock (method.Compiler, method.ParameterInfo, loc,
1069 ToplevelBlock.Flags.CompilerGenerated | ToplevelBlock.Flags.NoFlowAnalysis);
1071 method.Block.AddStatement (new TryFinallyBlockProxyStatement (this, block));
1073 // Cannot it add to storey because it'd be emitted before nested
1074 // anonoymous methods which could capture shared variable
1079 public void EmitYieldBreak (EmitContext ec, bool unwind_protect)
1081 ec.Emit (unwind_protect ? OpCodes.Leave : OpCodes.Br, move_next_error);
1084 public override string GetSignatureForError ()
1086 return OriginalMethod.GetSignatureForError ();
1089 public override void Emit (EmitContext ec)
1092 // Load Iterator storey instance
1094 storey.Instance.Emit (ec);
1097 // Initialize iterator PC when it's unitialized
1100 ec.Emit (OpCodes.Dup);
1101 ec.EmitInt ((int)IteratorStorey.State.Uninitialized);
1103 var field = storey.PC.Spec;
1104 if (storey.MemberName.IsGeneric) {
1105 field = MemberCache.GetMember (Storey.Instance.Type, field);
1108 ec.Emit (OpCodes.Stfld, field);
1112 public void EmitDispose (EmitContext ec)
1114 if (resume_points == null)
1117 Label end = ec.DefineLabel ();
1119 Label[] labels = null;
1120 for (int i = 0; i < resume_points.Count; ++i) {
1121 ResumableStatement s = resume_points[i];
1122 Label ret = s.PrepareForDispose (ec, end);
1123 if (ret.Equals (end) && labels == null)
1125 if (labels == null) {
1126 labels = new Label[resume_points.Count + 1];
1127 for (int j = 0; j <= i; ++j)
1131 labels[i + 1] = ret;
1134 if (labels != null) {
1135 current_pc = ec.GetTemporaryLocal (ec.BuiltinTypes.UInt);
1137 ec.Emit (OpCodes.Ldfld, storey.PC.Spec);
1138 ec.Emit (OpCodes.Stloc, current_pc);
1143 ec.Emit (OpCodes.Stfld, ((IteratorStorey) storey).DisposingField.Spec);
1146 ec.EmitInt ((int) IteratorStorey.State.After);
1147 ec.Emit (OpCodes.Stfld, storey.PC.Spec);
1149 if (labels != null) {
1150 //SymbolWriter.StartIteratorDispatcher (ec.ig);
1151 ec.Emit (OpCodes.Ldloc, current_pc);
1152 ec.Emit (OpCodes.Switch, labels);
1153 //SymbolWriter.EndIteratorDispatcher (ec.ig);
1155 foreach (ResumableStatement s in resume_points)
1156 s.EmitForDispose (ec, current_pc, end, true);
1162 public override void EmitStatement (EmitContext ec)
1164 throw new NotImplementedException ();
1167 public override void InjectYield (EmitContext ec, Expression expr, int resume_pc, bool unwind_protect, Label resume_point)
1169 // Store the new value into current
1170 var fe = new FieldExpr (((IteratorStorey) storey).CurrentField, loc);
1171 fe.InstanceExpression = new CompilerGeneratedThis (storey.CurrentType, loc);
1172 fe.EmitAssign (ec, expr, false, false);
1174 base.InjectYield (ec, expr, resume_pc, unwind_protect, resume_point);
1176 EmitLeave (ec, unwind_protect);
1178 ec.MarkLabel (resume_point);
1181 public static void CreateIterator (IMethodData method, TypeDefinition parent, Modifiers modifiers)
1184 TypeSpec iterator_type;
1186 TypeSpec ret = method.ReturnType;
1190 if (!CheckType (ret, parent, out iterator_type, out is_enumerable)) {
1191 parent.Compiler.Report.Error (1624, method.Location,
1192 "The body of `{0}' cannot be an iterator block " +
1193 "because `{1}' is not an iterator interface type",
1194 method.GetSignatureForError (),
1195 ret.GetSignatureForError ());
1199 ParametersCompiled parameters = method.ParameterInfo;
1200 for (int i = 0; i < parameters.Count; i++) {
1201 Parameter p = parameters [i];
1202 Parameter.Modifier mod = p.ModFlags;
1203 if ((mod & Parameter.Modifier.RefOutMask) != 0) {
1204 parent.Compiler.Report.Error (1623, p.Location,
1205 "Iterators cannot have ref or out parameters");
1209 if (p is ArglistParameter) {
1210 parent.Compiler.Report.Error (1636, method.Location,
1211 "__arglist is not allowed in parameter list of iterators");
1215 if (parameters.Types [i].IsPointer) {
1216 parent.Compiler.Report.Error (1637, p.Location,
1217 "Iterators cannot have unsafe parameters or yield types");
1222 if ((modifiers & Modifiers.UNSAFE) != 0) {
1223 parent.Compiler.Report.Error (1629, method.Location, "Unsafe code may not appear in iterators");
1226 method.Block = method.Block.ConvertToIterator (method, parent, iterator_type, is_enumerable);
1229 static bool CheckType (TypeSpec ret, TypeContainer parent, out TypeSpec original_iterator_type, out bool is_enumerable)
1231 original_iterator_type = null;
1232 is_enumerable = false;
1234 if (ret.BuiltinType == BuiltinTypeSpec.Type.IEnumerable) {
1235 original_iterator_type = parent.Compiler.BuiltinTypes.Object;
1236 is_enumerable = true;
1239 if (ret.BuiltinType == BuiltinTypeSpec.Type.IEnumerator) {
1240 original_iterator_type = parent.Compiler.BuiltinTypes.Object;
1241 is_enumerable = false;
1245 InflatedTypeSpec inflated = ret as InflatedTypeSpec;
1246 if (inflated == null)
1249 var member_definition = inflated.MemberDefinition;
1250 PredefinedType ptype = parent.Module.PredefinedTypes.IEnumerableGeneric;
1252 if (ptype.Define () && ptype.TypeSpec.MemberDefinition == member_definition) {
1253 original_iterator_type = inflated.TypeArguments[0];
1254 is_enumerable = true;
1258 ptype = parent.Module.PredefinedTypes.IEnumeratorGeneric;
1259 if (ptype.Define () && ptype.TypeSpec.MemberDefinition == member_definition) {
1260 original_iterator_type = inflated.TypeArguments[0];
1261 is_enumerable = false;