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 // Flow analysis for Yield.
19 using System.Collections.Generic;
22 using IKVM.Reflection.Emit;
24 using System.Reflection.Emit;
29 public abstract class YieldStatement<T> : ResumableStatement where T : StateMachineInitializer
31 protected Expression expr;
32 protected bool unwind_protect;
33 protected T machine_initializer;
36 protected YieldStatement (Expression expr, Location l)
42 public Expression Expr {
43 get { return this.expr; }
46 protected override void CloneTo (CloneContext clonectx, Statement t)
48 var target = (YieldStatement<T>) t;
49 target.expr = expr.Clone (clonectx);
52 protected override void DoEmit (EmitContext ec)
54 machine_initializer.InjectYield (ec, expr, resume_pc, unwind_protect, resume_point);
57 public override bool Resolve (BlockContext bc)
59 expr = expr.Resolve (bc);
63 machine_initializer = bc.CurrentAnonymousMethod as T;
65 if (!bc.CurrentBranching.CurrentUsageVector.IsUnreachable)
66 unwind_protect = bc.CurrentBranching.AddResumePoint (this, out resume_pc);
72 public class Yield : YieldStatement<Iterator>
74 public Yield (Expression expr, Location loc)
79 public static bool CheckContext (ResolveContext ec, Location loc)
81 if (!ec.CurrentAnonymousMethod.IsIterator) {
82 ec.Report.Error (1621, loc,
83 "The yield statement cannot be used inside anonymous method blocks");
90 public override bool Resolve (BlockContext bc)
92 if (!CheckContext (bc, loc))
95 if (!base.Resolve (bc))
98 var otype = bc.CurrentIterator.OriginalIteratorType;
99 if (expr.Type != otype) {
100 expr = Convert.ImplicitConversionRequired (bc, expr, otype, loc);
108 public override object Accept (StructuralVisitor visitor)
110 return visitor.Visit (this);
114 public class YieldBreak : ExitStatement
118 public YieldBreak (Location l)
123 public override void Error_FinallyClause (Report Report)
125 Report.Error (1625, loc, "Cannot yield in the body of a finally clause");
128 protected override void CloneTo (CloneContext clonectx, Statement target)
130 throw new NotSupportedException ();
133 protected override bool DoResolve (BlockContext ec)
135 iterator = ec.CurrentIterator;
136 return Yield.CheckContext (ec, loc);
139 protected override void DoEmit (EmitContext ec)
141 iterator.EmitYieldBreak (ec, unwind_protect);
144 public override object Accept (StructuralVisitor visitor)
146 return visitor.Visit (this);
150 public abstract class StateMachine : AnonymousMethodStorey
154 Running = -3, // Used only in CurrentPC, never stored into $PC
161 StateMachineMethod method;
163 protected StateMachine (Block block, TypeContainer parent, MemberBase host, TypeParameter[] tparams, string name)
164 : base (block, parent, host, tparams, name)
170 public StateMachineMethod StateMachineMethod {
184 public void AddEntryMethod (StateMachineMethod method)
186 if (this.method != null)
187 throw new InternalErrorException ();
189 this.method = method;
193 protected override bool DoDefineMembers ()
195 pc_field = AddCompilerGeneratedField ("$PC", new TypeExpression (Compiler.BuiltinTypes.Int, Location));
197 return base.DoDefineMembers ();
201 class IteratorStorey : StateMachine
203 class GetEnumeratorMethod : StateMachineMethod
205 sealed class GetEnumeratorStatement : Statement
207 readonly IteratorStorey host;
208 readonly StateMachineMethod host_method;
210 Expression new_storey;
212 public GetEnumeratorStatement (IteratorStorey host, StateMachineMethod host_method)
215 this.host_method = host_method;
216 loc = host_method.Location;
219 protected override void CloneTo (CloneContext clonectx, Statement target)
221 throw new NotSupportedException ();
224 public override bool Resolve (BlockContext ec)
226 TypeExpression storey_type_expr = new TypeExpression (host.Definition, loc);
227 List<Expression> init = null;
228 if (host.hoisted_this != null) {
229 init = new List<Expression> (host.hoisted_params == null ? 1 : host.HoistedParameters.Count + 1);
230 HoistedThis ht = host.hoisted_this;
231 FieldExpr from = new FieldExpr (ht.Field, loc);
232 from.InstanceExpression = new CompilerGeneratedThis (ec.CurrentType, loc);
233 init.Add (new ElementInitializer (ht.Field.Name, from, loc));
236 if (host.hoisted_params != null) {
238 init = new List<Expression> (host.HoistedParameters.Count);
240 for (int i = 0; i < host.hoisted_params.Count; ++i) {
241 HoistedParameter hp = host.hoisted_params [i];
242 HoistedParameter hp_cp = host.hoisted_params_copy [i];
244 FieldExpr from = new FieldExpr (hp_cp.Field, loc);
245 from.InstanceExpression = new CompilerGeneratedThis (ec.CurrentType, loc);
247 init.Add (new ElementInitializer (hp.Field.Name, from, loc));
252 new_storey = new NewInitialize (storey_type_expr, null,
253 new CollectionOrObjectInitializers (init, loc), loc);
255 new_storey = new New (storey_type_expr, null, loc);
258 new_storey = new_storey.Resolve (ec);
259 if (new_storey != null)
260 new_storey = Convert.ImplicitConversionRequired (ec, new_storey, host_method.MemberType, loc);
262 ec.CurrentBranching.CurrentUsageVector.Goto ();
266 protected override void DoEmit (EmitContext ec)
268 Label label_init = ec.DefineLabel ();
271 ec.Emit (OpCodes.Ldflda, host.PC.Spec);
272 ec.EmitInt ((int) State.Start);
273 ec.EmitInt ((int) State.Uninitialized);
275 var m = ec.Module.PredefinedMembers.InterlockedCompareExchange.Resolve (loc);
277 ec.Emit (OpCodes.Call, m);
279 ec.EmitInt ((int) State.Uninitialized);
280 ec.Emit (OpCodes.Bne_Un_S, label_init);
283 ec.Emit (OpCodes.Ret);
285 ec.MarkLabel (label_init);
287 new_storey.Emit (ec);
288 ec.Emit (OpCodes.Ret);
292 public GetEnumeratorMethod (IteratorStorey host, FullNamedExpression returnType, MemberName name)
293 : base (host, null, returnType, Modifiers.DEBUGGER_HIDDEN, name)
295 Block.AddStatement (new GetEnumeratorStatement (host, this));
299 class DisposeMethod : StateMachineMethod
301 sealed class DisposeMethodStatement : Statement
305 public DisposeMethodStatement (Iterator iterator)
307 this.iterator = iterator;
308 this.loc = iterator.Location;
311 protected override void CloneTo (CloneContext clonectx, Statement target)
313 throw new NotSupportedException ();
316 public override bool Resolve (BlockContext ec)
321 protected override void DoEmit (EmitContext ec)
323 ec.CurrentAnonymousMethod = iterator;
324 iterator.EmitDispose (ec);
328 public DisposeMethod (IteratorStorey host)
329 : base (host, null, new TypeExpression (host.Compiler.BuiltinTypes.Void, host.Location), Modifiers.PUBLIC | Modifiers.DEBUGGER_HIDDEN,
330 new MemberName ("Dispose", host.Location))
332 host.AddMethod (this);
334 Block.AddStatement (new DisposeMethodStatement (host.Iterator));
339 // Uses Method as method info
341 class DynamicMethodGroupExpr : MethodGroupExpr
343 readonly Method method;
345 public DynamicMethodGroupExpr (Method method, Location loc)
346 : base ((IList<MemberSpec>) null, null, loc)
348 this.method = method;
349 eclass = ExprClass.Unresolved;
352 protected override Expression DoResolve (ResolveContext ec)
354 Methods = new List<MemberSpec> (1) { method.Spec };
355 type = method.Parent.Definition;
356 InstanceExpression = new CompilerGeneratedThis (type, Location);
357 return base.DoResolve (ec);
361 class DynamicFieldExpr : FieldExpr
363 readonly Field field;
365 public DynamicFieldExpr (Field field, Location loc)
371 protected override Expression DoResolve (ResolveContext ec)
374 type = spec.MemberType;
375 InstanceExpression = new CompilerGeneratedThis (type, Location);
376 return base.DoResolve (ec);
380 public readonly Iterator Iterator;
382 List<HoistedParameter> hoisted_params_copy;
384 TypeExpr iterator_type_expr;
386 Field disposing_field;
389 TypeExpr enumerator_type;
390 TypeExpr enumerable_type;
391 TypeArguments generic_args;
392 TypeExpr generic_enumerator_type;
393 TypeExpr generic_enumerable_type;
395 public IteratorStorey (Iterator iterator)
396 : base (iterator.Container.ParametersBlock, iterator.Host,
397 iterator.OriginalMethod as MemberBase, iterator.GenericMethod == null ? null : iterator.GenericMethod.CurrentTypeParameters, "Iterator")
399 this.Iterator = iterator;
402 public Field CurrentField {
404 return current_field;
408 public Field DisposingField {
410 return disposing_field;
414 public IList<HoistedParameter> HoistedParameters {
415 get { return hoisted_params; }
418 protected override TypeSpec[] ResolveBaseTypes (out FullNamedExpression base_class)
420 var mtype = Iterator.OriginalIteratorType;
422 mtype = Mutator.Mutate (mtype);
424 iterator_type_expr = new TypeExpression (mtype, Location);
425 generic_args = new TypeArguments (iterator_type_expr);
427 var list = new List<FullNamedExpression> ();
428 if (Iterator.IsEnumerable) {
429 enumerable_type = new TypeExpression (Compiler.BuiltinTypes.IEnumerable, Location);
430 list.Add (enumerable_type);
432 if (Module.PredefinedTypes.IEnumerableGeneric.Define ()) {
433 generic_enumerable_type = new GenericTypeExpr (Module.PredefinedTypes.IEnumerableGeneric.TypeSpec, generic_args, Location);
434 list.Add (generic_enumerable_type);
438 enumerator_type = new TypeExpression (Compiler.BuiltinTypes.IEnumerator, Location);
439 list.Add (enumerator_type);
441 list.Add (new TypeExpression (Compiler.BuiltinTypes.IDisposable, Location));
443 var ienumerator_generic = Module.PredefinedTypes.IEnumeratorGeneric;
444 if (ienumerator_generic.Define ()) {
445 generic_enumerator_type = new GenericTypeExpr (ienumerator_generic.TypeSpec, generic_args, Location);
446 list.Add (generic_enumerator_type);
451 return base.ResolveBaseTypes (out base_class);
454 protected override bool DoDefineMembers ()
456 current_field = AddCompilerGeneratedField ("$current", iterator_type_expr);
457 disposing_field = AddCompilerGeneratedField ("$disposing", new TypeExpression (Compiler.BuiltinTypes.Bool, Location));
459 if (hoisted_params != null) {
461 // Iterators are independent, each GetEnumerator call has to
462 // create same enumerator therefore we have to keep original values
463 // around for re-initialization
465 // TODO: Do it for assigned/modified parameters only
467 hoisted_params_copy = new List<HoistedParameter> (hoisted_params.Count);
468 foreach (HoistedParameter hp in hoisted_params) {
469 hoisted_params_copy.Add (new HoistedParameter (hp, "<$>" + hp.Field.Name));
473 if (generic_enumerator_type != null)
474 Define_Current (true);
476 Define_Current (false);
477 new DisposeMethod (this);
480 if (Iterator.IsEnumerable) {
481 FullNamedExpression explicit_iface = new TypeExpression (Compiler.BuiltinTypes.IEnumerable, Location);
482 var name = new MemberName ("GetEnumerator", null, explicit_iface, Location);
484 if (generic_enumerator_type != null) {
485 Method get_enumerator = new StateMachineMethod (this, null, enumerator_type, 0, name);
487 explicit_iface = new GenericTypeExpr (Module.PredefinedTypes.IEnumerableGeneric.Resolve (), generic_args, Location);
488 name = new MemberName ("GetEnumerator", null, explicit_iface, Location);
489 Method gget_enumerator = new GetEnumeratorMethod (this, generic_enumerator_type, name);
492 // Just call generic GetEnumerator implementation
494 get_enumerator.Block.AddStatement (
495 new Return (new Invocation (new DynamicMethodGroupExpr (gget_enumerator, Location), null), Location));
497 AddMethod (get_enumerator);
498 AddMethod (gget_enumerator);
500 AddMethod (new GetEnumeratorMethod (this, enumerator_type, name));
504 return base.DoDefineMembers ();
507 void Define_Current (bool is_generic)
510 FullNamedExpression explicit_iface;
513 explicit_iface = new GenericTypeExpr (Module.PredefinedTypes.IEnumeratorGeneric.Resolve (), generic_args, Location);
514 type = iterator_type_expr;
516 explicit_iface = new TypeExpression (Module.Compiler.BuiltinTypes.IEnumerator, Location);
517 type = new TypeExpression (Compiler.BuiltinTypes.Object, Location);
520 var name = new MemberName ("Current", null, explicit_iface, Location);
522 ToplevelBlock get_block = new ToplevelBlock (Compiler, Location);
523 get_block.AddStatement (new Return (new DynamicFieldExpr (CurrentField, Location), Location));
525 Property current = new Property (this, type, Modifiers.DEBUGGER_HIDDEN, name, null);
526 current.Get = new Property.GetMethod (current, 0, null, Location);
527 current.Get.Block = get_block;
529 AddProperty (current);
534 Method reset = new Method (
535 this, null, new TypeExpression (Compiler.BuiltinTypes.Void, Location),
536 Modifiers.PUBLIC | Modifiers.DEBUGGER_HIDDEN,
537 new MemberName ("Reset", Location),
538 ParametersCompiled.EmptyReadOnlyParameters, null);
541 reset.Block = new ToplevelBlock (Compiler, Location);
543 TypeSpec ex_type = Module.PredefinedTypes.NotSupportedException.Resolve ();
547 reset.Block.AddStatement (new Throw (new New (new TypeExpression (ex_type, Location), null, Location), Location));
550 protected override void EmitHoistedParameters (EmitContext ec, IList<HoistedParameter> hoisted)
552 base.EmitHoistedParameters (ec, hoisted);
553 base.EmitHoistedParameters (ec, hoisted_params_copy);
556 protected override string GetVariableMangledName (LocalVariable local_info)
558 return "<" + local_info.Name + ">__" + local_name_idx++.ToString ("X");
562 public class StateMachineMethod : Method
564 readonly StateMachineInitializer expr;
566 public StateMachineMethod (StateMachine host, StateMachineInitializer expr, FullNamedExpression returnType, Modifiers mod, MemberName name)
567 : base (host, null, returnType, mod | Modifiers.COMPILER_GENERATED,
568 name, ParametersCompiled.EmptyReadOnlyParameters, null)
571 Block = new ToplevelBlock (host.Compiler, ParametersCompiled.EmptyReadOnlyParameters, Location);
574 public override EmitContext CreateEmitContext (ILGenerator ig)
576 EmitContext ec = new EmitContext (this, ig, MemberType);
577 ec.CurrentAnonymousMethod = expr;
579 if (expr is AsyncInitializer)
580 ec.With (BuilderContext.Options.AsyncBody, true);
586 public abstract class StateMachineInitializer : AnonymousExpression
588 sealed class MoveNextBodyStatement : Statement
590 readonly StateMachineInitializer state_machine;
592 public MoveNextBodyStatement (StateMachineInitializer stateMachine)
594 this.state_machine = stateMachine;
595 this.loc = stateMachine.Location;
598 protected override void CloneTo (CloneContext clonectx, Statement target)
600 throw new NotSupportedException ();
603 public override bool Resolve (BlockContext ec)
608 protected override void DoEmit (EmitContext ec)
610 state_machine.EmitMoveNext (ec);
614 public readonly TypeContainer Host;
615 protected StateMachine storey;
618 // The state as we generate the machine
621 Label iterator_body_end;
622 protected Label move_next_error;
623 LocalBuilder skip_finally;
624 protected LocalBuilder current_pc;
625 protected List<ResumableStatement> resume_points;
627 protected StateMachineInitializer (ParametersBlock block, TypeContainer host, TypeSpec returnType)
628 : base (block, returnType, block.StartLocation)
635 public Label BodyEnd {
637 return iterator_body_end;
641 public LocalBuilder CurrentPC
648 public LocalBuilder SkipFinally {
654 public override AnonymousMethodStorey Storey {
662 public int AddResumePoint (ResumableStatement stmt)
664 if (resume_points == null)
665 resume_points = new List<ResumableStatement> ();
667 resume_points.Add (stmt);
668 return resume_points.Count;
671 public override Expression CreateExpressionTree (ResolveContext ec)
673 throw new NotSupportedException ("ET");
676 protected virtual BlockContext CreateBlockContext (ResolveContext rc)
678 var ctx = new BlockContext (rc, block, ((BlockContext) rc).ReturnType);
679 ctx.CurrentAnonymousMethod = this;
683 protected override Expression DoResolve (ResolveContext ec)
685 storey = (StateMachine) block.Parent.ParametersBlock.AnonymousMethodStorey;
687 var ctx = CreateBlockContext (ec);
692 // Explicit return is required for Task<T> state machine
694 var task_storey = storey as AsyncTaskStorey;
695 if (task_storey == null || (task_storey.ReturnType != null && !task_storey.ReturnType.IsGenericTask))
696 ctx.CurrentBranching.CurrentUsageVector.Goto ();
698 ctx.EndFlowBranching ();
700 if (!ec.IsInProbingMode) {
701 var move_next = new StateMachineMethod (storey, this, new TypeExpression (ReturnType, loc), Modifiers.PUBLIC, new MemberName ("MoveNext", loc));
702 move_next.Block.AddStatement (new MoveNextBodyStatement (this));
703 storey.AddEntryMethod (move_next);
706 eclass = ExprClass.Value;
710 public override void Emit (EmitContext ec)
713 // Load Iterator storey instance
715 storey.Instance.Emit (ec);
718 void EmitMoveNext_NoResumePoints (EmitContext ec, Block original_block)
721 ec.Emit (OpCodes.Ldfld, storey.PC.Spec);
724 ec.EmitInt ((int) IteratorStorey.State.After);
725 ec.Emit (OpCodes.Stfld, storey.PC.Spec);
727 // We only care if the PC is zero (start executing) or non-zero (don't do anything)
728 ec.Emit (OpCodes.Brtrue, move_next_error);
730 iterator_body_end = ec.DefineLabel ();
732 SymbolWriter.StartIteratorBody (ec);
733 original_block.Emit (ec);
734 SymbolWriter.EndIteratorBody (ec);
736 ec.MarkLabel (iterator_body_end);
738 EmitMoveNextEpilogue (ec);
740 ec.MarkLabel (move_next_error);
742 if (ReturnType.Kind != MemberKind.Void) {
744 ec.Emit (OpCodes.Ret);
748 void EmitMoveNext (EmitContext ec)
750 move_next_ok = ec.DefineLabel ();
751 move_next_error = ec.DefineLabel ();
753 if (resume_points == null) {
754 EmitMoveNext_NoResumePoints (ec, block);
758 current_pc = ec.GetTemporaryLocal (ec.BuiltinTypes.UInt);
760 ec.Emit (OpCodes.Ldfld, storey.PC.Spec);
761 ec.Emit (OpCodes.Stloc, current_pc);
763 // We're actually in state 'running', but this is as good a PC value as any if there's an abnormal exit
765 ec.EmitInt ((int) IteratorStorey.State.After);
766 ec.Emit (OpCodes.Stfld, storey.PC.Spec);
768 Label[] labels = new Label[1 + resume_points.Count];
769 labels[0] = ec.DefineLabel ();
771 bool need_skip_finally = false;
772 for (int i = 0; i < resume_points.Count; ++i) {
773 ResumableStatement s = resume_points[i];
774 need_skip_finally |= s is ExceptionStatement;
775 labels[i + 1] = s.PrepareForEmit (ec);
778 if (need_skip_finally) {
779 skip_finally = ec.GetTemporaryLocal (ec.BuiltinTypes.Bool);
781 ec.Emit (OpCodes.Stloc, skip_finally);
784 var async_init = this as AsyncInitializer;
785 if (async_init != null)
786 ec.BeginExceptionBlock ();
788 SymbolWriter.StartIteratorDispatcher (ec);
789 ec.Emit (OpCodes.Ldloc, current_pc);
790 ec.Emit (OpCodes.Switch, labels);
792 ec.Emit (async_init != null ? OpCodes.Leave : OpCodes.Br, move_next_error);
793 SymbolWriter.EndIteratorDispatcher (ec);
795 ec.MarkLabel (labels[0]);
797 iterator_body_end = ec.DefineLabel ();
799 SymbolWriter.StartIteratorBody (ec);
801 SymbolWriter.EndIteratorBody (ec);
803 SymbolWriter.StartIteratorDispatcher (ec);
805 ec.MarkLabel (iterator_body_end);
807 if (async_init != null) {
808 var catch_value = LocalVariable.CreateCompilerGenerated (ec.Module.Compiler.BuiltinTypes.Exception, block, Location);
810 ec.BeginCatchBlock (catch_value.Type);
811 catch_value.EmitAssign (ec);
814 ec.EmitInt ((int) IteratorStorey.State.After);
815 ec.Emit (OpCodes.Stfld, storey.PC.Spec);
817 ((AsyncTaskStorey) async_init.Storey).EmitSetException (ec, new LocalVariableReference (catch_value, Location));
819 ec.Emit (OpCodes.Leave, move_next_ok);
820 ec.EndExceptionBlock ();
824 ec.EmitInt ((int) IteratorStorey.State.After);
825 ec.Emit (OpCodes.Stfld, storey.PC.Spec);
827 EmitMoveNextEpilogue (ec);
829 ec.MarkLabel (move_next_error);
831 if (ReturnType.Kind != MemberKind.Void) {
833 ec.Emit (OpCodes.Ret);
836 ec.MarkLabel (move_next_ok);
838 if (ReturnType.Kind != MemberKind.Void) {
840 ec.Emit (OpCodes.Ret);
843 SymbolWriter.EndIteratorDispatcher (ec);
846 protected virtual void EmitMoveNextEpilogue (EmitContext ec)
850 public void EmitLeave (EmitContext ec, bool unwind_protect)
853 ec.Emit (unwind_protect ? OpCodes.Leave : OpCodes.Br, move_next_ok);
857 // Called back from YieldStatement
859 public virtual void InjectYield (EmitContext ec, Expression expr, int resume_pc, bool unwind_protect, Label resume_point)
862 // Guard against being disposed meantime
864 Label disposed = ec.DefineLabel ();
865 var iterator = storey as IteratorStorey;
866 if (iterator != null) {
868 ec.Emit (OpCodes.Ldfld, iterator.DisposingField.Spec);
869 ec.Emit (OpCodes.Brtrue_S, disposed);
873 // store resume program-counter
876 ec.EmitInt (resume_pc);
877 ec.Emit (OpCodes.Stfld, storey.PC.Spec);
879 if (iterator != null) {
880 ec.MarkLabel (disposed);
883 // mark finally blocks as disabled
884 if (unwind_protect && skip_finally != null) {
886 ec.Emit (OpCodes.Stloc, skip_finally);
892 // Iterators are implemented as hidden anonymous block
894 public class Iterator : StateMachineInitializer
896 public readonly IMethodData OriginalMethod;
897 public readonly bool IsEnumerable;
898 public readonly TypeSpec OriginalIteratorType;
900 public Iterator (ParametersBlock block, IMethodData method, TypeContainer host, TypeSpec iterator_type, bool is_enumerable)
901 : base (block, host, host.Compiler.BuiltinTypes.Bool)
903 this.OriginalMethod = method;
904 this.OriginalIteratorType = iterator_type;
905 this.IsEnumerable = is_enumerable;
906 this.type = method.ReturnType;
909 public Block Container {
910 get { return OriginalMethod.Block; }
913 public GenericMethod GenericMethod {
914 get { return OriginalMethod.GenericMethod; }
917 public override string ContainerType {
918 get { return "iterator"; }
921 public override bool IsIterator {
925 public void EmitYieldBreak (EmitContext ec, bool unwind_protect)
927 ec.Emit (unwind_protect ? OpCodes.Leave : OpCodes.Br, move_next_error);
930 public override string GetSignatureForError ()
932 return OriginalMethod.GetSignatureForError ();
935 public override void Emit (EmitContext ec)
938 // Load Iterator storey instance
940 storey.Instance.Emit (ec);
943 // Initialize iterator PC when it's unitialized
946 ec.Emit (OpCodes.Dup);
947 ec.EmitInt ((int)IteratorStorey.State.Uninitialized);
949 var field = storey.PC.Spec;
950 if (storey.MemberName.IsGeneric) {
951 field = MemberCache.GetMember (Storey.Instance.Type, field);
954 ec.Emit (OpCodes.Stfld, field);
958 public void EmitDispose (EmitContext ec)
960 Label end = ec.DefineLabel ();
962 Label[] labels = null;
963 int n_resume_points = resume_points == null ? 0 : resume_points.Count;
964 for (int i = 0; i < n_resume_points; ++i) {
965 ResumableStatement s = resume_points[i];
966 Label ret = s.PrepareForDispose (ec, end);
967 if (ret.Equals (end) && labels == null)
969 if (labels == null) {
970 labels = new Label[resume_points.Count + 1];
971 for (int j = 0; j <= i; ++j)
978 if (labels != null) {
979 current_pc = ec.GetTemporaryLocal (ec.BuiltinTypes.UInt);
981 ec.Emit (OpCodes.Ldfld, storey.PC.Spec);
982 ec.Emit (OpCodes.Stloc, current_pc);
987 ec.Emit (OpCodes.Stfld, ((IteratorStorey) storey).DisposingField.Spec);
990 ec.EmitInt ((int) IteratorStorey.State.After);
991 ec.Emit (OpCodes.Stfld, storey.PC.Spec);
993 if (labels != null) {
994 //SymbolWriter.StartIteratorDispatcher (ec.ig);
995 ec.Emit (OpCodes.Ldloc, current_pc);
996 ec.Emit (OpCodes.Switch, labels);
997 //SymbolWriter.EndIteratorDispatcher (ec.ig);
999 foreach (ResumableStatement s in resume_points)
1000 s.EmitForDispose (ec, current_pc, end, true);
1006 public override void EmitStatement (EmitContext ec)
1008 throw new NotImplementedException ();
1011 public override void InjectYield (EmitContext ec, Expression expr, int resume_pc, bool unwind_protect, Label resume_point)
1013 // Store the new value into current
1014 var fe = new FieldExpr (((IteratorStorey) storey).CurrentField, loc);
1015 fe.InstanceExpression = new CompilerGeneratedThis (storey.CurrentType, loc);
1016 fe.EmitAssign (ec, expr, false, false);
1018 base.InjectYield (ec, expr, resume_pc, unwind_protect, resume_point);
1020 EmitLeave (ec, unwind_protect);
1022 ec.MarkLabel (resume_point);
1025 protected override BlockContext CreateBlockContext (ResolveContext rc)
1027 var bc = base.CreateBlockContext (rc);
1028 bc.StartFlowBranching (this, rc.CurrentBranching);
1032 public static void CreateIterator (IMethodData method, TypeContainer parent, Modifiers modifiers)
1035 TypeSpec iterator_type;
1037 TypeSpec ret = method.ReturnType;
1041 if (!CheckType (ret, parent, out iterator_type, out is_enumerable)) {
1042 parent.Compiler.Report.Error (1624, method.Location,
1043 "The body of `{0}' cannot be an iterator block " +
1044 "because `{1}' is not an iterator interface type",
1045 method.GetSignatureForError (),
1046 TypeManager.CSharpName (ret));
1050 ParametersCompiled parameters = method.ParameterInfo;
1051 for (int i = 0; i < parameters.Count; i++) {
1052 Parameter p = parameters [i];
1053 Parameter.Modifier mod = p.ModFlags;
1054 if ((mod & Parameter.Modifier.ISBYREF) != 0) {
1055 parent.Compiler.Report.Error (1623, p.Location,
1056 "Iterators cannot have ref or out parameters");
1060 if (p is ArglistParameter) {
1061 parent.Compiler.Report.Error (1636, method.Location,
1062 "__arglist is not allowed in parameter list of iterators");
1066 if (parameters.Types [i].IsPointer) {
1067 parent.Compiler.Report.Error (1637, p.Location,
1068 "Iterators cannot have unsafe parameters or yield types");
1073 if ((modifiers & Modifiers.UNSAFE) != 0) {
1074 parent.Compiler.Report.Error (1629, method.Location, "Unsafe code may not appear in iterators");
1077 method.Block.WrapIntoIterator (method, parent, iterator_type, is_enumerable);
1080 static bool CheckType (TypeSpec ret, TypeContainer parent, out TypeSpec original_iterator_type, out bool is_enumerable)
1082 original_iterator_type = null;
1083 is_enumerable = false;
1085 if (ret.BuiltinType == BuiltinTypeSpec.Type.IEnumerable) {
1086 original_iterator_type = parent.Compiler.BuiltinTypes.Object;
1087 is_enumerable = true;
1090 if (ret.BuiltinType == BuiltinTypeSpec.Type.IEnumerator) {
1091 original_iterator_type = parent.Compiler.BuiltinTypes.Object;
1092 is_enumerable = false;
1096 InflatedTypeSpec inflated = ret as InflatedTypeSpec;
1097 if (inflated == null)
1100 var member_definition = inflated.MemberDefinition;
1101 PredefinedType ptype = parent.Module.PredefinedTypes.IEnumerableGeneric;
1103 if (ptype.Define () && ptype.TypeSpec.MemberDefinition == member_definition) {
1104 original_iterator_type = inflated.TypeArguments[0];
1105 is_enumerable = true;
1109 ptype = parent.Module.PredefinedTypes.IEnumeratorGeneric;
1110 if (ptype.Define () && ptype.TypeSpec.MemberDefinition == member_definition) {
1111 original_iterator_type = inflated.TypeArguments[0];
1112 is_enumerable = false;