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 MemberName name = new MemberName (QualifiedAliasMember.GlobalAlias, "System", null, Location);
482 name = new MemberName (name, "Collections", Location);
483 name = new MemberName (name, "IEnumerable", Location);
484 name = new MemberName (name, "GetEnumerator", Location);
486 if (generic_enumerator_type != null) {
487 Method get_enumerator = new StateMachineMethod (this, null, enumerator_type, 0, name);
489 name = new MemberName (name.Left.Left, "Generic", Location);
490 name = new MemberName (name, "IEnumerable", generic_args, Location);
491 name = new MemberName (name, "GetEnumerator", Location);
492 Method gget_enumerator = new GetEnumeratorMethod (this, generic_enumerator_type, name);
495 // Just call generic GetEnumerator implementation
497 get_enumerator.Block.AddStatement (
498 new Return (new Invocation (new DynamicMethodGroupExpr (gget_enumerator, Location), null), Location));
500 AddMethod (get_enumerator);
501 AddMethod (gget_enumerator);
503 AddMethod (new GetEnumeratorMethod (this, enumerator_type, name));
507 return base.DoDefineMembers ();
510 void Define_Current (bool is_generic)
514 MemberName name = new MemberName (QualifiedAliasMember.GlobalAlias, "System", null, Location);
515 name = new MemberName (name, "Collections", Location);
518 name = new MemberName (name, "Generic", Location);
519 name = new MemberName (name, "IEnumerator", generic_args, Location);
520 type = iterator_type_expr;
522 name = new MemberName (name, "IEnumerator");
523 type = new TypeExpression (Compiler.BuiltinTypes.Object, Location);
526 name = new MemberName (name, "Current", Location);
528 ToplevelBlock get_block = new ToplevelBlock (Compiler, Location);
529 get_block.AddStatement (new Return (new DynamicFieldExpr (CurrentField, Location), Location));
531 Property current = new Property (this, type, Modifiers.DEBUGGER_HIDDEN, name, null);
532 current.Get = new Property.GetMethod (current, 0, null, Location);
533 current.Get.Block = get_block;
535 AddProperty (current);
540 Method reset = new Method (
541 this, null, new TypeExpression (Compiler.BuiltinTypes.Void, Location),
542 Modifiers.PUBLIC | Modifiers.DEBUGGER_HIDDEN,
543 new MemberName ("Reset", Location),
544 ParametersCompiled.EmptyReadOnlyParameters, null);
547 reset.Block = new ToplevelBlock (Compiler, Location);
549 TypeSpec ex_type = Module.PredefinedTypes.NotSupportedException.Resolve ();
553 reset.Block.AddStatement (new Throw (new New (new TypeExpression (ex_type, Location), null, Location), Location));
556 protected override void EmitHoistedParameters (EmitContext ec, IList<HoistedParameter> hoisted)
558 base.EmitHoistedParameters (ec, hoisted);
559 base.EmitHoistedParameters (ec, hoisted_params_copy);
562 protected override string GetVariableMangledName (LocalVariable local_info)
564 return "<" + local_info.Name + ">__" + local_name_idx++.ToString ("X");
568 public class StateMachineMethod : Method
570 readonly StateMachineInitializer expr;
572 public StateMachineMethod (StateMachine host, StateMachineInitializer expr, FullNamedExpression returnType, Modifiers mod, MemberName name)
573 : base (host, null, returnType, mod | Modifiers.COMPILER_GENERATED,
574 name, ParametersCompiled.EmptyReadOnlyParameters, null)
577 Block = new ToplevelBlock (host.Compiler, ParametersCompiled.EmptyReadOnlyParameters, Location);
580 public override EmitContext CreateEmitContext (ILGenerator ig)
582 EmitContext ec = new EmitContext (this, ig, MemberType);
583 ec.CurrentAnonymousMethod = expr;
585 if (expr is AsyncInitializer)
586 ec.With (BuilderContext.Options.AsyncBody, true);
592 public abstract class StateMachineInitializer : AnonymousExpression
594 sealed class MoveNextBodyStatement : Statement
596 readonly StateMachineInitializer state_machine;
598 public MoveNextBodyStatement (StateMachineInitializer stateMachine)
600 this.state_machine = stateMachine;
601 this.loc = stateMachine.Location;
604 protected override void CloneTo (CloneContext clonectx, Statement target)
606 throw new NotSupportedException ();
609 public override bool Resolve (BlockContext ec)
614 protected override void DoEmit (EmitContext ec)
616 state_machine.EmitMoveNext (ec);
620 public readonly TypeContainer Host;
621 protected StateMachine storey;
624 // The state as we generate the machine
627 Label iterator_body_end;
628 protected Label move_next_error;
629 LocalBuilder skip_finally;
630 protected LocalBuilder current_pc;
631 protected List<ResumableStatement> resume_points;
633 protected StateMachineInitializer (ParametersBlock block, TypeContainer host, TypeSpec returnType)
634 : base (block, returnType, block.StartLocation)
641 public Label BodyEnd {
643 return iterator_body_end;
647 public LocalBuilder CurrentPC
654 public LocalBuilder SkipFinally {
660 public override AnonymousMethodStorey Storey {
668 public int AddResumePoint (ResumableStatement stmt)
670 if (resume_points == null)
671 resume_points = new List<ResumableStatement> ();
673 resume_points.Add (stmt);
674 return resume_points.Count;
677 public override Expression CreateExpressionTree (ResolveContext ec)
679 throw new NotSupportedException ("ET");
682 protected virtual BlockContext CreateBlockContext (ResolveContext rc)
684 var ctx = new BlockContext (rc, block, ((BlockContext) rc).ReturnType);
685 ctx.CurrentAnonymousMethod = this;
689 protected override Expression DoResolve (ResolveContext ec)
691 storey = (StateMachine) block.Parent.ParametersBlock.AnonymousMethodStorey;
693 var ctx = CreateBlockContext (ec);
698 // Explicit return is required for Task<T> state machine
700 var task_storey = storey as AsyncTaskStorey;
701 if (task_storey == null || (task_storey.ReturnType != null && !task_storey.ReturnType.IsGenericTask))
702 ctx.CurrentBranching.CurrentUsageVector.Goto ();
704 ctx.EndFlowBranching ();
706 if (!ec.IsInProbingMode) {
707 var move_next = new StateMachineMethod (storey, this, new TypeExpression (ReturnType, loc), Modifiers.PUBLIC, new MemberName ("MoveNext", loc));
708 move_next.Block.AddStatement (new MoveNextBodyStatement (this));
709 storey.AddEntryMethod (move_next);
712 eclass = ExprClass.Value;
716 public override void Emit (EmitContext ec)
719 // Load Iterator storey instance
721 storey.Instance.Emit (ec);
724 void EmitMoveNext_NoResumePoints (EmitContext ec, Block original_block)
727 ec.Emit (OpCodes.Ldfld, storey.PC.Spec);
730 ec.EmitInt ((int) IteratorStorey.State.After);
731 ec.Emit (OpCodes.Stfld, storey.PC.Spec);
733 // We only care if the PC is zero (start executing) or non-zero (don't do anything)
734 ec.Emit (OpCodes.Brtrue, move_next_error);
736 iterator_body_end = ec.DefineLabel ();
738 SymbolWriter.StartIteratorBody (ec);
739 original_block.Emit (ec);
740 SymbolWriter.EndIteratorBody (ec);
742 ec.MarkLabel (iterator_body_end);
744 EmitMoveNextEpilogue (ec);
746 ec.MarkLabel (move_next_error);
748 if (ReturnType.Kind != MemberKind.Void) {
750 ec.Emit (OpCodes.Ret);
754 void EmitMoveNext (EmitContext ec)
756 move_next_ok = ec.DefineLabel ();
757 move_next_error = ec.DefineLabel ();
759 if (resume_points == null) {
760 EmitMoveNext_NoResumePoints (ec, block);
764 current_pc = ec.GetTemporaryLocal (ec.BuiltinTypes.UInt);
766 ec.Emit (OpCodes.Ldfld, storey.PC.Spec);
767 ec.Emit (OpCodes.Stloc, current_pc);
769 // We're actually in state 'running', but this is as good a PC value as any if there's an abnormal exit
771 ec.EmitInt ((int) IteratorStorey.State.After);
772 ec.Emit (OpCodes.Stfld, storey.PC.Spec);
774 Label[] labels = new Label[1 + resume_points.Count];
775 labels[0] = ec.DefineLabel ();
777 bool need_skip_finally = false;
778 for (int i = 0; i < resume_points.Count; ++i) {
779 ResumableStatement s = resume_points[i];
780 need_skip_finally |= s is ExceptionStatement;
781 labels[i + 1] = s.PrepareForEmit (ec);
784 if (need_skip_finally) {
785 skip_finally = ec.GetTemporaryLocal (ec.BuiltinTypes.Bool);
787 ec.Emit (OpCodes.Stloc, skip_finally);
790 var async_init = this as AsyncInitializer;
791 if (async_init != null)
792 ec.BeginExceptionBlock ();
794 SymbolWriter.StartIteratorDispatcher (ec);
795 ec.Emit (OpCodes.Ldloc, current_pc);
796 ec.Emit (OpCodes.Switch, labels);
798 ec.Emit (async_init != null ? OpCodes.Leave : OpCodes.Br, move_next_error);
799 SymbolWriter.EndIteratorDispatcher (ec);
801 ec.MarkLabel (labels[0]);
803 iterator_body_end = ec.DefineLabel ();
805 SymbolWriter.StartIteratorBody (ec);
807 SymbolWriter.EndIteratorBody (ec);
809 SymbolWriter.StartIteratorDispatcher (ec);
811 ec.MarkLabel (iterator_body_end);
813 if (async_init != null) {
814 var catch_value = LocalVariable.CreateCompilerGenerated (ec.Module.Compiler.BuiltinTypes.Exception, block, Location);
816 ec.BeginCatchBlock (catch_value.Type);
817 catch_value.EmitAssign (ec);
820 ec.EmitInt ((int) IteratorStorey.State.After);
821 ec.Emit (OpCodes.Stfld, storey.PC.Spec);
823 ((AsyncTaskStorey) async_init.Storey).EmitSetException (ec, new LocalVariableReference (catch_value, Location));
825 ec.Emit (OpCodes.Leave, move_next_ok);
826 ec.EndExceptionBlock ();
830 ec.EmitInt ((int) IteratorStorey.State.After);
831 ec.Emit (OpCodes.Stfld, storey.PC.Spec);
833 EmitMoveNextEpilogue (ec);
835 ec.MarkLabel (move_next_error);
837 if (ReturnType.Kind != MemberKind.Void) {
839 ec.Emit (OpCodes.Ret);
842 ec.MarkLabel (move_next_ok);
844 if (ReturnType.Kind != MemberKind.Void) {
846 ec.Emit (OpCodes.Ret);
849 SymbolWriter.EndIteratorDispatcher (ec);
852 protected virtual void EmitMoveNextEpilogue (EmitContext ec)
856 public void EmitLeave (EmitContext ec, bool unwind_protect)
859 ec.Emit (unwind_protect ? OpCodes.Leave : OpCodes.Br, move_next_ok);
863 // Called back from YieldStatement
865 public virtual void InjectYield (EmitContext ec, Expression expr, int resume_pc, bool unwind_protect, Label resume_point)
868 // Guard against being disposed meantime
870 Label disposed = ec.DefineLabel ();
871 var iterator = storey as IteratorStorey;
872 if (iterator != null) {
874 ec.Emit (OpCodes.Ldfld, iterator.DisposingField.Spec);
875 ec.Emit (OpCodes.Brtrue_S, disposed);
879 // store resume program-counter
882 ec.EmitInt (resume_pc);
883 ec.Emit (OpCodes.Stfld, storey.PC.Spec);
885 if (iterator != null) {
886 ec.MarkLabel (disposed);
889 // mark finally blocks as disabled
890 if (unwind_protect && skip_finally != null) {
892 ec.Emit (OpCodes.Stloc, skip_finally);
898 // Iterators are implemented as hidden anonymous block
900 public class Iterator : StateMachineInitializer
902 public readonly IMethodData OriginalMethod;
903 public readonly bool IsEnumerable;
904 public readonly TypeSpec OriginalIteratorType;
906 public Iterator (ParametersBlock block, IMethodData method, TypeContainer host, TypeSpec iterator_type, bool is_enumerable)
907 : base (block, host, host.Compiler.BuiltinTypes.Bool)
909 this.OriginalMethod = method;
910 this.OriginalIteratorType = iterator_type;
911 this.IsEnumerable = is_enumerable;
912 this.type = method.ReturnType;
915 public Block Container {
916 get { return OriginalMethod.Block; }
919 public GenericMethod GenericMethod {
920 get { return OriginalMethod.GenericMethod; }
923 public override string ContainerType {
924 get { return "iterator"; }
927 public override bool IsIterator {
931 public void EmitYieldBreak (EmitContext ec, bool unwind_protect)
933 ec.Emit (unwind_protect ? OpCodes.Leave : OpCodes.Br, move_next_error);
936 public override string GetSignatureForError ()
938 return OriginalMethod.GetSignatureForError ();
941 public override void Emit (EmitContext ec)
944 // Load Iterator storey instance
946 storey.Instance.Emit (ec);
949 // Initialize iterator PC when it's unitialized
952 ec.Emit (OpCodes.Dup);
953 ec.EmitInt ((int)IteratorStorey.State.Uninitialized);
955 var field = storey.PC.Spec;
956 if (storey.MemberName.IsGeneric) {
957 field = MemberCache.GetMember (Storey.Instance.Type, field);
960 ec.Emit (OpCodes.Stfld, field);
964 public void EmitDispose (EmitContext ec)
966 Label end = ec.DefineLabel ();
968 Label[] labels = null;
969 int n_resume_points = resume_points == null ? 0 : resume_points.Count;
970 for (int i = 0; i < n_resume_points; ++i) {
971 ResumableStatement s = resume_points[i];
972 Label ret = s.PrepareForDispose (ec, end);
973 if (ret.Equals (end) && labels == null)
975 if (labels == null) {
976 labels = new Label[resume_points.Count + 1];
977 for (int j = 0; j <= i; ++j)
984 if (labels != null) {
985 current_pc = ec.GetTemporaryLocal (ec.BuiltinTypes.UInt);
987 ec.Emit (OpCodes.Ldfld, storey.PC.Spec);
988 ec.Emit (OpCodes.Stloc, current_pc);
993 ec.Emit (OpCodes.Stfld, ((IteratorStorey) storey).DisposingField.Spec);
996 ec.EmitInt ((int) IteratorStorey.State.After);
997 ec.Emit (OpCodes.Stfld, storey.PC.Spec);
999 if (labels != null) {
1000 //SymbolWriter.StartIteratorDispatcher (ec.ig);
1001 ec.Emit (OpCodes.Ldloc, current_pc);
1002 ec.Emit (OpCodes.Switch, labels);
1003 //SymbolWriter.EndIteratorDispatcher (ec.ig);
1005 foreach (ResumableStatement s in resume_points)
1006 s.EmitForDispose (ec, current_pc, end, true);
1012 public override void EmitStatement (EmitContext ec)
1014 throw new NotImplementedException ();
1017 public override void InjectYield (EmitContext ec, Expression expr, int resume_pc, bool unwind_protect, Label resume_point)
1019 // Store the new value into current
1020 var fe = new FieldExpr (((IteratorStorey) storey).CurrentField, loc);
1021 fe.InstanceExpression = new CompilerGeneratedThis (storey.CurrentType, loc);
1022 fe.EmitAssign (ec, expr, false, false);
1024 base.InjectYield (ec, expr, resume_pc, unwind_protect, resume_point);
1026 EmitLeave (ec, unwind_protect);
1028 ec.MarkLabel (resume_point);
1031 protected override BlockContext CreateBlockContext (ResolveContext rc)
1033 var bc = base.CreateBlockContext (rc);
1034 bc.StartFlowBranching (this, rc.CurrentBranching);
1038 public static void CreateIterator (IMethodData method, TypeContainer parent, Modifiers modifiers)
1041 TypeSpec iterator_type;
1043 TypeSpec ret = method.ReturnType;
1047 if (!CheckType (ret, parent, out iterator_type, out is_enumerable)) {
1048 parent.Compiler.Report.Error (1624, method.Location,
1049 "The body of `{0}' cannot be an iterator block " +
1050 "because `{1}' is not an iterator interface type",
1051 method.GetSignatureForError (),
1052 TypeManager.CSharpName (ret));
1056 ParametersCompiled parameters = method.ParameterInfo;
1057 for (int i = 0; i < parameters.Count; i++) {
1058 Parameter p = parameters [i];
1059 Parameter.Modifier mod = p.ModFlags;
1060 if ((mod & Parameter.Modifier.ISBYREF) != 0) {
1061 parent.Compiler.Report.Error (1623, p.Location,
1062 "Iterators cannot have ref or out parameters");
1066 if (p is ArglistParameter) {
1067 parent.Compiler.Report.Error (1636, method.Location,
1068 "__arglist is not allowed in parameter list of iterators");
1072 if (parameters.Types [i].IsPointer) {
1073 parent.Compiler.Report.Error (1637, p.Location,
1074 "Iterators cannot have unsafe parameters or yield types");
1079 if ((modifiers & Modifiers.UNSAFE) != 0) {
1080 parent.Compiler.Report.Error (1629, method.Location, "Unsafe code may not appear in iterators");
1083 method.Block.WrapIntoIterator (method, parent, iterator_type, is_enumerable);
1086 static bool CheckType (TypeSpec ret, TypeContainer parent, out TypeSpec original_iterator_type, out bool is_enumerable)
1088 original_iterator_type = null;
1089 is_enumerable = false;
1091 if (ret.BuiltinType == BuiltinTypeSpec.Type.IEnumerable) {
1092 original_iterator_type = parent.Compiler.BuiltinTypes.Object;
1093 is_enumerable = true;
1096 if (ret.BuiltinType == BuiltinTypeSpec.Type.IEnumerator) {
1097 original_iterator_type = parent.Compiler.BuiltinTypes.Object;
1098 is_enumerable = false;
1102 InflatedTypeSpec inflated = ret as InflatedTypeSpec;
1103 if (inflated == null)
1106 var member_definition = inflated.MemberDefinition;
1107 PredefinedType ptype = parent.Module.PredefinedTypes.IEnumerableGeneric;
1109 if (ptype.Define () && ptype.TypeSpec.MemberDefinition == member_definition) {
1110 original_iterator_type = inflated.TypeArguments[0];
1111 is_enumerable = true;
1115 ptype = parent.Module.PredefinedTypes.IEnumeratorGeneric;
1116 if (ptype.Define () && ptype.TypeSpec.MemberDefinition == member_definition) {
1117 original_iterator_type = inflated.TypeArguments[0];
1118 is_enumerable = false;