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, 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];
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 TypeSpec[] ResolveBaseTypes (out FullNamedExpression base_class)
436
var mtype = Iterator.OriginalIteratorType;
438
mtype = Mutator.Mutate (mtype);
440
iterator_type_expr = new TypeExpression (mtype, Location);
442
var ifaces = new List<TypeSpec> (5);
443
if (Iterator.IsEnumerable) {
444
ifaces.Add (Compiler.BuiltinTypes.IEnumerable);
446
if (Module.PredefinedTypes.IEnumerableGeneric.Define ()) {
447
generic_enumerable_type = Module.PredefinedTypes.IEnumerableGeneric.TypeSpec.MakeGenericType (Module, new[] { mtype });
448
ifaces.Add (generic_enumerable_type);
452
ifaces.Add (Compiler.BuiltinTypes.IEnumerator);
453
ifaces.Add (Compiler.BuiltinTypes.IDisposable);
455
var ienumerator_generic = Module.PredefinedTypes.IEnumeratorGeneric;
456
if (ienumerator_generic.Define ()) {
457
generic_enumerator_type = ienumerator_generic.TypeSpec.MakeGenericType (Module, new [] { mtype });
458
ifaces.Add (generic_enumerator_type);
463
base_type = Compiler.BuiltinTypes.Object;
464
return ifaces.ToArray ();
467
protected override bool DoDefineMembers ()
469
current_field = AddCompilerGeneratedField ("$current", iterator_type_expr);
470
disposing_field = AddCompilerGeneratedField ("$disposing", new TypeExpression (Compiler.BuiltinTypes.Bool, Location));
472
if (hoisted_params != null) {
474
// Iterators are independent, each GetEnumerator call has to
475
// create same enumerator therefore we have to keep original values
476
// around for re-initialization
478
// TODO: Do it for assigned/modified parameters only
480
hoisted_params_copy = new List<HoistedParameter> (hoisted_params.Count);
481
foreach (HoistedParameter hp in hoisted_params) {
482
hoisted_params_copy.Add (new HoistedParameter (hp, "<$>" + hp.Field.Name));
486
if (generic_enumerator_type != null)
487
Define_Current (true);
489
Define_Current (false);
490
new DisposeMethod (this);
493
if (Iterator.IsEnumerable) {
494
FullNamedExpression explicit_iface = new TypeExpression (Compiler.BuiltinTypes.IEnumerable, Location);
495
var name = new MemberName ("GetEnumerator", null, explicit_iface, Location.Null);
497
if (generic_enumerator_type != null) {
498
explicit_iface = new TypeExpression (generic_enumerable_type, Location);
499
var gname = new MemberName ("GetEnumerator", null, explicit_iface, Location.Null);
500
Method gget_enumerator = GetEnumeratorMethod.Create (this, new TypeExpression (generic_enumerator_type, Location), gname);
503
// Just call generic GetEnumerator implementation
505
var stmt = new Return (new Invocation (new DynamicMethodGroupExpr (gget_enumerator, Location), null), Location);
506
Method get_enumerator = GetEnumeratorMethod.Create (this, new TypeExpression (Compiler.BuiltinTypes.IEnumerator, Location), name, stmt);
508
Members.Add (get_enumerator);
509
Members.Add (gget_enumerator);
511
Members.Add (GetEnumeratorMethod.Create (this, new TypeExpression (Compiler.BuiltinTypes.IEnumerator, Location), name));
515
return base.DoDefineMembers ();
518
void Define_Current (bool is_generic)
521
FullNamedExpression explicit_iface;
524
explicit_iface = new TypeExpression (generic_enumerator_type, Location);
525
type = iterator_type_expr;
527
explicit_iface = new TypeExpression (Module.Compiler.BuiltinTypes.IEnumerator, Location);
528
type = new TypeExpression (Compiler.BuiltinTypes.Object, Location);
531
var name = new MemberName ("Current", null, explicit_iface, Location);
533
ToplevelBlock get_block = new ToplevelBlock (Compiler, Location) {
534
IsCompilerGenerated = true
536
get_block.AddStatement (new Return (new DynamicFieldExpr (CurrentField, Location), Location));
538
Property current = new Property (this, type, Modifiers.DEBUGGER_HIDDEN | Modifiers.COMPILER_GENERATED, name, null);
539
current.Get = new Property.GetMethod (current, Modifiers.COMPILER_GENERATED, null, Location);
540
current.Get.Block = get_block;
542
Members.Add (current);
547
Method reset = new Method (
548
this, new TypeExpression (Compiler.BuiltinTypes.Void, Location),
549
Modifiers.PUBLIC | Modifiers.DEBUGGER_HIDDEN | Modifiers.COMPILER_GENERATED,
550
new MemberName ("Reset", Location),
551
ParametersCompiled.EmptyReadOnlyParameters, null);
554
reset.Block = new ToplevelBlock (Compiler, Location) {
555
IsCompilerGenerated = true
558
TypeSpec ex_type = Module.PredefinedTypes.NotSupportedException.Resolve ();
562
reset.Block.AddStatement (new Throw (new New (new TypeExpression (ex_type, Location), null, Location), Location));
565
protected override void EmitHoistedParameters (EmitContext ec, List<HoistedParameter> hoisted)
567
base.EmitHoistedParameters (ec, hoisted);
568
base.EmitHoistedParameters (ec, hoisted_params_copy);
572
public class StateMachineMethod : Method
574
readonly StateMachineInitializer expr;
576
public StateMachineMethod (StateMachine host, StateMachineInitializer expr, FullNamedExpression returnType, Modifiers mod, MemberName name)
577
: base (host, returnType, mod | Modifiers.COMPILER_GENERATED,
578
name, ParametersCompiled.EmptyReadOnlyParameters, null)
581
Block = new ToplevelBlock (host.Compiler, ParametersCompiled.EmptyReadOnlyParameters, Location.Null);
584
public override EmitContext CreateEmitContext (ILGenerator ig, SourceMethodBuilder sourceMethod)
586
EmitContext ec = new EmitContext (this, ig, MemberType, sourceMethod);
587
ec.CurrentAnonymousMethod = expr;
589
if (expr is AsyncInitializer)
590
ec.With (BuilderContext.Options.AsyncBody, true);
596
public abstract class StateMachineInitializer : AnonymousExpression
598
sealed class MoveNextBodyStatement : Statement
600
readonly StateMachineInitializer state_machine;
602
public MoveNextBodyStatement (StateMachineInitializer stateMachine)
604
this.state_machine = stateMachine;
605
this.loc = stateMachine.Location;
608
protected override void CloneTo (CloneContext clonectx, Statement target)
610
throw new NotSupportedException ();
613
public override bool Resolve (BlockContext ec)
618
protected override void DoEmit (EmitContext ec)
620
state_machine.EmitMoveNext (ec);
623
public override void Emit (EmitContext ec)
625
// Don't create sequence point
630
public readonly TypeDefinition Host;
631
protected StateMachine storey;
634
// The state as we generate the machine
637
Label iterator_body_end;
638
protected Label move_next_error;
639
LocalBuilder skip_finally;
640
protected LocalBuilder current_pc;
641
protected List<ResumableStatement> resume_points;
643
protected StateMachineInitializer (ParametersBlock block, TypeDefinition host, TypeSpec returnType)
644
: base (block, returnType, block.StartLocation)
651
public Label BodyEnd {
653
return iterator_body_end;
657
public LocalBuilder CurrentPC
664
public LocalBuilder SkipFinally {
670
public override AnonymousMethodStorey Storey {
678
public int AddResumePoint (ResumableStatement stmt)
680
if (resume_points == null)
681
resume_points = new List<ResumableStatement> ();
683
resume_points.Add (stmt);
684
return resume_points.Count;
687
public override Expression CreateExpressionTree (ResolveContext ec)
689
throw new NotSupportedException ("ET");
692
protected virtual BlockContext CreateBlockContext (ResolveContext rc)
694
var ctx = new BlockContext (rc, block, ((BlockContext) rc).ReturnType);
695
ctx.CurrentAnonymousMethod = this;
699
protected override Expression DoResolve (ResolveContext ec)
701
var ctx = CreateBlockContext (ec);
706
// Explicit return is required for Task<T> state machine
708
var task_storey = storey as AsyncTaskStorey;
709
if (task_storey == null || (task_storey.ReturnType != null && !task_storey.ReturnType.IsGenericTask))
710
ctx.CurrentBranching.CurrentUsageVector.Goto ();
712
ctx.EndFlowBranching ();
714
if (!ec.IsInProbingMode) {
715
var move_next = new StateMachineMethod (storey, this, new TypeExpression (ReturnType, loc), Modifiers.PUBLIC, new MemberName ("MoveNext", loc));
716
move_next.Block.AddStatement (new MoveNextBodyStatement (this));
717
storey.AddEntryMethod (move_next);
720
eclass = ExprClass.Value;
724
public override void Emit (EmitContext ec)
727
// Load state machine instance
729
storey.Instance.Emit (ec);
732
void EmitMoveNext_NoResumePoints (EmitContext ec)
735
ec.Emit (OpCodes.Ldfld, storey.PC.Spec);
738
ec.EmitInt ((int) IteratorStorey.State.After);
739
ec.Emit (OpCodes.Stfld, storey.PC.Spec);
741
// We only care if the PC is zero (start executing) or non-zero (don't do anything)
742
ec.Emit (OpCodes.Brtrue, move_next_error);
744
iterator_body_end = ec.DefineLabel ();
746
block.EmitEmbedded (ec);
748
ec.MarkLabel (iterator_body_end);
750
EmitMoveNextEpilogue (ec);
752
ec.MarkLabel (move_next_error);
754
if (ReturnType.Kind != MemberKind.Void) {
756
ec.Emit (OpCodes.Ret);
760
void EmitMoveNext (EmitContext ec)
762
move_next_ok = ec.DefineLabel ();
763
move_next_error = ec.DefineLabel ();
765
if (resume_points == null) {
766
EmitMoveNext_NoResumePoints (ec);
770
current_pc = ec.GetTemporaryLocal (ec.BuiltinTypes.UInt);
772
ec.Emit (OpCodes.Ldfld, storey.PC.Spec);
773
ec.Emit (OpCodes.Stloc, current_pc);
775
// We're actually in state 'running', but this is as good a PC value as any if there's an abnormal exit
777
ec.EmitInt ((int) IteratorStorey.State.After);
778
ec.Emit (OpCodes.Stfld, storey.PC.Spec);
780
Label[] labels = new Label[1 + resume_points.Count];
781
labels[0] = ec.DefineLabel ();
783
bool need_skip_finally = false;
784
for (int i = 0; i < resume_points.Count; ++i) {
785
ResumableStatement s = resume_points[i];
786
need_skip_finally |= s is ExceptionStatement;
787
labels[i + 1] = s.PrepareForEmit (ec);
790
if (need_skip_finally) {
791
skip_finally = ec.GetTemporaryLocal (ec.BuiltinTypes.Bool);
793
ec.Emit (OpCodes.Stloc, skip_finally);
796
var async_init = this as AsyncInitializer;
797
if (async_init != null)
798
ec.BeginExceptionBlock ();
800
ec.Emit (OpCodes.Ldloc, current_pc);
801
ec.Emit (OpCodes.Switch, labels);
803
ec.Emit (async_init != null ? OpCodes.Leave : OpCodes.Br, move_next_error);
805
ec.MarkLabel (labels[0]);
807
iterator_body_end = ec.DefineLabel ();
809
block.EmitEmbedded (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 ();
829
ec.Mark (Block.Original.EndLocation);
831
ec.EmitInt ((int) IteratorStorey.State.After);
832
ec.Emit (OpCodes.Stfld, storey.PC.Spec);
834
EmitMoveNextEpilogue (ec);
836
ec.MarkLabel (move_next_error);
838
if (ReturnType.Kind != MemberKind.Void) {
840
ec.Emit (OpCodes.Ret);
843
ec.MarkLabel (move_next_ok);
845
if (ReturnType.Kind != MemberKind.Void) {
847
ec.Emit (OpCodes.Ret);
851
protected virtual void EmitMoveNextEpilogue (EmitContext ec)
855
public void EmitLeave (EmitContext ec, bool unwind_protect)
858
ec.Emit (unwind_protect ? OpCodes.Leave : OpCodes.Br, move_next_ok);
862
// Called back from YieldStatement
864
public virtual void InjectYield (EmitContext ec, Expression expr, int resume_pc, bool unwind_protect, Label resume_point)
867
// Guard against being disposed meantime
869
Label disposed = ec.DefineLabel ();
870
var iterator = storey as IteratorStorey;
871
if (iterator != null) {
873
ec.Emit (OpCodes.Ldfld, iterator.DisposingField.Spec);
874
ec.Emit (OpCodes.Brtrue_S, disposed);
878
// store resume program-counter
881
ec.EmitInt (resume_pc);
882
ec.Emit (OpCodes.Stfld, storey.PC.Spec);
884
if (iterator != null) {
885
ec.MarkLabel (disposed);
888
// mark finally blocks as disabled
889
if (unwind_protect && skip_finally != null) {
891
ec.Emit (OpCodes.Stloc, skip_finally);
895
public void SetStateMachine (StateMachine stateMachine)
897
this.storey = stateMachine;
902
// Iterators are implemented as state machine blocks
904
public class Iterator : StateMachineInitializer
906
sealed class TryFinallyBlockProxyStatement : Statement
908
TryFinallyBlock block;
911
public TryFinallyBlockProxyStatement (Iterator iterator, TryFinallyBlock block)
913
this.iterator = iterator;
917
protected override void CloneTo (CloneContext clonectx, Statement target)
919
throw new NotSupportedException ();
922
protected override void DoEmit (EmitContext ec)
925
// Restore redirection for any captured variables
927
ec.CurrentAnonymousMethod = iterator;
929
using (ec.With (BuilderContext.Options.OmitDebugInfo, !ec.HasMethodSymbolBuilder)) {
930
block.EmitFinallyBody (ec);
935
public readonly IMethodData OriginalMethod;
936
public readonly bool IsEnumerable;
937
public readonly TypeSpec OriginalIteratorType;
938
int finally_hosts_counter;
940
public Iterator (ParametersBlock block, IMethodData method, TypeDefinition host, TypeSpec iterator_type, bool is_enumerable)
941
: base (block, host, host.Compiler.BuiltinTypes.Bool)
943
this.OriginalMethod = method;
944
this.OriginalIteratorType = iterator_type;
945
this.IsEnumerable = is_enumerable;
946
this.type = method.ReturnType;
951
public ToplevelBlock Container {
952
get { return OriginalMethod.Block; }
955
public override string ContainerType {
956
get { return "iterator"; }
959
public override bool IsIterator {
965
public Method CreateFinallyHost (TryFinallyBlock block)
967
var method = new Method (storey, new TypeExpression (storey.Compiler.BuiltinTypes.Void, loc),
968
Modifiers.COMPILER_GENERATED, new MemberName (CompilerGeneratedContainer.MakeName (null, null, "Finally", finally_hosts_counter++), loc),
969
ParametersCompiled.EmptyReadOnlyParameters, null);
971
method.Block = new ToplevelBlock (method.Compiler, method.ParameterInfo, loc);
972
method.Block.IsCompilerGenerated = true;
973
method.Block.AddStatement (new TryFinallyBlockProxyStatement (this, block));
975
// Cannot it add to storey because it'd be emitted before nested
976
// anonoymous methods which could capture shared variable
981
public void EmitYieldBreak (EmitContext ec, bool unwind_protect)
983
ec.Emit (unwind_protect ? OpCodes.Leave : OpCodes.Br, move_next_error);
986
public override string GetSignatureForError ()
988
return OriginalMethod.GetSignatureForError ();
991
public override void Emit (EmitContext ec)
994
// Load Iterator storey instance
996
storey.Instance.Emit (ec);
999
// Initialize iterator PC when it's unitialized
1002
ec.Emit (OpCodes.Dup);
1003
ec.EmitInt ((int)IteratorStorey.State.Uninitialized);
1005
var field = storey.PC.Spec;
1006
if (storey.MemberName.IsGeneric) {
1007
field = MemberCache.GetMember (Storey.Instance.Type, field);
1010
ec.Emit (OpCodes.Stfld, field);
1014
public void EmitDispose (EmitContext ec)
1016
if (resume_points == null)
1019
Label end = ec.DefineLabel ();
1021
Label[] labels = null;
1022
for (int i = 0; i < resume_points.Count; ++i) {
1023
ResumableStatement s = resume_points[i];
1024
Label ret = s.PrepareForDispose (ec, end);
1025
if (ret.Equals (end) && labels == null)
1027
if (labels == null) {
1028
labels = new Label[resume_points.Count + 1];
1029
for (int j = 0; j <= i; ++j)
1033
labels[i + 1] = ret;
1036
if (labels != null) {
1037
current_pc = ec.GetTemporaryLocal (ec.BuiltinTypes.UInt);
1039
ec.Emit (OpCodes.Ldfld, storey.PC.Spec);
1040
ec.Emit (OpCodes.Stloc, current_pc);
1045
ec.Emit (OpCodes.Stfld, ((IteratorStorey) storey).DisposingField.Spec);
1048
ec.EmitInt ((int) IteratorStorey.State.After);
1049
ec.Emit (OpCodes.Stfld, storey.PC.Spec);
1051
if (labels != null) {
1052
//SymbolWriter.StartIteratorDispatcher (ec.ig);
1053
ec.Emit (OpCodes.Ldloc, current_pc);
1054
ec.Emit (OpCodes.Switch, labels);
1055
//SymbolWriter.EndIteratorDispatcher (ec.ig);
1057
foreach (ResumableStatement s in resume_points)
1058
s.EmitForDispose (ec, current_pc, end, true);
1064
public override void EmitStatement (EmitContext ec)
1066
throw new NotImplementedException ();
1069
public override void InjectYield (EmitContext ec, Expression expr, int resume_pc, bool unwind_protect, Label resume_point)
1071
// Store the new value into current
1072
var fe = new FieldExpr (((IteratorStorey) storey).CurrentField, loc);
1073
fe.InstanceExpression = new CompilerGeneratedThis (storey.CurrentType, loc);
1074
fe.EmitAssign (ec, expr, false, false);
1076
base.InjectYield (ec, expr, resume_pc, unwind_protect, resume_point);
1078
EmitLeave (ec, unwind_protect);
1080
ec.MarkLabel (resume_point);
1083
protected override BlockContext CreateBlockContext (ResolveContext rc)
1085
var bc = base.CreateBlockContext (rc);
1086
bc.StartFlowBranching (this, rc.CurrentBranching);
1090
public static void CreateIterator (IMethodData method, TypeDefinition parent, Modifiers modifiers)
1093
TypeSpec iterator_type;
1095
TypeSpec ret = method.ReturnType;
1099
if (!CheckType (ret, parent, out iterator_type, out is_enumerable)) {
1100
parent.Compiler.Report.Error (1624, method.Location,
1101
"The body of `{0}' cannot be an iterator block " +
1102
"because `{1}' is not an iterator interface type",
1103
method.GetSignatureForError (),
1104
TypeManager.CSharpName (ret));
1108
ParametersCompiled parameters = method.ParameterInfo;
1109
for (int i = 0; i < parameters.Count; i++) {
1110
Parameter p = parameters [i];
1111
Parameter.Modifier mod = p.ModFlags;
1112
if ((mod & Parameter.Modifier.RefOutMask) != 0) {
1113
parent.Compiler.Report.Error (1623, p.Location,
1114
"Iterators cannot have ref or out parameters");
1118
if (p is ArglistParameter) {
1119
parent.Compiler.Report.Error (1636, method.Location,
1120
"__arglist is not allowed in parameter list of iterators");
1124
if (parameters.Types [i].IsPointer) {
1125
parent.Compiler.Report.Error (1637, p.Location,
1126
"Iterators cannot have unsafe parameters or yield types");
1131
if ((modifiers & Modifiers.UNSAFE) != 0) {
1132
parent.Compiler.Report.Error (1629, method.Location, "Unsafe code may not appear in iterators");
1135
method.Block = method.Block.ConvertToIterator (method, parent, iterator_type, is_enumerable);
1138
static bool CheckType (TypeSpec ret, TypeContainer parent, out TypeSpec original_iterator_type, out bool is_enumerable)
1140
original_iterator_type = null;
1141
is_enumerable = false;
1143
if (ret.BuiltinType == BuiltinTypeSpec.Type.IEnumerable) {
1144
original_iterator_type = parent.Compiler.BuiltinTypes.Object;
1145
is_enumerable = true;
1148
if (ret.BuiltinType == BuiltinTypeSpec.Type.IEnumerator) {
1149
original_iterator_type = parent.Compiler.BuiltinTypes.Object;
1150
is_enumerable = false;
1154
InflatedTypeSpec inflated = ret as InflatedTypeSpec;
1155
if (inflated == null)
1158
var member_definition = inflated.MemberDefinition;
1159
PredefinedType ptype = parent.Module.PredefinedTypes.IEnumerableGeneric;
1161
if (ptype.Define () && ptype.TypeSpec.MemberDefinition == member_definition) {
1162
original_iterator_type = inflated.TypeArguments[0];
1163
is_enumerable = true;
1167
ptype = parent.Module.PredefinedTypes.IEnumeratorGeneric;
1168
if (ptype.Define () && ptype.TypeSpec.MemberDefinition == member_definition) {
1169
original_iterator_type = inflated.TypeArguments[0];
1170
is_enumerable = false;