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)
166 protected override bool DoResolve (BlockContext bc)
168 iterator = bc.CurrentIterator;
169 return Yield.CheckContext (bc, loc);
172 protected override void DoEmit (EmitContext ec)
174 iterator.EmitYieldBreak (ec, unwind_protect);
177 protected override bool DoFlowAnalysis (FlowAnalysisContext fc)
182 public override Reachability MarkReachable (Reachability rc)
184 base.MarkReachable (rc);
185 return Reachability.CreateUnreachable ();
188 public override object Accept (StructuralVisitor visitor)
190 return visitor.Visit (this);
194 public abstract class StateMachine : AnonymousMethodStorey
198 Running = -3, // Used only in CurrentPC, never stored into $PC
205 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 (ResolveContext rc, LocalVariable local_info)
249 if (local_info.IsCompilerGenerated)
250 return base.GetVariableMangledName (rc, local_info);
253 // Special format which encodes original variable name and
254 // it's scope to support lifted variables debugging. This
255 // is same what csc does and allows to correctly set fields
256 // scope information (like ambiguity, out of scope, etc).
258 var id = rc.CurrentBlock.Explicit.GetDebugSymbolScopeIndex ();
259 return "<" + local_info.Name + ">__" + id;
263 class IteratorStorey : StateMachine
265 class GetEnumeratorMethod : StateMachineMethod
267 sealed class GetEnumeratorStatement : Statement
269 readonly IteratorStorey host;
270 readonly StateMachineMethod host_method;
272 Expression new_storey;
274 public GetEnumeratorStatement (IteratorStorey host, StateMachineMethod host_method)
277 this.host_method = host_method;
278 loc = host_method.Location;
281 protected override void CloneTo (CloneContext clonectx, Statement target)
283 throw new NotSupportedException ();
286 public override bool Resolve (BlockContext ec)
288 TypeExpression storey_type_expr = new TypeExpression (host.Definition, loc);
289 List<Expression> init = null;
290 if (host.hoisted_this != null) {
291 init = new List<Expression> (host.hoisted_params == null ? 1 : host.HoistedParameters.Count + 1);
292 HoistedThis ht = host.hoisted_this;
293 FieldExpr from = new FieldExpr (ht.Field, loc);
294 from.InstanceExpression = new CompilerGeneratedThis (ec.CurrentType, loc);
295 init.Add (new ElementInitializer (ht.Field.Name, from, loc));
298 if (host.hoisted_params != null) {
300 init = new List<Expression> (host.HoistedParameters.Count);
302 for (int i = 0; i < host.hoisted_params.Count; ++i) {
303 HoistedParameter hp = host.hoisted_params [i];
304 HoistedParameter hp_cp = host.hoisted_params_copy [i] ?? hp;
306 FieldExpr from = new FieldExpr (hp_cp.Field, loc);
307 from.InstanceExpression = new CompilerGeneratedThis (ec.CurrentType, loc);
309 init.Add (new ElementInitializer (hp.Field.Name, from, loc));
314 new_storey = new NewInitialize (storey_type_expr, null,
315 new CollectionOrObjectInitializers (init, loc), loc);
317 new_storey = new New (storey_type_expr, null, loc);
320 new_storey = new_storey.Resolve (ec);
321 if (new_storey != null)
322 new_storey = Convert.ImplicitConversionRequired (ec, new_storey, host_method.MemberType, loc);
327 protected override void DoEmit (EmitContext ec)
329 Label label_init = ec.DefineLabel ();
332 ec.Emit (OpCodes.Ldflda, host.PC.Spec);
333 ec.EmitInt ((int) State.Start);
334 ec.EmitInt ((int) State.Uninitialized);
336 var m = ec.Module.PredefinedMembers.InterlockedCompareExchange.Resolve (loc);
338 ec.Emit (OpCodes.Call, m);
340 ec.EmitInt ((int) State.Uninitialized);
341 ec.Emit (OpCodes.Bne_Un_S, label_init);
344 ec.Emit (OpCodes.Ret);
346 ec.MarkLabel (label_init);
348 new_storey.Emit (ec);
349 ec.Emit (OpCodes.Ret);
352 protected override bool DoFlowAnalysis (FlowAnalysisContext fc)
354 throw new NotImplementedException ();
357 public override Reachability MarkReachable (Reachability rc)
359 base.MarkReachable (rc);
360 return Reachability.CreateUnreachable ();
364 GetEnumeratorMethod (IteratorStorey host, FullNamedExpression returnType, MemberName name)
365 : base (host, null, returnType, Modifiers.DEBUGGER_HIDDEN, name, ToplevelBlock.Flags.CompilerGenerated | ToplevelBlock.Flags.NoFlowAnalysis)
369 public static GetEnumeratorMethod Create (IteratorStorey host, FullNamedExpression returnType, MemberName name)
371 return Create (host, returnType, name, null);
374 public static GetEnumeratorMethod Create (IteratorStorey host, FullNamedExpression returnType, MemberName name, Statement statement)
376 var m = new GetEnumeratorMethod (host, returnType, name);
377 var stmt = statement ?? new GetEnumeratorStatement (host, m);
378 m.block.AddStatement (stmt);
383 class DisposeMethod : StateMachineMethod
385 sealed class DisposeMethodStatement : Statement
389 public DisposeMethodStatement (Iterator iterator)
391 this.iterator = iterator;
392 this.loc = iterator.Location;
395 protected override void CloneTo (CloneContext clonectx, Statement target)
397 throw new NotSupportedException ();
400 public override bool Resolve (BlockContext ec)
405 protected override void DoEmit (EmitContext ec)
407 ec.CurrentAnonymousMethod = iterator;
408 iterator.EmitDispose (ec);
411 protected override bool DoFlowAnalysis (FlowAnalysisContext fc)
413 throw new NotImplementedException ();
417 public DisposeMethod (IteratorStorey host)
418 : base (host, null, new TypeExpression (host.Compiler.BuiltinTypes.Void, host.Location), Modifiers.PUBLIC | Modifiers.DEBUGGER_HIDDEN,
419 new MemberName ("Dispose", host.Location), ToplevelBlock.Flags.CompilerGenerated | ToplevelBlock.Flags.NoFlowAnalysis)
421 host.Members.Add (this);
423 Block.AddStatement (new DisposeMethodStatement (host.Iterator));
428 // Uses Method as method info
430 class DynamicMethodGroupExpr : MethodGroupExpr
432 readonly Method method;
434 public DynamicMethodGroupExpr (Method method, Location loc)
435 : base ((IList<MemberSpec>) null, null, loc)
437 this.method = method;
438 eclass = ExprClass.Unresolved;
441 protected override Expression DoResolve (ResolveContext ec)
443 Methods = new List<MemberSpec> (1) { method.Spec };
444 type = method.Parent.Definition;
445 InstanceExpression = new CompilerGeneratedThis (type, Location);
446 return base.DoResolve (ec);
450 class DynamicFieldExpr : FieldExpr
452 readonly Field field;
454 public DynamicFieldExpr (Field field, Location loc)
460 protected override Expression DoResolve (ResolveContext ec)
463 type = spec.MemberType;
464 InstanceExpression = new CompilerGeneratedThis (type, Location);
465 return base.DoResolve (ec);
469 public readonly Iterator Iterator;
471 List<HoistedParameter> hoisted_params_copy;
473 TypeExpr iterator_type_expr;
475 Field disposing_field;
477 TypeSpec generic_enumerator_type;
478 TypeSpec generic_enumerable_type;
480 public IteratorStorey (Iterator iterator)
481 : base (iterator.Container.ParametersBlock, iterator.Host,
482 iterator.OriginalMethod as MemberBase, iterator.OriginalMethod.CurrentTypeParameters, "Iterator", MemberKind.Class)
484 this.Iterator = iterator;
487 public Field CurrentField {
489 return current_field;
493 public Field DisposingField {
495 return disposing_field;
499 public IList<HoistedParameter> HoistedParameters {
500 get { return hoisted_params; }
503 protected override Constructor DefineDefaultConstructor (bool is_static)
505 var ctor = base.DefineDefaultConstructor (is_static);
506 ctor.ModFlags |= Modifiers.DEBUGGER_HIDDEN;
510 protected override TypeSpec[] ResolveBaseTypes (out FullNamedExpression base_class)
512 var mtype = Iterator.OriginalIteratorType;
514 mtype = Mutator.Mutate (mtype);
516 iterator_type_expr = new TypeExpression (mtype, Location);
518 var ifaces = new List<TypeSpec> (5);
519 if (Iterator.IsEnumerable) {
520 ifaces.Add (Compiler.BuiltinTypes.IEnumerable);
522 if (Module.PredefinedTypes.IEnumerableGeneric.Define ()) {
523 generic_enumerable_type = Module.PredefinedTypes.IEnumerableGeneric.TypeSpec.MakeGenericType (Module, new[] { mtype });
524 ifaces.Add (generic_enumerable_type);
528 ifaces.Add (Compiler.BuiltinTypes.IEnumerator);
529 ifaces.Add (Compiler.BuiltinTypes.IDisposable);
531 var ienumerator_generic = Module.PredefinedTypes.IEnumeratorGeneric;
532 if (ienumerator_generic.Define ()) {
533 generic_enumerator_type = ienumerator_generic.TypeSpec.MakeGenericType (Module, new [] { mtype });
534 ifaces.Add (generic_enumerator_type);
539 base_type = Compiler.BuiltinTypes.Object;
540 return ifaces.ToArray ();
543 protected override bool DoDefineMembers ()
545 current_field = AddCompilerGeneratedField ("$current", iterator_type_expr);
546 disposing_field = AddCompilerGeneratedField ("$disposing", new TypeExpression (Compiler.BuiltinTypes.Bool, Location));
548 if (Iterator.IsEnumerable && hoisted_params != null) {
550 // Iterators are independent, each GetEnumerator call has to
551 // create same enumerator therefore we have to keep original values
552 // around for re-initialization
554 hoisted_params_copy = new List<HoistedParameter> (hoisted_params.Count);
555 foreach (HoistedParameter hp in hoisted_params) {
558 // Don't create field copy for unmodified captured parameters
560 HoistedParameter hp_copy;
562 hp_copy = new HoistedParameter (hp, "<$>" + hp.Field.Name);
567 hoisted_params_copy.Add (hp_copy);
571 if (generic_enumerator_type != null)
572 Define_Current (true);
574 Define_Current (false);
575 new DisposeMethod (this);
578 if (Iterator.IsEnumerable) {
579 FullNamedExpression explicit_iface = new TypeExpression (Compiler.BuiltinTypes.IEnumerable, Location);
580 var name = new MemberName ("GetEnumerator", null, explicit_iface, Location.Null);
582 if (generic_enumerator_type != null) {
583 explicit_iface = new TypeExpression (generic_enumerable_type, Location);
584 var gname = new MemberName ("GetEnumerator", null, explicit_iface, Location.Null);
585 Method gget_enumerator = GetEnumeratorMethod.Create (this, new TypeExpression (generic_enumerator_type, Location), gname);
588 // Just call generic GetEnumerator implementation
590 var stmt = new Return (new Invocation (new DynamicMethodGroupExpr (gget_enumerator, Location), null), Location);
591 Method get_enumerator = GetEnumeratorMethod.Create (this, new TypeExpression (Compiler.BuiltinTypes.IEnumerator, Location), name, stmt);
593 Members.Add (get_enumerator);
594 Members.Add (gget_enumerator);
596 Members.Add (GetEnumeratorMethod.Create (this, new TypeExpression (Compiler.BuiltinTypes.IEnumerator, Location), name));
600 return base.DoDefineMembers ();
603 void Define_Current (bool is_generic)
606 FullNamedExpression explicit_iface;
609 explicit_iface = new TypeExpression (generic_enumerator_type, Location);
610 type = iterator_type_expr;
612 explicit_iface = new TypeExpression (Module.Compiler.BuiltinTypes.IEnumerator, Location);
613 type = new TypeExpression (Compiler.BuiltinTypes.Object, Location);
616 var name = new MemberName ("Current", null, explicit_iface, Location);
618 ToplevelBlock get_block = new ToplevelBlock (Compiler, ParametersCompiled.EmptyReadOnlyParameters, Location,
619 Block.Flags.CompilerGenerated | Block.Flags.NoFlowAnalysis);
620 get_block.AddStatement (new Return (new DynamicFieldExpr (CurrentField, Location), Location));
622 Property current = new Property (this, type, Modifiers.DEBUGGER_HIDDEN | Modifiers.COMPILER_GENERATED, name, null);
623 current.Get = new Property.GetMethod (current, Modifiers.COMPILER_GENERATED, null, Location);
624 current.Get.Block = get_block;
626 Members.Add (current);
631 Method reset = new Method (
632 this, new TypeExpression (Compiler.BuiltinTypes.Void, Location),
633 Modifiers.PUBLIC | Modifiers.DEBUGGER_HIDDEN | Modifiers.COMPILER_GENERATED,
634 new MemberName ("Reset", Location),
635 ParametersCompiled.EmptyReadOnlyParameters, null);
638 reset.Block = new ToplevelBlock (Compiler, reset.ParameterInfo, Location,
639 Block.Flags.CompilerGenerated | Block.Flags.NoFlowAnalysis);
641 TypeSpec ex_type = Module.PredefinedTypes.NotSupportedException.Resolve ();
645 reset.Block.AddStatement (new Throw (new New (new TypeExpression (ex_type, Location), null, Location), Location));
648 protected override void EmitHoistedParameters (EmitContext ec, List<HoistedParameter> hoisted)
650 base.EmitHoistedParameters (ec, hoisted);
651 if (hoisted_params_copy != null)
652 base.EmitHoistedParameters (ec, hoisted_params_copy);
656 public class StateMachineMethod : Method
658 readonly StateMachineInitializer expr;
660 public StateMachineMethod (StateMachine host, StateMachineInitializer expr, FullNamedExpression returnType,
661 Modifiers mod, MemberName name, ToplevelBlock.Flags blockFlags)
662 : base (host, returnType, mod | Modifiers.COMPILER_GENERATED,
663 name, ParametersCompiled.EmptyReadOnlyParameters, null)
666 Block = new ToplevelBlock (host.Compiler, ParametersCompiled.EmptyReadOnlyParameters, Location.Null, blockFlags);
669 public override EmitContext CreateEmitContext (ILGenerator ig, SourceMethodBuilder sourceMethod)
671 EmitContext ec = new EmitContext (this, ig, MemberType, sourceMethod);
672 ec.CurrentAnonymousMethod = expr;
674 if (expr is AsyncInitializer)
675 ec.With (BuilderContext.Options.AsyncBody, true);
681 public abstract class StateMachineInitializer : AnonymousExpression
683 sealed class MoveNextBodyStatement : Statement
685 readonly StateMachineInitializer state_machine;
687 public MoveNextBodyStatement (StateMachineInitializer stateMachine)
689 this.state_machine = stateMachine;
690 this.loc = stateMachine.Location;
693 protected override void CloneTo (CloneContext clonectx, Statement target)
695 throw new NotSupportedException ();
698 public override bool Resolve (BlockContext ec)
703 protected override void DoEmit (EmitContext ec)
705 state_machine.EmitMoveNext (ec);
708 public override void Emit (EmitContext ec)
710 // Don't create sequence point
714 protected override bool DoFlowAnalysis (FlowAnalysisContext fc)
716 return state_machine.ReturnType.Kind != MemberKind.Void;
719 public override Reachability MarkReachable (Reachability rc)
721 base.MarkReachable (rc);
723 if (state_machine.ReturnType.Kind != MemberKind.Void)
724 rc = Reachability.CreateUnreachable ();
730 public readonly TypeDefinition Host;
731 protected StateMachine storey;
734 // The state as we generate the machine
736 protected Label move_next_ok;
737 protected Label move_next_error;
738 LocalBuilder skip_finally;
739 protected LocalBuilder current_pc;
740 protected List<ResumableStatement> resume_points;
742 protected StateMachineInitializer (ParametersBlock block, TypeDefinition host, TypeSpec returnType)
743 : base (block, returnType, block.StartLocation)
750 public Label BodyEnd { get; set; }
752 public LocalBuilder CurrentPC
759 public LocalBuilder SkipFinally {
765 public override AnonymousMethodStorey Storey {
773 public int AddResumePoint (ResumableStatement stmt)
775 if (resume_points == null)
776 resume_points = new List<ResumableStatement> ();
778 resume_points.Add (stmt);
779 return resume_points.Count;
782 public override Expression CreateExpressionTree (ResolveContext ec)
784 throw new NotSupportedException ("ET");
787 protected virtual BlockContext CreateBlockContext (BlockContext bc)
789 var ctx = new BlockContext (bc, block, bc.ReturnType);
790 ctx.CurrentAnonymousMethod = this;
792 ctx.AssignmentInfoOffset = bc.AssignmentInfoOffset;
793 ctx.EnclosingLoop = bc.EnclosingLoop;
794 ctx.EnclosingLoopOrSwitch = bc.EnclosingLoopOrSwitch;
795 ctx.Switch = bc.Switch;
800 protected override Expression DoResolve (ResolveContext rc)
802 var bc = (BlockContext) rc;
803 var ctx = CreateBlockContext (bc);
807 if (!rc.IsInProbingMode) {
808 var move_next = new StateMachineMethod (storey, this, new TypeExpression (ReturnType, loc), Modifiers.PUBLIC, new MemberName ("MoveNext", loc), 0);
809 move_next.Block.AddStatement (new MoveNextBodyStatement (this));
810 storey.AddEntryMethod (move_next);
813 bc.AssignmentInfoOffset = ctx.AssignmentInfoOffset;
814 eclass = ExprClass.Value;
818 public override void Emit (EmitContext ec)
821 // Load state machine instance
823 storey.Instance.Emit (ec);
826 void EmitMoveNext_NoResumePoints (EmitContext ec)
829 ec.Emit (OpCodes.Ldfld, storey.PC.Spec);
832 ec.EmitInt ((int) IteratorStorey.State.After);
833 ec.Emit (OpCodes.Stfld, storey.PC.Spec);
835 // We only care if the PC is zero (start executing) or non-zero (don't do anything)
836 ec.Emit (OpCodes.Brtrue, move_next_error);
838 BodyEnd = ec.DefineLabel ();
840 var async_init = this as AsyncInitializer;
841 if (async_init != null)
842 ec.BeginExceptionBlock ();
844 block.EmitEmbedded (ec);
846 if (async_init != null)
847 async_init.EmitCatchBlock (ec);
849 ec.MarkLabel (BodyEnd);
851 EmitMoveNextEpilogue (ec);
853 ec.MarkLabel (move_next_error);
855 if (ReturnType.Kind != MemberKind.Void) {
857 ec.Emit (OpCodes.Ret);
860 ec.MarkLabel (move_next_ok);
863 void EmitMoveNext (EmitContext ec)
865 move_next_ok = ec.DefineLabel ();
866 move_next_error = ec.DefineLabel ();
868 if (resume_points == null) {
869 EmitMoveNext_NoResumePoints (ec);
873 current_pc = ec.GetTemporaryLocal (ec.BuiltinTypes.UInt);
875 ec.Emit (OpCodes.Ldfld, storey.PC.Spec);
876 ec.Emit (OpCodes.Stloc, current_pc);
878 // We're actually in state 'running', but this is as good a PC value as any if there's an abnormal exit
880 ec.EmitInt ((int) IteratorStorey.State.After);
881 ec.Emit (OpCodes.Stfld, storey.PC.Spec);
883 Label[] labels = new Label[1 + resume_points.Count];
884 labels[0] = ec.DefineLabel ();
886 bool need_skip_finally = false;
887 for (int i = 0; i < resume_points.Count; ++i) {
888 ResumableStatement s = resume_points[i];
889 need_skip_finally |= s is ExceptionStatement;
890 labels[i + 1] = s.PrepareForEmit (ec);
893 if (need_skip_finally) {
894 skip_finally = ec.GetTemporaryLocal (ec.BuiltinTypes.Bool);
896 ec.Emit (OpCodes.Stloc, skip_finally);
899 var async_init = this as AsyncInitializer;
900 if (async_init != null)
901 ec.BeginExceptionBlock ();
903 ec.Emit (OpCodes.Ldloc, current_pc);
904 ec.Emit (OpCodes.Switch, labels);
906 ec.Emit (async_init != null ? OpCodes.Leave : OpCodes.Br, move_next_error);
908 ec.MarkLabel (labels[0]);
910 BodyEnd = ec.DefineLabel ();
912 block.EmitEmbedded (ec);
914 ec.MarkLabel (BodyEnd);
916 if (async_init != null) {
917 async_init.EmitCatchBlock (ec);
920 ec.Mark (Block.Original.EndLocation);
922 ec.EmitInt ((int) IteratorStorey.State.After);
923 ec.Emit (OpCodes.Stfld, storey.PC.Spec);
925 EmitMoveNextEpilogue (ec);
927 ec.MarkLabel (move_next_error);
929 if (ReturnType.Kind != MemberKind.Void) {
931 ec.Emit (OpCodes.Ret);
934 ec.MarkLabel (move_next_ok);
936 if (ReturnType.Kind != MemberKind.Void) {
938 ec.Emit (OpCodes.Ret);
942 protected virtual void EmitMoveNextEpilogue (EmitContext ec)
946 public void EmitLeave (EmitContext ec, bool unwind_protect)
949 ec.Emit (unwind_protect ? OpCodes.Leave : OpCodes.Br, move_next_ok);
953 // Called back from YieldStatement
955 public virtual void InjectYield (EmitContext ec, Expression expr, int resume_pc, bool unwind_protect, Label resume_point)
958 // Guard against being disposed meantime
960 Label disposed = ec.DefineLabel ();
961 var iterator = storey as IteratorStorey;
962 if (iterator != null) {
964 ec.Emit (OpCodes.Ldfld, iterator.DisposingField.Spec);
965 ec.Emit (OpCodes.Brtrue_S, disposed);
969 // store resume program-counter
972 ec.EmitInt (resume_pc);
973 ec.Emit (OpCodes.Stfld, storey.PC.Spec);
975 if (iterator != null) {
976 ec.MarkLabel (disposed);
979 // mark finally blocks as disabled
980 if (unwind_protect && skip_finally != null) {
982 ec.Emit (OpCodes.Stloc, skip_finally);
986 public void SetStateMachine (StateMachine stateMachine)
988 this.storey = stateMachine;
993 // Iterators are implemented as state machine blocks
995 public class Iterator : StateMachineInitializer
997 sealed class TryFinallyBlockProxyStatement : Statement
999 TryFinallyBlock block;
1002 public TryFinallyBlockProxyStatement (Iterator iterator, TryFinallyBlock block)
1004 this.iterator = iterator;
1008 protected override void CloneTo (CloneContext clonectx, Statement target)
1010 throw new NotSupportedException ();
1013 protected override bool DoFlowAnalysis (FlowAnalysisContext fc)
1015 throw new NotSupportedException ();
1018 protected override void DoEmit (EmitContext ec)
1021 // Restore redirection for any captured variables
1023 ec.CurrentAnonymousMethod = iterator;
1025 using (ec.With (BuilderContext.Options.OmitDebugInfo, !ec.HasMethodSymbolBuilder)) {
1026 block.EmitFinallyBody (ec);
1031 public readonly IMethodData OriginalMethod;
1032 public readonly bool IsEnumerable;
1033 public readonly TypeSpec OriginalIteratorType;
1034 int finally_hosts_counter;
1036 public Iterator (ParametersBlock block, IMethodData method, TypeDefinition host, TypeSpec iterator_type, bool is_enumerable)
1037 : base (block, host, host.Compiler.BuiltinTypes.Bool)
1039 this.OriginalMethod = method;
1040 this.OriginalIteratorType = iterator_type;
1041 this.IsEnumerable = is_enumerable;
1042 this.type = method.ReturnType;
1047 public ToplevelBlock Container {
1048 get { return OriginalMethod.Block; }
1051 public override string ContainerType {
1052 get { return "iterator"; }
1055 public override bool IsIterator {
1056 get { return true; }
1061 public Method CreateFinallyHost (TryFinallyBlock block)
1063 var method = new Method (storey, new TypeExpression (storey.Compiler.BuiltinTypes.Void, loc),
1064 Modifiers.COMPILER_GENERATED, new MemberName (CompilerGeneratedContainer.MakeName (null, null, "Finally", finally_hosts_counter++), loc),
1065 ParametersCompiled.EmptyReadOnlyParameters, null);
1067 method.Block = new ToplevelBlock (method.Compiler, method.ParameterInfo, loc,
1068 ToplevelBlock.Flags.CompilerGenerated | ToplevelBlock.Flags.NoFlowAnalysis);
1070 method.Block.AddStatement (new TryFinallyBlockProxyStatement (this, block));
1072 // Cannot it add to storey because it'd be emitted before nested
1073 // anonoymous methods which could capture shared variable
1078 public void EmitYieldBreak (EmitContext ec, bool unwind_protect)
1080 ec.Emit (unwind_protect ? OpCodes.Leave : OpCodes.Br, move_next_error);
1083 public override string GetSignatureForError ()
1085 return OriginalMethod.GetSignatureForError ();
1088 public override void Emit (EmitContext ec)
1091 // Load Iterator storey instance
1093 storey.Instance.Emit (ec);
1096 // Initialize iterator PC when it's unitialized
1099 ec.Emit (OpCodes.Dup);
1100 ec.EmitInt ((int)IteratorStorey.State.Uninitialized);
1102 var field = storey.PC.Spec;
1103 if (storey.MemberName.IsGeneric) {
1104 field = MemberCache.GetMember (Storey.Instance.Type, field);
1107 ec.Emit (OpCodes.Stfld, field);
1111 public void EmitDispose (EmitContext ec)
1113 if (resume_points == null)
1116 Label end = ec.DefineLabel ();
1118 Label[] labels = null;
1119 for (int i = 0; i < resume_points.Count; ++i) {
1120 ResumableStatement s = resume_points[i];
1121 Label ret = s.PrepareForDispose (ec, end);
1122 if (ret.Equals (end) && labels == null)
1124 if (labels == null) {
1125 labels = new Label[resume_points.Count + 1];
1126 for (int j = 0; j <= i; ++j)
1130 labels[i + 1] = ret;
1133 if (labels != null) {
1134 current_pc = ec.GetTemporaryLocal (ec.BuiltinTypes.UInt);
1136 ec.Emit (OpCodes.Ldfld, storey.PC.Spec);
1137 ec.Emit (OpCodes.Stloc, current_pc);
1142 ec.Emit (OpCodes.Stfld, ((IteratorStorey) storey).DisposingField.Spec);
1145 ec.EmitInt ((int) IteratorStorey.State.After);
1146 ec.Emit (OpCodes.Stfld, storey.PC.Spec);
1148 if (labels != null) {
1149 //SymbolWriter.StartIteratorDispatcher (ec.ig);
1150 ec.Emit (OpCodes.Ldloc, current_pc);
1151 ec.Emit (OpCodes.Switch, labels);
1152 //SymbolWriter.EndIteratorDispatcher (ec.ig);
1154 foreach (ResumableStatement s in resume_points)
1155 s.EmitForDispose (ec, current_pc, end, true);
1161 public override void EmitStatement (EmitContext ec)
1163 throw new NotImplementedException ();
1166 public override void InjectYield (EmitContext ec, Expression expr, int resume_pc, bool unwind_protect, Label resume_point)
1168 // Store the new value into current
1169 var fe = new FieldExpr (((IteratorStorey) storey).CurrentField, loc);
1170 fe.InstanceExpression = new CompilerGeneratedThis (storey.CurrentType, loc);
1171 fe.EmitAssign (ec, expr, false, false);
1173 base.InjectYield (ec, expr, resume_pc, unwind_protect, resume_point);
1175 EmitLeave (ec, unwind_protect);
1177 ec.MarkLabel (resume_point);
1180 public static void CreateIterator (IMethodData method, TypeDefinition parent, Modifiers modifiers)
1183 TypeSpec iterator_type;
1185 TypeSpec ret = method.ReturnType;
1189 if (!CheckType (ret, parent, out iterator_type, out is_enumerable)) {
1190 parent.Compiler.Report.Error (1624, method.Location,
1191 "The body of `{0}' cannot be an iterator block " +
1192 "because `{1}' is not an iterator interface type",
1193 method.GetSignatureForError (),
1194 ret.GetSignatureForError ());
1198 ParametersCompiled parameters = method.ParameterInfo;
1199 for (int i = 0; i < parameters.Count; i++) {
1200 Parameter p = parameters [i];
1201 Parameter.Modifier mod = p.ModFlags;
1202 if ((mod & Parameter.Modifier.RefOutMask) != 0) {
1203 parent.Compiler.Report.Error (1623, p.Location,
1204 "Iterators cannot have ref or out parameters");
1208 if (p is ArglistParameter) {
1209 parent.Compiler.Report.Error (1636, method.Location,
1210 "__arglist is not allowed in parameter list of iterators");
1214 if (parameters.Types [i].IsPointer) {
1215 parent.Compiler.Report.Error (1637, p.Location,
1216 "Iterators cannot have unsafe parameters or yield types");
1221 if ((modifiers & Modifiers.UNSAFE) != 0) {
1222 Expression.UnsafeInsideIteratorError (parent.Compiler.Report, method.Location);
1225 method.Block = method.Block.ConvertToIterator (method, parent, iterator_type, is_enumerable);
1228 static bool CheckType (TypeSpec ret, TypeContainer parent, out TypeSpec original_iterator_type, out bool is_enumerable)
1230 original_iterator_type = null;
1231 is_enumerable = false;
1233 if (ret.BuiltinType == BuiltinTypeSpec.Type.IEnumerable) {
1234 original_iterator_type = parent.Compiler.BuiltinTypes.Object;
1235 is_enumerable = true;
1238 if (ret.BuiltinType == BuiltinTypeSpec.Type.IEnumerator) {
1239 original_iterator_type = parent.Compiler.BuiltinTypes.Object;
1240 is_enumerable = false;
1244 InflatedTypeSpec inflated = ret as InflatedTypeSpec;
1245 if (inflated == null)
1248 var member_definition = inflated.MemberDefinition;
1249 PredefinedType ptype = parent.Module.PredefinedTypes.IEnumerableGeneric;
1251 if (ptype.Define () && ptype.TypeSpec.MemberDefinition == member_definition) {
1252 original_iterator_type = inflated.TypeArguments[0];
1253 is_enumerable = true;
1257 ptype = parent.Module.PredefinedTypes.IEnumeratorGeneric;
1258 if (ptype.Define () && ptype.TypeSpec.MemberDefinition == member_definition) {
1259 original_iterator_type = inflated.TypeArguments[0];
1260 is_enumerable = false;