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;
33 protected YieldStatement (Expression expr, Location l)
39 public Expression Expr {
40 get { return this.expr; }
43 protected override void CloneTo (CloneContext clonectx, Statement t)
45 var target = (YieldStatement<T>) t;
46 target.expr = expr.Clone (clonectx);
49 protected override void DoEmit (EmitContext ec)
51 machine_initializer.InjectYield (ec, expr, resume_pc, unwind_protect, resume_point);
54 public override bool Resolve (BlockContext bc)
56 expr = expr.Resolve (bc);
60 machine_initializer = bc.CurrentAnonymousMethod as T;
62 if (!bc.CurrentBranching.CurrentUsageVector.IsUnreachable)
63 unwind_protect = bc.CurrentBranching.AddResumePoint (this, this, out resume_pc);
69 public class Yield : YieldStatement<Iterator>
71 public Yield (Expression expr, Location loc)
76 public static bool CheckContext (ResolveContext ec, Location loc)
78 if (!ec.CurrentAnonymousMethod.IsIterator) {
79 ec.Report.Error (1621, loc,
80 "The yield statement cannot be used inside anonymous method blocks");
87 public override bool Resolve (BlockContext bc)
89 if (!CheckContext (bc, loc))
92 if (!base.Resolve (bc))
95 var otype = bc.CurrentIterator.OriginalIteratorType;
96 if (expr.Type != otype) {
97 expr = Convert.ImplicitConversionRequired (bc, expr, otype, loc);
105 public override object Accept (StructuralVisitor visitor)
107 return visitor.Visit (this);
111 public class YieldBreak : ExitStatement
115 public YieldBreak (Location l)
120 public override void Error_FinallyClause (Report Report)
122 Report.Error (1625, loc, "Cannot yield in the body of a finally clause");
125 protected override void CloneTo (CloneContext clonectx, Statement target)
127 throw new NotSupportedException ();
130 protected override bool DoResolve (BlockContext ec)
132 iterator = ec.CurrentIterator;
133 return Yield.CheckContext (ec, loc);
136 protected override void DoEmit (EmitContext ec)
138 iterator.EmitYieldBreak (ec, unwind_protect);
141 public override object Accept (StructuralVisitor visitor)
143 return visitor.Visit (this);
147 public abstract class StateMachine : AnonymousMethodStorey
151 Running = -3, // Used only in CurrentPC, never stored into $PC
158 StateMachineMethod method;
161 protected StateMachine (ParametersBlock block, TypeDefinition parent, MemberBase host, TypeParameters tparams, string name, MemberKind kind)
162 : base (block, parent, host, tparams, name, kind)
168 public StateMachineMethod StateMachineMethod {
182 public void AddEntryMethod (StateMachineMethod method)
184 if (this.method != null)
185 throw new InternalErrorException ();
187 this.method = method;
188 Members.Add (method);
191 protected override bool DoDefineMembers ()
193 pc_field = AddCompilerGeneratedField ("$PC", new TypeExpression (Compiler.BuiltinTypes.Int, Location));
195 return base.DoDefineMembers ();
198 protected override string GetVariableMangledName (LocalVariable local_info)
200 if (local_info.IsCompilerGenerated)
201 return base.GetVariableMangledName (local_info);
203 return "<" + local_info.Name + ">__" + local_name_idx++.ToString ("X");
207 class IteratorStorey : StateMachine
209 class GetEnumeratorMethod : StateMachineMethod
211 sealed class GetEnumeratorStatement : Statement
213 readonly IteratorStorey host;
214 readonly StateMachineMethod host_method;
216 Expression new_storey;
218 public GetEnumeratorStatement (IteratorStorey host, StateMachineMethod host_method)
221 this.host_method = host_method;
222 loc = host_method.Location;
225 protected override void CloneTo (CloneContext clonectx, Statement target)
227 throw new NotSupportedException ();
230 public override bool Resolve (BlockContext ec)
232 TypeExpression storey_type_expr = new TypeExpression (host.Definition, loc);
233 List<Expression> init = null;
234 if (host.hoisted_this != null) {
235 init = new List<Expression> (host.hoisted_params == null ? 1 : host.HoistedParameters.Count + 1);
236 HoistedThis ht = host.hoisted_this;
237 FieldExpr from = new FieldExpr (ht.Field, loc);
238 from.InstanceExpression = new CompilerGeneratedThis (ec.CurrentType, loc);
239 init.Add (new ElementInitializer (ht.Field.Name, from, loc));
242 if (host.hoisted_params != null) {
244 init = new List<Expression> (host.HoistedParameters.Count);
246 for (int i = 0; i < host.hoisted_params.Count; ++i) {
247 HoistedParameter hp = host.hoisted_params [i];
248 HoistedParameter hp_cp = host.hoisted_params_copy [i] ?? hp;
250 FieldExpr from = new FieldExpr (hp_cp.Field, loc);
251 from.InstanceExpression = new CompilerGeneratedThis (ec.CurrentType, loc);
253 init.Add (new ElementInitializer (hp.Field.Name, from, loc));
258 new_storey = new NewInitialize (storey_type_expr, null,
259 new CollectionOrObjectInitializers (init, loc), loc);
261 new_storey = new New (storey_type_expr, null, loc);
264 new_storey = new_storey.Resolve (ec);
265 if (new_storey != null)
266 new_storey = Convert.ImplicitConversionRequired (ec, new_storey, host_method.MemberType, loc);
268 ec.CurrentBranching.CurrentUsageVector.Goto ();
272 protected override void DoEmit (EmitContext ec)
274 Label label_init = ec.DefineLabel ();
277 ec.Emit (OpCodes.Ldflda, host.PC.Spec);
278 ec.EmitInt ((int) State.Start);
279 ec.EmitInt ((int) State.Uninitialized);
281 var m = ec.Module.PredefinedMembers.InterlockedCompareExchange.Resolve (loc);
283 ec.Emit (OpCodes.Call, m);
285 ec.EmitInt ((int) State.Uninitialized);
286 ec.Emit (OpCodes.Bne_Un_S, label_init);
289 ec.Emit (OpCodes.Ret);
291 ec.MarkLabel (label_init);
293 new_storey.Emit (ec);
294 ec.Emit (OpCodes.Ret);
298 GetEnumeratorMethod (IteratorStorey host, FullNamedExpression returnType, MemberName name)
299 : base (host, null, returnType, Modifiers.DEBUGGER_HIDDEN, name)
303 public static GetEnumeratorMethod Create (IteratorStorey host, FullNamedExpression returnType, MemberName name)
305 return Create (host, returnType, name, null);
308 public static GetEnumeratorMethod Create (IteratorStorey host, FullNamedExpression returnType, MemberName name, Statement statement)
310 var m = new GetEnumeratorMethod (host, returnType, name);
311 var stmt = statement ?? new GetEnumeratorStatement (host, m);
312 m.block.AddStatement (stmt);
313 m.block.IsCompilerGenerated = true;
318 class DisposeMethod : StateMachineMethod
320 sealed class DisposeMethodStatement : Statement
324 public DisposeMethodStatement (Iterator iterator)
326 this.iterator = iterator;
327 this.loc = iterator.Location;
330 protected override void CloneTo (CloneContext clonectx, Statement target)
332 throw new NotSupportedException ();
335 public override bool Resolve (BlockContext ec)
340 protected override void DoEmit (EmitContext ec)
342 ec.CurrentAnonymousMethod = iterator;
343 iterator.EmitDispose (ec);
347 public DisposeMethod (IteratorStorey host)
348 : base (host, null, new TypeExpression (host.Compiler.BuiltinTypes.Void, host.Location), Modifiers.PUBLIC | Modifiers.DEBUGGER_HIDDEN,
349 new MemberName ("Dispose", host.Location))
351 host.Members.Add (this);
353 Block.AddStatement (new DisposeMethodStatement (host.Iterator));
354 Block.IsCompilerGenerated = true;
359 // Uses Method as method info
361 class DynamicMethodGroupExpr : MethodGroupExpr
363 readonly Method method;
365 public DynamicMethodGroupExpr (Method method, Location loc)
366 : base ((IList<MemberSpec>) null, null, loc)
368 this.method = method;
369 eclass = ExprClass.Unresolved;
372 protected override Expression DoResolve (ResolveContext ec)
374 Methods = new List<MemberSpec> (1) { method.Spec };
375 type = method.Parent.Definition;
376 InstanceExpression = new CompilerGeneratedThis (type, Location);
377 return base.DoResolve (ec);
381 class DynamicFieldExpr : FieldExpr
383 readonly Field field;
385 public DynamicFieldExpr (Field field, Location loc)
391 protected override Expression DoResolve (ResolveContext ec)
394 type = spec.MemberType;
395 InstanceExpression = new CompilerGeneratedThis (type, Location);
396 return base.DoResolve (ec);
400 public readonly Iterator Iterator;
402 List<HoistedParameter> hoisted_params_copy;
404 TypeExpr iterator_type_expr;
406 Field disposing_field;
408 TypeSpec generic_enumerator_type;
409 TypeSpec generic_enumerable_type;
411 public IteratorStorey (Iterator iterator)
412 : base (iterator.Container.ParametersBlock, iterator.Host,
413 iterator.OriginalMethod as MemberBase, iterator.OriginalMethod.CurrentTypeParameters, "Iterator", MemberKind.Class)
415 this.Iterator = iterator;
418 public Field CurrentField {
420 return current_field;
424 public Field DisposingField {
426 return disposing_field;
430 public IList<HoistedParameter> HoistedParameters {
431 get { return hoisted_params; }
434 protected override Constructor DefineDefaultConstructor (bool is_static)
436 var ctor = base.DefineDefaultConstructor (is_static);
437 ctor.ModFlags |= Modifiers.DEBUGGER_HIDDEN;
441 protected override TypeSpec[] ResolveBaseTypes (out FullNamedExpression base_class)
443 var mtype = Iterator.OriginalIteratorType;
445 mtype = Mutator.Mutate (mtype);
447 iterator_type_expr = new TypeExpression (mtype, Location);
449 var ifaces = new List<TypeSpec> (5);
450 if (Iterator.IsEnumerable) {
451 ifaces.Add (Compiler.BuiltinTypes.IEnumerable);
453 if (Module.PredefinedTypes.IEnumerableGeneric.Define ()) {
454 generic_enumerable_type = Module.PredefinedTypes.IEnumerableGeneric.TypeSpec.MakeGenericType (Module, new[] { mtype });
455 ifaces.Add (generic_enumerable_type);
459 ifaces.Add (Compiler.BuiltinTypes.IEnumerator);
460 ifaces.Add (Compiler.BuiltinTypes.IDisposable);
462 var ienumerator_generic = Module.PredefinedTypes.IEnumeratorGeneric;
463 if (ienumerator_generic.Define ()) {
464 generic_enumerator_type = ienumerator_generic.TypeSpec.MakeGenericType (Module, new [] { mtype });
465 ifaces.Add (generic_enumerator_type);
470 base_type = Compiler.BuiltinTypes.Object;
471 return ifaces.ToArray ();
474 protected override bool DoDefineMembers ()
476 current_field = AddCompilerGeneratedField ("$current", iterator_type_expr);
477 disposing_field = AddCompilerGeneratedField ("$disposing", new TypeExpression (Compiler.BuiltinTypes.Bool, Location));
479 if (Iterator.IsEnumerable && hoisted_params != null) {
481 // Iterators are independent, each GetEnumerator call has to
482 // create same enumerator therefore we have to keep original values
483 // around for re-initialization
485 hoisted_params_copy = new List<HoistedParameter> (hoisted_params.Count);
486 foreach (HoistedParameter hp in hoisted_params) {
489 // Don't create field copy for unmodified captured parameters
491 HoistedParameter hp_copy;
493 hp_copy = new HoistedParameter (hp, "<$>" + hp.Field.Name);
498 hoisted_params_copy.Add (hp_copy);
502 if (generic_enumerator_type != null)
503 Define_Current (true);
505 Define_Current (false);
506 new DisposeMethod (this);
509 if (Iterator.IsEnumerable) {
510 FullNamedExpression explicit_iface = new TypeExpression (Compiler.BuiltinTypes.IEnumerable, Location);
511 var name = new MemberName ("GetEnumerator", null, explicit_iface, Location.Null);
513 if (generic_enumerator_type != null) {
514 explicit_iface = new TypeExpression (generic_enumerable_type, Location);
515 var gname = new MemberName ("GetEnumerator", null, explicit_iface, Location.Null);
516 Method gget_enumerator = GetEnumeratorMethod.Create (this, new TypeExpression (generic_enumerator_type, Location), gname);
519 // Just call generic GetEnumerator implementation
521 var stmt = new Return (new Invocation (new DynamicMethodGroupExpr (gget_enumerator, Location), null), Location);
522 Method get_enumerator = GetEnumeratorMethod.Create (this, new TypeExpression (Compiler.BuiltinTypes.IEnumerator, Location), name, stmt);
524 Members.Add (get_enumerator);
525 Members.Add (gget_enumerator);
527 Members.Add (GetEnumeratorMethod.Create (this, new TypeExpression (Compiler.BuiltinTypes.IEnumerator, Location), name));
531 return base.DoDefineMembers ();
534 void Define_Current (bool is_generic)
537 FullNamedExpression explicit_iface;
540 explicit_iface = new TypeExpression (generic_enumerator_type, Location);
541 type = iterator_type_expr;
543 explicit_iface = new TypeExpression (Module.Compiler.BuiltinTypes.IEnumerator, Location);
544 type = new TypeExpression (Compiler.BuiltinTypes.Object, Location);
547 var name = new MemberName ("Current", null, explicit_iface, Location);
549 ToplevelBlock get_block = new ToplevelBlock (Compiler, Location) {
550 IsCompilerGenerated = true
552 get_block.AddStatement (new Return (new DynamicFieldExpr (CurrentField, Location), Location));
554 Property current = new Property (this, type, Modifiers.DEBUGGER_HIDDEN | Modifiers.COMPILER_GENERATED, name, null);
555 current.Get = new Property.GetMethod (current, Modifiers.COMPILER_GENERATED, null, Location);
556 current.Get.Block = get_block;
558 Members.Add (current);
563 Method reset = new Method (
564 this, new TypeExpression (Compiler.BuiltinTypes.Void, Location),
565 Modifiers.PUBLIC | Modifiers.DEBUGGER_HIDDEN | Modifiers.COMPILER_GENERATED,
566 new MemberName ("Reset", Location),
567 ParametersCompiled.EmptyReadOnlyParameters, null);
570 reset.Block = new ToplevelBlock (Compiler, Location) {
571 IsCompilerGenerated = true
574 TypeSpec ex_type = Module.PredefinedTypes.NotSupportedException.Resolve ();
578 reset.Block.AddStatement (new Throw (new New (new TypeExpression (ex_type, Location), null, Location), Location));
581 protected override void EmitHoistedParameters (EmitContext ec, List<HoistedParameter> hoisted)
583 base.EmitHoistedParameters (ec, hoisted);
584 if (hoisted_params_copy != null)
585 base.EmitHoistedParameters (ec, hoisted_params_copy);
589 public class StateMachineMethod : Method
591 readonly StateMachineInitializer expr;
593 public StateMachineMethod (StateMachine host, StateMachineInitializer expr, FullNamedExpression returnType, Modifiers mod, MemberName name)
594 : base (host, returnType, mod | Modifiers.COMPILER_GENERATED,
595 name, ParametersCompiled.EmptyReadOnlyParameters, null)
598 Block = new ToplevelBlock (host.Compiler, ParametersCompiled.EmptyReadOnlyParameters, Location.Null);
601 public override EmitContext CreateEmitContext (ILGenerator ig, SourceMethodBuilder sourceMethod)
603 EmitContext ec = new EmitContext (this, ig, MemberType, sourceMethod);
604 ec.CurrentAnonymousMethod = expr;
606 if (expr is AsyncInitializer)
607 ec.With (BuilderContext.Options.AsyncBody, true);
613 public abstract class StateMachineInitializer : AnonymousExpression
615 sealed class MoveNextBodyStatement : Statement
617 readonly StateMachineInitializer state_machine;
619 public MoveNextBodyStatement (StateMachineInitializer stateMachine)
621 this.state_machine = stateMachine;
622 this.loc = stateMachine.Location;
625 protected override void CloneTo (CloneContext clonectx, Statement target)
627 throw new NotSupportedException ();
630 public override bool Resolve (BlockContext ec)
635 protected override void DoEmit (EmitContext ec)
637 state_machine.EmitMoveNext (ec);
640 public override void Emit (EmitContext ec)
642 // Don't create sequence point
647 public readonly TypeDefinition Host;
648 protected StateMachine storey;
651 // The state as we generate the machine
654 Label iterator_body_end;
655 protected Label move_next_error;
656 LocalBuilder skip_finally;
657 protected LocalBuilder current_pc;
658 protected List<ResumableStatement> resume_points;
660 protected StateMachineInitializer (ParametersBlock block, TypeDefinition host, TypeSpec returnType)
661 : base (block, returnType, block.StartLocation)
668 public Label BodyEnd {
670 return iterator_body_end;
674 public LocalBuilder CurrentPC
681 public LocalBuilder SkipFinally {
687 public override AnonymousMethodStorey Storey {
695 public int AddResumePoint (ResumableStatement stmt)
697 if (resume_points == null)
698 resume_points = new List<ResumableStatement> ();
700 resume_points.Add (stmt);
701 return resume_points.Count;
704 public override Expression CreateExpressionTree (ResolveContext ec)
706 throw new NotSupportedException ("ET");
709 protected virtual BlockContext CreateBlockContext (ResolveContext rc)
711 var ctx = new BlockContext (rc, block, ((BlockContext) rc).ReturnType);
712 ctx.CurrentAnonymousMethod = this;
716 protected override Expression DoResolve (ResolveContext ec)
718 var ctx = CreateBlockContext (ec);
723 // Explicit return is required for Task<T> state machine
725 var task_storey = storey as AsyncTaskStorey;
726 if (task_storey == null || (task_storey.ReturnType != null && !task_storey.ReturnType.IsGenericTask))
727 ctx.CurrentBranching.CurrentUsageVector.Goto ();
729 ctx.EndFlowBranching ();
731 if (!ec.IsInProbingMode) {
732 var move_next = new StateMachineMethod (storey, this, new TypeExpression (ReturnType, loc), Modifiers.PUBLIC, new MemberName ("MoveNext", loc));
733 move_next.Block.AddStatement (new MoveNextBodyStatement (this));
734 storey.AddEntryMethod (move_next);
737 eclass = ExprClass.Value;
741 public override void Emit (EmitContext ec)
744 // Load state machine instance
746 storey.Instance.Emit (ec);
749 void EmitMoveNext_NoResumePoints (EmitContext ec)
752 ec.Emit (OpCodes.Ldfld, storey.PC.Spec);
755 ec.EmitInt ((int) IteratorStorey.State.After);
756 ec.Emit (OpCodes.Stfld, storey.PC.Spec);
758 // We only care if the PC is zero (start executing) or non-zero (don't do anything)
759 ec.Emit (OpCodes.Brtrue, move_next_error);
761 iterator_body_end = ec.DefineLabel ();
763 block.EmitEmbedded (ec);
765 ec.MarkLabel (iterator_body_end);
767 EmitMoveNextEpilogue (ec);
769 ec.MarkLabel (move_next_error);
771 if (ReturnType.Kind != MemberKind.Void) {
773 ec.Emit (OpCodes.Ret);
777 void EmitMoveNext (EmitContext ec)
779 move_next_ok = ec.DefineLabel ();
780 move_next_error = ec.DefineLabel ();
782 if (resume_points == null) {
783 EmitMoveNext_NoResumePoints (ec);
787 current_pc = ec.GetTemporaryLocal (ec.BuiltinTypes.UInt);
789 ec.Emit (OpCodes.Ldfld, storey.PC.Spec);
790 ec.Emit (OpCodes.Stloc, current_pc);
792 // We're actually in state 'running', but this is as good a PC value as any if there's an abnormal exit
794 ec.EmitInt ((int) IteratorStorey.State.After);
795 ec.Emit (OpCodes.Stfld, storey.PC.Spec);
797 Label[] labels = new Label[1 + resume_points.Count];
798 labels[0] = ec.DefineLabel ();
800 bool need_skip_finally = false;
801 for (int i = 0; i < resume_points.Count; ++i) {
802 ResumableStatement s = resume_points[i];
803 need_skip_finally |= s is ExceptionStatement;
804 labels[i + 1] = s.PrepareForEmit (ec);
807 if (need_skip_finally) {
808 skip_finally = ec.GetTemporaryLocal (ec.BuiltinTypes.Bool);
810 ec.Emit (OpCodes.Stloc, skip_finally);
813 var async_init = this as AsyncInitializer;
814 if (async_init != null)
815 ec.BeginExceptionBlock ();
817 ec.Emit (OpCodes.Ldloc, current_pc);
818 ec.Emit (OpCodes.Switch, labels);
820 ec.Emit (async_init != null ? OpCodes.Leave : OpCodes.Br, move_next_error);
822 ec.MarkLabel (labels[0]);
824 iterator_body_end = ec.DefineLabel ();
826 block.EmitEmbedded (ec);
828 ec.MarkLabel (iterator_body_end);
830 if (async_init != null) {
831 var catch_value = LocalVariable.CreateCompilerGenerated (ec.Module.Compiler.BuiltinTypes.Exception, block, Location);
833 ec.BeginCatchBlock (catch_value.Type);
834 catch_value.EmitAssign (ec);
837 ec.EmitInt ((int) IteratorStorey.State.After);
838 ec.Emit (OpCodes.Stfld, storey.PC.Spec);
840 ((AsyncTaskStorey) async_init.Storey).EmitSetException (ec, new LocalVariableReference (catch_value, Location));
842 ec.Emit (OpCodes.Leave, move_next_ok);
843 ec.EndExceptionBlock ();
846 ec.Mark (Block.Original.EndLocation);
848 ec.EmitInt ((int) IteratorStorey.State.After);
849 ec.Emit (OpCodes.Stfld, storey.PC.Spec);
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);
862 if (ReturnType.Kind != MemberKind.Void) {
864 ec.Emit (OpCodes.Ret);
868 protected virtual void EmitMoveNextEpilogue (EmitContext ec)
872 public void EmitLeave (EmitContext ec, bool unwind_protect)
875 ec.Emit (unwind_protect ? OpCodes.Leave : OpCodes.Br, move_next_ok);
879 // Called back from YieldStatement
881 public virtual void InjectYield (EmitContext ec, Expression expr, int resume_pc, bool unwind_protect, Label resume_point)
884 // Guard against being disposed meantime
886 Label disposed = ec.DefineLabel ();
887 var iterator = storey as IteratorStorey;
888 if (iterator != null) {
890 ec.Emit (OpCodes.Ldfld, iterator.DisposingField.Spec);
891 ec.Emit (OpCodes.Brtrue_S, disposed);
895 // store resume program-counter
898 ec.EmitInt (resume_pc);
899 ec.Emit (OpCodes.Stfld, storey.PC.Spec);
901 if (iterator != null) {
902 ec.MarkLabel (disposed);
905 // mark finally blocks as disabled
906 if (unwind_protect && skip_finally != null) {
908 ec.Emit (OpCodes.Stloc, skip_finally);
912 public void SetStateMachine (StateMachine stateMachine)
914 this.storey = stateMachine;
919 // Iterators are implemented as state machine blocks
921 public class Iterator : StateMachineInitializer
923 sealed class TryFinallyBlockProxyStatement : Statement
925 TryFinallyBlock block;
928 public TryFinallyBlockProxyStatement (Iterator iterator, TryFinallyBlock block)
930 this.iterator = iterator;
934 protected override void CloneTo (CloneContext clonectx, Statement target)
936 throw new NotSupportedException ();
939 protected override void DoEmit (EmitContext ec)
942 // Restore redirection for any captured variables
944 ec.CurrentAnonymousMethod = iterator;
946 using (ec.With (BuilderContext.Options.OmitDebugInfo, !ec.HasMethodSymbolBuilder)) {
947 block.EmitFinallyBody (ec);
952 public readonly IMethodData OriginalMethod;
953 public readonly bool IsEnumerable;
954 public readonly TypeSpec OriginalIteratorType;
955 int finally_hosts_counter;
957 public Iterator (ParametersBlock block, IMethodData method, TypeDefinition host, TypeSpec iterator_type, bool is_enumerable)
958 : base (block, host, host.Compiler.BuiltinTypes.Bool)
960 this.OriginalMethod = method;
961 this.OriginalIteratorType = iterator_type;
962 this.IsEnumerable = is_enumerable;
963 this.type = method.ReturnType;
968 public ToplevelBlock Container {
969 get { return OriginalMethod.Block; }
972 public override string ContainerType {
973 get { return "iterator"; }
976 public override bool IsIterator {
982 public Method CreateFinallyHost (TryFinallyBlock block)
984 var method = new Method (storey, new TypeExpression (storey.Compiler.BuiltinTypes.Void, loc),
985 Modifiers.COMPILER_GENERATED, new MemberName (CompilerGeneratedContainer.MakeName (null, null, "Finally", finally_hosts_counter++), loc),
986 ParametersCompiled.EmptyReadOnlyParameters, null);
988 method.Block = new ToplevelBlock (method.Compiler, method.ParameterInfo, loc);
989 method.Block.IsCompilerGenerated = true;
990 method.Block.AddStatement (new TryFinallyBlockProxyStatement (this, block));
992 // Cannot it add to storey because it'd be emitted before nested
993 // anonoymous methods which could capture shared variable
998 public void EmitYieldBreak (EmitContext ec, bool unwind_protect)
1000 ec.Emit (unwind_protect ? OpCodes.Leave : OpCodes.Br, move_next_error);
1003 public override string GetSignatureForError ()
1005 return OriginalMethod.GetSignatureForError ();
1008 public override void Emit (EmitContext ec)
1011 // Load Iterator storey instance
1013 storey.Instance.Emit (ec);
1016 // Initialize iterator PC when it's unitialized
1019 ec.Emit (OpCodes.Dup);
1020 ec.EmitInt ((int)IteratorStorey.State.Uninitialized);
1022 var field = storey.PC.Spec;
1023 if (storey.MemberName.IsGeneric) {
1024 field = MemberCache.GetMember (Storey.Instance.Type, field);
1027 ec.Emit (OpCodes.Stfld, field);
1031 public void EmitDispose (EmitContext ec)
1033 if (resume_points == null)
1036 Label end = ec.DefineLabel ();
1038 Label[] labels = null;
1039 for (int i = 0; i < resume_points.Count; ++i) {
1040 ResumableStatement s = resume_points[i];
1041 Label ret = s.PrepareForDispose (ec, end);
1042 if (ret.Equals (end) && labels == null)
1044 if (labels == null) {
1045 labels = new Label[resume_points.Count + 1];
1046 for (int j = 0; j <= i; ++j)
1050 labels[i + 1] = ret;
1053 if (labels != null) {
1054 current_pc = ec.GetTemporaryLocal (ec.BuiltinTypes.UInt);
1056 ec.Emit (OpCodes.Ldfld, storey.PC.Spec);
1057 ec.Emit (OpCodes.Stloc, current_pc);
1062 ec.Emit (OpCodes.Stfld, ((IteratorStorey) storey).DisposingField.Spec);
1065 ec.EmitInt ((int) IteratorStorey.State.After);
1066 ec.Emit (OpCodes.Stfld, storey.PC.Spec);
1068 if (labels != null) {
1069 //SymbolWriter.StartIteratorDispatcher (ec.ig);
1070 ec.Emit (OpCodes.Ldloc, current_pc);
1071 ec.Emit (OpCodes.Switch, labels);
1072 //SymbolWriter.EndIteratorDispatcher (ec.ig);
1074 foreach (ResumableStatement s in resume_points)
1075 s.EmitForDispose (ec, current_pc, end, true);
1081 public override void EmitStatement (EmitContext ec)
1083 throw new NotImplementedException ();
1086 public override void InjectYield (EmitContext ec, Expression expr, int resume_pc, bool unwind_protect, Label resume_point)
1088 // Store the new value into current
1089 var fe = new FieldExpr (((IteratorStorey) storey).CurrentField, loc);
1090 fe.InstanceExpression = new CompilerGeneratedThis (storey.CurrentType, loc);
1091 fe.EmitAssign (ec, expr, false, false);
1093 base.InjectYield (ec, expr, resume_pc, unwind_protect, resume_point);
1095 EmitLeave (ec, unwind_protect);
1097 ec.MarkLabel (resume_point);
1100 protected override BlockContext CreateBlockContext (ResolveContext rc)
1102 var bc = base.CreateBlockContext (rc);
1103 bc.StartFlowBranching (this, rc.CurrentBranching);
1107 public static void CreateIterator (IMethodData method, TypeDefinition parent, Modifiers modifiers)
1110 TypeSpec iterator_type;
1112 TypeSpec ret = method.ReturnType;
1116 if (!CheckType (ret, parent, out iterator_type, out is_enumerable)) {
1117 parent.Compiler.Report.Error (1624, method.Location,
1118 "The body of `{0}' cannot be an iterator block " +
1119 "because `{1}' is not an iterator interface type",
1120 method.GetSignatureForError (),
1121 ret.GetSignatureForError ());
1125 ParametersCompiled parameters = method.ParameterInfo;
1126 for (int i = 0; i < parameters.Count; i++) {
1127 Parameter p = parameters [i];
1128 Parameter.Modifier mod = p.ModFlags;
1129 if ((mod & Parameter.Modifier.RefOutMask) != 0) {
1130 parent.Compiler.Report.Error (1623, p.Location,
1131 "Iterators cannot have ref or out parameters");
1135 if (p is ArglistParameter) {
1136 parent.Compiler.Report.Error (1636, method.Location,
1137 "__arglist is not allowed in parameter list of iterators");
1141 if (parameters.Types [i].IsPointer) {
1142 parent.Compiler.Report.Error (1637, p.Location,
1143 "Iterators cannot have unsafe parameters or yield types");
1148 if ((modifiers & Modifiers.UNSAFE) != 0) {
1149 parent.Compiler.Report.Error (1629, method.Location, "Unsafe code may not appear in iterators");
1152 method.Block = method.Block.ConvertToIterator (method, parent, iterator_type, is_enumerable);
1155 static bool CheckType (TypeSpec ret, TypeContainer parent, out TypeSpec original_iterator_type, out bool is_enumerable)
1157 original_iterator_type = null;
1158 is_enumerable = false;
1160 if (ret.BuiltinType == BuiltinTypeSpec.Type.IEnumerable) {
1161 original_iterator_type = parent.Compiler.BuiltinTypes.Object;
1162 is_enumerable = true;
1165 if (ret.BuiltinType == BuiltinTypeSpec.Type.IEnumerator) {
1166 original_iterator_type = parent.Compiler.BuiltinTypes.Object;
1167 is_enumerable = false;
1171 InflatedTypeSpec inflated = ret as InflatedTypeSpec;
1172 if (inflated == null)
1175 var member_definition = inflated.MemberDefinition;
1176 PredefinedType ptype = parent.Module.PredefinedTypes.IEnumerableGeneric;
1178 if (ptype.Define () && ptype.TypeSpec.MemberDefinition == member_definition) {
1179 original_iterator_type = inflated.TypeArguments[0];
1180 is_enumerable = true;
1184 ptype = parent.Module.PredefinedTypes.IEnumeratorGeneric;
1185 if (ptype.Define () && ptype.TypeSpec.MemberDefinition == member_definition) {
1186 original_iterator_type = inflated.TypeArguments[0];
1187 is_enumerable = false;