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.
14 // Flow analysis for Yield.
18 using System.Collections.Generic;
21 using IKVM.Reflection.Emit;
23 using System.Reflection.Emit;
28 public abstract class YieldStatement<T> : ResumableStatement where T : StateMachineInitializer
30 protected Expression expr;
31 protected bool unwind_protect;
32 protected T machine_initializer;
35 protected YieldStatement (Expression expr, Location l)
41 protected override void CloneTo (CloneContext clonectx, Statement t)
43 var target = (YieldStatement<T>) t;
44 target.expr = expr.Clone (clonectx);
47 protected override void DoEmit (EmitContext ec)
49 machine_initializer.InjectYield (ec, expr, resume_pc, unwind_protect, resume_point);
52 public override bool Resolve (BlockContext bc)
54 expr = expr.Resolve (bc);
58 machine_initializer = bc.CurrentAnonymousMethod as T;
60 if (!bc.CurrentBranching.CurrentUsageVector.IsUnreachable)
61 unwind_protect = bc.CurrentBranching.AddResumePoint (this, out resume_pc);
67 public class Yield : YieldStatement<Iterator>
69 public Yield (Expression expr, Location loc)
74 public static bool CheckContext (ResolveContext ec, Location loc)
76 if (!ec.CurrentAnonymousMethod.IsIterator) {
77 ec.Report.Error (1621, loc,
78 "The yield statement cannot be used inside anonymous method blocks");
85 public override bool Resolve (BlockContext bc)
87 if (!CheckContext (bc, loc))
90 if (!base.Resolve (bc))
93 var otype = bc.CurrentIterator.OriginalIteratorType;
94 if (expr.Type != otype) {
95 expr = Convert.ImplicitConversionRequired (bc, expr, otype, loc);
104 public class YieldBreak : ExitStatement
108 public YieldBreak (Location l)
113 public override void Error_FinallyClause (Report Report)
115 Report.Error (1625, loc, "Cannot yield in the body of a finally clause");
118 protected override void CloneTo (CloneContext clonectx, Statement target)
120 throw new NotSupportedException ();
123 protected override bool DoResolve (BlockContext ec)
125 iterator = ec.CurrentIterator;
126 return Yield.CheckContext (ec, loc);
129 protected override void DoEmit (EmitContext ec)
131 iterator.EmitYieldBreak (ec, unwind_protect);
135 public abstract class StateMachine : AnonymousMethodStorey
139 Running = -3, // Used only in CurrentPC, never stored into $PC
147 StateMachineMethod method;
149 protected StateMachine (Block block, TypeContainer parent, MemberBase host, TypeParameter[] tparams, string name)
150 : base (block, parent, host, tparams, name)
156 public StateMachineMethod StateMachineMethod {
170 public void AddEntryMethod (StateMachineMethod method)
172 if (this.method != null)
173 throw new InternalErrorException ();
175 this.method = method;
179 protected override bool DoDefineMembers ()
181 pc_field = AddCompilerGeneratedField ("$PC", new TypeExpression (Compiler.BuiltinTypes.Int, Location));
183 return base.DoDefineMembers ();
186 protected override string GetVariableMangledName (LocalVariable local_info)
188 return "<" + local_info.Name + ">__" + local_name_idx++.ToString ("X");
192 class IteratorStorey : StateMachine
194 class GetEnumeratorMethod : StateMachineMethod
196 sealed class GetEnumeratorStatement : Statement
198 readonly IteratorStorey host;
199 readonly StateMachineMethod host_method;
201 Expression new_storey;
203 public GetEnumeratorStatement (IteratorStorey host, StateMachineMethod host_method)
206 this.host_method = host_method;
207 loc = host_method.Location;
210 protected override void CloneTo (CloneContext clonectx, Statement target)
212 throw new NotSupportedException ();
215 public override bool Resolve (BlockContext ec)
217 TypeExpression storey_type_expr = new TypeExpression (host.Definition, loc);
218 List<Expression> init = null;
219 if (host.hoisted_this != null) {
220 init = new List<Expression> (host.hoisted_params == null ? 1 : host.HoistedParameters.Count + 1);
221 HoistedThis ht = host.hoisted_this;
222 FieldExpr from = new FieldExpr (ht.Field, loc);
223 from.InstanceExpression = new CompilerGeneratedThis (ec.CurrentType, loc);
224 init.Add (new ElementInitializer (ht.Field.Name, from, loc));
227 if (host.hoisted_params != null) {
229 init = new List<Expression> (host.HoistedParameters.Count);
231 for (int i = 0; i < host.hoisted_params.Count; ++i) {
232 HoistedParameter hp = host.hoisted_params [i];
233 HoistedParameter hp_cp = host.hoisted_params_copy [i];
235 FieldExpr from = new FieldExpr (hp_cp.Field, loc);
236 from.InstanceExpression = new CompilerGeneratedThis (ec.CurrentType, loc);
238 init.Add (new ElementInitializer (hp.Field.Name, from, loc));
243 new_storey = new NewInitialize (storey_type_expr, null,
244 new CollectionOrObjectInitializers (init, loc), loc);
246 new_storey = new New (storey_type_expr, null, loc);
249 new_storey = new_storey.Resolve (ec);
250 if (new_storey != null)
251 new_storey = Convert.ImplicitConversionRequired (ec, new_storey, host_method.MemberType, loc);
253 ec.CurrentBranching.CurrentUsageVector.Goto ();
257 protected override void DoEmit (EmitContext ec)
259 Label label_init = ec.DefineLabel ();
262 ec.Emit (OpCodes.Ldflda, host.PC.Spec);
263 ec.EmitInt ((int) State.Start);
264 ec.EmitInt ((int) State.Uninitialized);
266 var m = ec.Module.PredefinedMembers.InterlockedCompareExchange.Resolve (loc);
268 ec.Emit (OpCodes.Call, m);
270 ec.EmitInt ((int) State.Uninitialized);
271 ec.Emit (OpCodes.Bne_Un_S, label_init);
274 ec.Emit (OpCodes.Ret);
276 ec.MarkLabel (label_init);
278 new_storey.Emit (ec);
279 ec.Emit (OpCodes.Ret);
283 public GetEnumeratorMethod (IteratorStorey host, FullNamedExpression returnType, MemberName name)
284 : base (host, null, returnType, Modifiers.DEBUGGER_HIDDEN, name)
286 Block.AddStatement (new GetEnumeratorStatement (host, this));
290 class DisposeMethod : StateMachineMethod
292 sealed class DisposeMethodStatement : Statement
296 public DisposeMethodStatement (Iterator iterator)
298 this.iterator = iterator;
299 this.loc = iterator.Location;
302 protected override void CloneTo (CloneContext clonectx, Statement target)
304 throw new NotSupportedException ();
307 public override bool Resolve (BlockContext ec)
312 protected override void DoEmit (EmitContext ec)
314 ec.CurrentAnonymousMethod = iterator;
315 iterator.EmitDispose (ec);
319 public DisposeMethod (IteratorStorey host)
320 : base (host, null, new TypeExpression (host.Compiler.BuiltinTypes.Void, host.Location), Modifiers.PUBLIC | Modifiers.DEBUGGER_HIDDEN,
321 new MemberName ("Dispose", host.Location))
323 host.AddMethod (this);
325 Block.AddStatement (new DisposeMethodStatement (host.Iterator));
330 // Uses Method as method info
332 class DynamicMethodGroupExpr : MethodGroupExpr
334 readonly Method method;
336 public DynamicMethodGroupExpr (Method method, Location loc)
337 : base ((IList<MemberSpec>) null, null, loc)
339 this.method = method;
340 eclass = ExprClass.Unresolved;
343 protected override Expression DoResolve (ResolveContext ec)
345 Methods = new List<MemberSpec> (1) { method.Spec };
346 type = method.Parent.Definition;
347 InstanceExpression = new CompilerGeneratedThis (type, Location);
348 return base.DoResolve (ec);
352 class DynamicFieldExpr : FieldExpr
354 readonly Field field;
356 public DynamicFieldExpr (Field field, Location loc)
362 protected override Expression DoResolve (ResolveContext ec)
365 type = spec.MemberType;
366 InstanceExpression = new CompilerGeneratedThis (type, Location);
367 return base.DoResolve (ec);
371 public readonly Iterator Iterator;
373 List<HoistedParameter> hoisted_params_copy;
375 TypeExpr iterator_type_expr;
377 Field disposing_field;
379 TypeExpr enumerator_type;
380 TypeExpr enumerable_type;
381 TypeArguments generic_args;
382 TypeExpr generic_enumerator_type;
383 TypeExpr generic_enumerable_type;
385 public IteratorStorey (Iterator iterator)
386 : base (iterator.Container.ParametersBlock, iterator.Host,
387 iterator.OriginalMethod as MemberBase, iterator.GenericMethod == null ? null : iterator.GenericMethod.CurrentTypeParameters, "Iterator")
389 this.Iterator = iterator;
392 public Field CurrentField {
394 return current_field;
398 public Field DisposingField {
400 return disposing_field;
404 public IList<HoistedParameter> HoistedParameters {
405 get { return hoisted_params; }
408 protected override TypeSpec[] ResolveBaseTypes (out FullNamedExpression base_class)
410 var mtype = Iterator.OriginalIteratorType;
412 mtype = Mutator.Mutate (mtype);
414 iterator_type_expr = new TypeExpression (mtype, Location);
415 generic_args = new TypeArguments (iterator_type_expr);
417 var list = new List<FullNamedExpression> ();
418 if (Iterator.IsEnumerable) {
419 enumerable_type = new TypeExpression (Compiler.BuiltinTypes.IEnumerable, Location);
420 list.Add (enumerable_type);
422 if (Module.PredefinedTypes.IEnumerableGeneric.Define ()) {
423 generic_enumerable_type = new GenericTypeExpr (Module.PredefinedTypes.IEnumerableGeneric.TypeSpec, generic_args, Location);
424 list.Add (generic_enumerable_type);
428 enumerator_type = new TypeExpression (Compiler.BuiltinTypes.IEnumerator, Location);
429 list.Add (enumerator_type);
431 list.Add (new TypeExpression (Compiler.BuiltinTypes.IDisposable, Location));
433 var ienumerator_generic = Module.PredefinedTypes.IEnumeratorGeneric;
434 if (ienumerator_generic.Define ()) {
435 generic_enumerator_type = new GenericTypeExpr (ienumerator_generic.TypeSpec, generic_args, Location);
436 list.Add (generic_enumerator_type);
441 return base.ResolveBaseTypes (out base_class);
444 protected override bool DoDefineMembers ()
446 current_field = AddCompilerGeneratedField ("$current", iterator_type_expr);
447 disposing_field = AddCompilerGeneratedField ("$disposing", new TypeExpression (Compiler.BuiltinTypes.Bool, Location));
449 if (hoisted_params != null) {
451 // Iterators are independent, each GetEnumerator call has to
452 // create same enumerator therefore we have to keep original values
453 // around for re-initialization
455 // TODO: Do it for assigned/modified parameters only
457 hoisted_params_copy = new List<HoistedParameter> (hoisted_params.Count);
458 foreach (HoistedParameter hp in hoisted_params) {
459 hoisted_params_copy.Add (new HoistedParameter (hp, "<$>" + hp.Field.Name));
463 if (generic_enumerator_type != null)
464 Define_Current (true);
466 Define_Current (false);
467 new DisposeMethod (this);
470 if (Iterator.IsEnumerable) {
471 MemberName name = new MemberName (QualifiedAliasMember.GlobalAlias, "System", null, Location);
472 name = new MemberName (name, "Collections", Location);
473 name = new MemberName (name, "IEnumerable", Location);
474 name = new MemberName (name, "GetEnumerator", Location);
476 if (generic_enumerator_type != null) {
477 Method get_enumerator = new StateMachineMethod (this, null, enumerator_type, 0, name);
479 name = new MemberName (name.Left.Left, "Generic", Location);
480 name = new MemberName (name, "IEnumerable", generic_args, Location);
481 name = new MemberName (name, "GetEnumerator", Location);
482 Method gget_enumerator = new GetEnumeratorMethod (this, generic_enumerator_type, name);
485 // Just call generic GetEnumerator implementation
487 get_enumerator.Block.AddStatement (
488 new Return (new Invocation (new DynamicMethodGroupExpr (gget_enumerator, Location), null), Location));
490 AddMethod (get_enumerator);
491 AddMethod (gget_enumerator);
493 AddMethod (new GetEnumeratorMethod (this, enumerator_type, name));
497 return base.DoDefineMembers ();
500 void Define_Current (bool is_generic)
504 MemberName name = new MemberName (QualifiedAliasMember.GlobalAlias, "System", null, Location);
505 name = new MemberName (name, "Collections", Location);
508 name = new MemberName (name, "Generic", Location);
509 name = new MemberName (name, "IEnumerator", generic_args, Location);
510 type = iterator_type_expr;
512 name = new MemberName (name, "IEnumerator");
513 type = new TypeExpression (Compiler.BuiltinTypes.Object, Location);
516 name = new MemberName (name, "Current", Location);
518 ToplevelBlock get_block = new ToplevelBlock (Compiler, Location);
519 get_block.AddStatement (new Return (new DynamicFieldExpr (CurrentField, Location), Location));
521 Property current = new Property (this, type, Modifiers.DEBUGGER_HIDDEN, name, null);
522 current.Get = new Property.GetMethod (current, 0, null, Location);
523 current.Get.Block = get_block;
525 AddProperty (current);
530 Method reset = new Method (
531 this, null, new TypeExpression (Compiler.BuiltinTypes.Void, Location),
532 Modifiers.PUBLIC | Modifiers.DEBUGGER_HIDDEN,
533 new MemberName ("Reset", Location),
534 ParametersCompiled.EmptyReadOnlyParameters, null);
537 reset.Block = new ToplevelBlock (Compiler, Location);
539 TypeSpec ex_type = Module.PredefinedTypes.NotSupportedException.Resolve ();
543 reset.Block.AddStatement (new Throw (new New (new TypeExpression (ex_type, Location), null, Location), Location));
546 protected override void EmitHoistedParameters (EmitContext ec, IList<HoistedParameter> hoisted)
548 base.EmitHoistedParameters (ec, hoisted);
549 base.EmitHoistedParameters (ec, hoisted_params_copy);
553 public class StateMachineMethod : Method
555 readonly StateMachineInitializer expr;
557 public StateMachineMethod (StateMachine host, StateMachineInitializer expr, FullNamedExpression returnType, Modifiers mod, MemberName name)
558 : base (host, null, returnType, mod | Modifiers.COMPILER_GENERATED,
559 name, ParametersCompiled.EmptyReadOnlyParameters, null)
562 Block = new ToplevelBlock (host.Compiler, ParametersCompiled.EmptyReadOnlyParameters, Location);
565 public override EmitContext CreateEmitContext (ILGenerator ig)
567 EmitContext ec = new EmitContext (this, ig, MemberType);
568 ec.CurrentAnonymousMethod = expr;
570 if (expr is AsyncInitializer)
571 ec.With (BuilderContext.Options.AsyncBody, true);
577 public abstract class StateMachineInitializer : AnonymousExpression
579 sealed class MoveNextBodyStatement : Statement
581 readonly StateMachineInitializer state_machine;
583 public MoveNextBodyStatement (StateMachineInitializer stateMachine)
585 this.state_machine = stateMachine;
586 this.loc = stateMachine.Location;
589 protected override void CloneTo (CloneContext clonectx, Statement target)
591 throw new NotSupportedException ();
594 public override bool Resolve (BlockContext ec)
599 protected override void DoEmit (EmitContext ec)
601 state_machine.EmitMoveNext (ec);
605 public readonly TypeContainer Host;
606 protected StateMachine storey;
609 // The state as we generate the machine
612 Label iterator_body_end;
613 protected Label move_next_error;
614 LocalBuilder skip_finally;
615 protected LocalBuilder current_pc;
616 protected List<ResumableStatement> resume_points;
618 protected StateMachineInitializer (ParametersBlock block, TypeContainer host, TypeSpec returnType)
619 : base (block, returnType, block.StartLocation)
626 public Label BodyEnd {
628 return iterator_body_end;
632 public LocalBuilder CurrentPC
639 public LocalBuilder SkipFinally {
645 public override AnonymousMethodStorey Storey {
653 public int AddResumePoint (ResumableStatement stmt)
655 if (resume_points == null)
656 resume_points = new List<ResumableStatement> ();
658 resume_points.Add (stmt);
659 return resume_points.Count;
662 public override Expression CreateExpressionTree (ResolveContext ec)
664 throw new NotSupportedException ("ET");
667 protected virtual BlockContext CreateBlockContext (ResolveContext rc)
669 var ctx = new BlockContext (rc, block, ((BlockContext) rc).ReturnType);
670 ctx.CurrentAnonymousMethod = this;
674 protected override Expression DoResolve (ResolveContext ec)
676 storey = (StateMachine) block.Parent.ParametersBlock.AnonymousMethodStorey;
678 var ctx = CreateBlockContext (ec);
683 // Explicit return is required for Task<T> state machine
685 var task_storey = storey as AsyncTaskStorey;
686 if (task_storey == null || (task_storey.ReturnType != null && !task_storey.ReturnType.IsGenericTask))
687 ctx.CurrentBranching.CurrentUsageVector.Goto ();
689 ctx.EndFlowBranching ();
691 if (!ec.IsInProbingMode) {
692 var move_next = new StateMachineMethod (storey, this, new TypeExpression (ReturnType, loc), Modifiers.PUBLIC, new MemberName ("MoveNext", loc));
693 move_next.Block.AddStatement (new MoveNextBodyStatement (this));
694 storey.AddEntryMethod (move_next);
697 eclass = ExprClass.Value;
701 public override void Emit (EmitContext ec)
704 // Load Iterator storey instance
706 storey.Instance.Emit (ec);
709 void EmitMoveNext_NoResumePoints (EmitContext ec, Block original_block)
712 ec.Emit (OpCodes.Ldfld, storey.PC.Spec);
715 ec.EmitInt ((int) IteratorStorey.State.After);
716 ec.Emit (OpCodes.Stfld, storey.PC.Spec);
718 // We only care if the PC is zero (start executing) or non-zero (don't do anything)
719 ec.Emit (OpCodes.Brtrue, move_next_error);
721 iterator_body_end = ec.DefineLabel ();
723 SymbolWriter.StartIteratorBody (ec);
724 original_block.Emit (ec);
725 SymbolWriter.EndIteratorBody (ec);
727 ec.MarkLabel (iterator_body_end);
729 EmitMoveNextEpilogue (ec);
731 ec.MarkLabel (move_next_error);
733 if (ReturnType.Kind != MemberKind.Void) {
735 ec.Emit (OpCodes.Ret);
739 void EmitMoveNext (EmitContext ec)
741 move_next_ok = ec.DefineLabel ();
742 move_next_error = ec.DefineLabel ();
744 if (resume_points == null) {
745 EmitMoveNext_NoResumePoints (ec, block);
749 current_pc = ec.GetTemporaryLocal (ec.BuiltinTypes.UInt);
751 ec.Emit (OpCodes.Ldfld, storey.PC.Spec);
752 ec.Emit (OpCodes.Stloc, current_pc);
754 // We're actually in state 'running', but this is as good a PC value as any if there's an abnormal exit
756 ec.EmitInt ((int) IteratorStorey.State.After);
757 ec.Emit (OpCodes.Stfld, storey.PC.Spec);
759 Label[] labels = new Label[1 + resume_points.Count];
760 labels[0] = ec.DefineLabel ();
762 bool need_skip_finally = false;
763 for (int i = 0; i < resume_points.Count; ++i) {
764 ResumableStatement s = resume_points[i];
765 need_skip_finally |= s is ExceptionStatement;
766 labels[i + 1] = s.PrepareForEmit (ec);
769 if (need_skip_finally) {
770 skip_finally = ec.GetTemporaryLocal (ec.BuiltinTypes.Bool);
772 ec.Emit (OpCodes.Stloc, skip_finally);
775 var async_init = this as AsyncInitializer;
776 if (async_init != null)
777 ec.BeginExceptionBlock ();
779 SymbolWriter.StartIteratorDispatcher (ec);
780 ec.Emit (OpCodes.Ldloc, current_pc);
781 ec.Emit (OpCodes.Switch, labels);
783 ec.Emit (async_init != null ? OpCodes.Leave : OpCodes.Br, move_next_error);
784 SymbolWriter.EndIteratorDispatcher (ec);
786 ec.MarkLabel (labels[0]);
788 iterator_body_end = ec.DefineLabel ();
790 SymbolWriter.StartIteratorBody (ec);
792 SymbolWriter.EndIteratorBody (ec);
794 SymbolWriter.StartIteratorDispatcher (ec);
796 ec.MarkLabel (iterator_body_end);
798 if (async_init != null) {
799 var catch_value = LocalVariable.CreateCompilerGenerated (ec.Module.Compiler.BuiltinTypes.Exception, block, Location);
801 ec.BeginCatchBlock (catch_value.Type);
802 catch_value.EmitAssign (ec);
805 ec.EmitInt ((int) IteratorStorey.State.After);
806 ec.Emit (OpCodes.Stfld, storey.PC.Spec);
808 ((AsyncTaskStorey) async_init.Storey).EmitSetException (ec, new LocalVariableReference (catch_value, Location));
810 ec.Emit (OpCodes.Leave, move_next_ok);
811 ec.EndExceptionBlock ();
815 ec.EmitInt ((int) IteratorStorey.State.After);
816 ec.Emit (OpCodes.Stfld, storey.PC.Spec);
818 EmitMoveNextEpilogue (ec);
820 ec.MarkLabel (move_next_error);
822 if (ReturnType.Kind != MemberKind.Void) {
824 ec.Emit (OpCodes.Ret);
827 ec.MarkLabel (move_next_ok);
829 if (ReturnType.Kind != MemberKind.Void) {
831 ec.Emit (OpCodes.Ret);
834 SymbolWriter.EndIteratorDispatcher (ec);
837 protected virtual void EmitMoveNextEpilogue (EmitContext ec)
841 public void EmitLeave (EmitContext ec, bool unwind_protect)
844 ec.Emit (unwind_protect ? OpCodes.Leave : OpCodes.Br, move_next_ok);
848 // Called back from YieldStatement
850 public virtual void InjectYield (EmitContext ec, Expression expr, int resume_pc, bool unwind_protect, Label resume_point)
853 // Guard against being disposed meantime
855 Label disposed = ec.DefineLabel ();
856 var iterator = storey as IteratorStorey;
857 if (iterator != null) {
859 ec.Emit (OpCodes.Ldfld, iterator.DisposingField.Spec);
860 ec.Emit (OpCodes.Brtrue_S, disposed);
864 // store resume program-counter
867 ec.EmitInt (resume_pc);
868 ec.Emit (OpCodes.Stfld, storey.PC.Spec);
870 if (iterator != null) {
871 ec.MarkLabel (disposed);
874 // mark finally blocks as disabled
875 if (unwind_protect && skip_finally != null) {
877 ec.Emit (OpCodes.Stloc, skip_finally);
883 // Iterators are implemented as hidden anonymous block
885 public class Iterator : StateMachineInitializer
887 public readonly IMethodData OriginalMethod;
888 public readonly bool IsEnumerable;
889 public readonly TypeSpec OriginalIteratorType;
891 public Iterator (ParametersBlock block, IMethodData method, TypeContainer host, TypeSpec iterator_type, bool is_enumerable)
892 : base (block, host, host.Compiler.BuiltinTypes.Bool)
894 this.OriginalMethod = method;
895 this.OriginalIteratorType = iterator_type;
896 this.IsEnumerable = is_enumerable;
897 this.type = method.ReturnType;
900 public Block Container {
901 get { return OriginalMethod.Block; }
904 public GenericMethod GenericMethod {
905 get { return OriginalMethod.GenericMethod; }
908 public override string ContainerType {
909 get { return "iterator"; }
912 public override bool IsIterator {
916 public void EmitYieldBreak (EmitContext ec, bool unwind_protect)
918 ec.Emit (unwind_protect ? OpCodes.Leave : OpCodes.Br, move_next_error);
921 public override string GetSignatureForError ()
923 return OriginalMethod.GetSignatureForError ();
926 public override void Emit (EmitContext ec)
929 // Load Iterator storey instance
931 storey.Instance.Emit (ec);
934 // Initialize iterator PC when it's unitialized
937 ec.Emit (OpCodes.Dup);
938 ec.EmitInt ((int)IteratorStorey.State.Uninitialized);
940 var field = storey.PC.Spec;
941 if (storey.MemberName.IsGeneric) {
942 field = MemberCache.GetMember (Storey.Instance.Type, field);
945 ec.Emit (OpCodes.Stfld, field);
949 public void EmitDispose (EmitContext ec)
951 Label end = ec.DefineLabel ();
953 Label[] labels = null;
954 int n_resume_points = resume_points == null ? 0 : resume_points.Count;
955 for (int i = 0; i < n_resume_points; ++i) {
956 ResumableStatement s = resume_points[i];
957 Label ret = s.PrepareForDispose (ec, end);
958 if (ret.Equals (end) && labels == null)
960 if (labels == null) {
961 labels = new Label[resume_points.Count + 1];
962 for (int j = 0; j <= i; ++j)
969 if (labels != null) {
970 current_pc = ec.GetTemporaryLocal (ec.BuiltinTypes.UInt);
972 ec.Emit (OpCodes.Ldfld, storey.PC.Spec);
973 ec.Emit (OpCodes.Stloc, current_pc);
978 ec.Emit (OpCodes.Stfld, ((IteratorStorey) storey).DisposingField.Spec);
981 ec.EmitInt ((int) IteratorStorey.State.After);
982 ec.Emit (OpCodes.Stfld, storey.PC.Spec);
984 if (labels != null) {
985 //SymbolWriter.StartIteratorDispatcher (ec.ig);
986 ec.Emit (OpCodes.Ldloc, current_pc);
987 ec.Emit (OpCodes.Switch, labels);
988 //SymbolWriter.EndIteratorDispatcher (ec.ig);
990 foreach (ResumableStatement s in resume_points)
991 s.EmitForDispose (ec, current_pc, end, true);
997 public override void EmitStatement (EmitContext ec)
999 throw new NotImplementedException ();
1002 public override void InjectYield (EmitContext ec, Expression expr, int resume_pc, bool unwind_protect, Label resume_point)
1004 // Store the new value into current
1005 var fe = new FieldExpr (((IteratorStorey) storey).CurrentField, loc);
1006 fe.InstanceExpression = new CompilerGeneratedThis (storey.CurrentType, loc);
1007 fe.EmitAssign (ec, expr, false, false);
1009 base.InjectYield (ec, expr, resume_pc, unwind_protect, resume_point);
1011 EmitLeave (ec, unwind_protect);
1013 ec.MarkLabel (resume_point);
1016 protected override BlockContext CreateBlockContext (ResolveContext rc)
1018 var bc = base.CreateBlockContext (rc);
1019 bc.StartFlowBranching (this, rc.CurrentBranching);
1023 public static void CreateIterator (IMethodData method, TypeContainer parent, Modifiers modifiers)
1026 TypeSpec iterator_type;
1028 TypeSpec ret = method.ReturnType;
1032 if (!CheckType (ret, parent, out iterator_type, out is_enumerable)) {
1033 parent.Compiler.Report.Error (1624, method.Location,
1034 "The body of `{0}' cannot be an iterator block " +
1035 "because `{1}' is not an iterator interface type",
1036 method.GetSignatureForError (),
1037 TypeManager.CSharpName (ret));
1041 ParametersCompiled parameters = method.ParameterInfo;
1042 for (int i = 0; i < parameters.Count; i++) {
1043 Parameter p = parameters [i];
1044 Parameter.Modifier mod = p.ModFlags;
1045 if ((mod & Parameter.Modifier.ISBYREF) != 0) {
1046 parent.Compiler.Report.Error (1623, p.Location,
1047 "Iterators cannot have ref or out parameters");
1051 if (p is ArglistParameter) {
1052 parent.Compiler.Report.Error (1636, method.Location,
1053 "__arglist is not allowed in parameter list of iterators");
1057 if (parameters.Types [i].IsPointer) {
1058 parent.Compiler.Report.Error (1637, p.Location,
1059 "Iterators cannot have unsafe parameters or yield types");
1064 if ((modifiers & Modifiers.UNSAFE) != 0) {
1065 parent.Compiler.Report.Error (1629, method.Location, "Unsafe code may not appear in iterators");
1068 method.Block.WrapIntoIterator (method, parent, iterator_type, is_enumerable);
1071 static bool CheckType (TypeSpec ret, TypeContainer parent, out TypeSpec original_iterator_type, out bool is_enumerable)
1073 original_iterator_type = null;
1074 is_enumerable = false;
1076 if (ret.BuiltinType == BuiltinTypeSpec.Type.IEnumerable) {
1077 original_iterator_type = parent.Compiler.BuiltinTypes.Object;
1078 is_enumerable = true;
1081 if (ret.BuiltinType == BuiltinTypeSpec.Type.IEnumerator) {
1082 original_iterator_type = parent.Compiler.BuiltinTypes.Object;
1083 is_enumerable = false;
1087 InflatedTypeSpec inflated = ret as InflatedTypeSpec;
1088 if (inflated == null)
1091 var member_definition = inflated.MemberDefinition;
1092 PredefinedType ptype = parent.Module.PredefinedTypes.IEnumerableGeneric;
1094 if (ptype.Define () && ptype.TypeSpec.MemberDefinition == member_definition) {
1095 original_iterator_type = inflated.TypeArguments[0];
1096 is_enumerable = true;
1100 ptype = parent.Module.PredefinedTypes.IEnumeratorGeneric;
1101 if (ptype.Define () && ptype.TypeSpec.MemberDefinition == member_definition) {
1102 original_iterator_type = inflated.TypeArguments[0];
1103 is_enumerable = false;