c0ccf129e74a77fd44b33e4c702b9e69412cd1e6
[mono.git] / mcs / mcs / iterators.cs
1 //
2 // iterators.cs: Support for implementing iterators
3 //
4 // Author:
5 //   Miguel de Icaza (miguel@ximian.com)
6 //   Marek Safar (marek.safar@gmail.com)
7 //
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.
12 //
13
14 using System;
15 using System.Collections.Generic;
16 using Mono.CompilerServices.SymbolWriter;
17
18 #if STATIC
19 using IKVM.Reflection.Emit;
20 #else
21 using System.Reflection.Emit;
22 #endif
23
24 namespace Mono.CSharp
25 {
26         public abstract class YieldStatement<T> : ResumableStatement where T : StateMachineInitializer
27         {
28                 protected Expression expr;
29                 protected bool unwind_protect;
30                 protected T machine_initializer;
31                 int resume_pc;
32                 ExceptionStatement inside_try_block;
33                 TryCatch inside_catch_block;
34
35                 protected YieldStatement (Expression expr, Location l)
36                 {
37                         this.expr = expr;
38                         loc = l;
39                 }
40
41                 public Expression Expr {
42                         get { return this.expr; }
43                 }
44                 
45                 protected override void CloneTo (CloneContext clonectx, Statement t)
46                 {
47                         var target = (YieldStatement<T>) t;
48                         target.expr = expr.Clone (clonectx);
49                 }
50
51                 protected override void DoEmit (EmitContext ec)
52                 {
53                         machine_initializer.InjectYield (ec, expr, resume_pc, unwind_protect, resume_point);
54                 }
55
56                 protected override bool DoFlowAnalysis (FlowAnalysisContext fc)
57                 {
58                         expr.FlowAnalysis (fc);
59
60                         RegisterResumePoint ();
61
62                         return false;
63                 }
64
65                 public override bool Resolve (BlockContext bc)
66                 {
67                         expr = expr.Resolve (bc);
68                         if (expr == null)
69                                 return false;
70
71                         machine_initializer = bc.CurrentAnonymousMethod as T;
72                         inside_try_block = bc.CurrentTryBlock;
73                         inside_catch_block = bc.CurrentTryCatch;
74                         return true;
75                 }
76
77                 public void RegisterResumePoint ()
78                 {
79                         if (resume_pc != 0)
80                                 return;
81
82                         if (inside_try_block == null) {
83                                 resume_pc = machine_initializer.AddResumePoint (this);
84                         } else {
85                                 resume_pc = inside_try_block.AddResumePoint (this, resume_pc, machine_initializer, inside_catch_block);
86                                 unwind_protect = true;
87                                 inside_try_block = null;
88                         }
89                 }
90         }
91
92         public class Yield : YieldStatement<Iterator>
93         {
94                 public Yield (Expression expr, Location loc)
95                         : base (expr, loc)
96                 {
97                 }
98
99                 public static bool CheckContext (BlockContext bc, Location loc)
100                 {
101                         if (!bc.CurrentAnonymousMethod.IsIterator) {
102                                 bc.Report.Error (1621, loc,
103                                         "The yield statement cannot be used inside anonymous method blocks");
104                                 return false;
105                         }
106
107                         if (bc.HasSet (ResolveContext.Options.FinallyScope)) {
108                                 bc.Report.Error (1625, loc, "Cannot yield in the body of a finally clause");
109                                 return false;
110                         }
111
112                         return true;
113                 }
114
115                 public override bool Resolve (BlockContext bc)
116                 {
117                         if (!CheckContext (bc, loc))
118                                 return false;
119
120                         if (bc.HasAny (ResolveContext.Options.TryWithCatchScope)) {
121                                 bc.Report.Error (1626, loc, "Cannot yield a value in the body of a try block with a catch clause");
122                         }
123
124                         if (bc.HasSet (ResolveContext.Options.CatchScope)) {
125                                 bc.Report.Error (1631, loc, "Cannot yield a value in the body of a catch clause");
126                         }
127
128                         if (!base.Resolve (bc))
129                                 return false;
130
131                         var otype = bc.CurrentIterator.OriginalIteratorType;
132                         if (expr.Type != otype) {
133                                 expr = Convert.ImplicitConversionRequired (bc, expr, otype, loc);
134                                 if (expr == null)
135                                         return false;
136                         }
137
138                         return true;
139                 }
140                 
141                 public override object Accept (StructuralVisitor visitor)
142                 {
143                         return visitor.Visit (this);
144                 }
145         }
146
147         public class YieldBreak : ExitStatement
148         {
149                 Iterator iterator;
150
151                 public YieldBreak (Location l)
152                 {
153                         loc = l;
154                 }
155
156                 protected override bool IsLocalExit {
157                         get {
158                                 return false;
159                         }
160                 }
161
162                 protected override void CloneTo (CloneContext clonectx, Statement target)
163                 {
164                 }
165
166                 protected override bool DoResolve (BlockContext bc)
167                 {
168                         iterator = bc.CurrentIterator;
169                         return Yield.CheckContext (bc, loc);
170                 }
171
172                 protected override void DoEmit (EmitContext ec)
173                 {
174                         iterator.EmitYieldBreak (ec, unwind_protect);
175                 }
176
177                 protected override bool DoFlowAnalysis (FlowAnalysisContext fc)
178                 {
179                         return true;
180                 }
181
182                 public override Reachability MarkReachable (Reachability rc)
183                 {
184                         base.MarkReachable (rc);
185                         return Reachability.CreateUnreachable ();
186                 }
187                 
188                 public override object Accept (StructuralVisitor visitor)
189                 {
190                         return visitor.Visit (this);
191                 }
192         }
193
194         public abstract class StateMachine : AnonymousMethodStorey
195         {
196                 public enum State
197                 {
198                         Running = -3, // Used only in CurrentPC, never stored into $PC
199                         Uninitialized = -2,
200                         After = -1,
201                         Start = 0
202                 }
203
204                 Field pc_field;
205                 StateMachineMethod method;
206
207                 protected StateMachine (ParametersBlock block, TypeDefinition parent, MemberBase host, TypeParameters tparams, string name, MemberKind kind)
208                         : base (block, parent, host, tparams, name, kind)
209                 {
210                         OriginalTypeParameters = tparams;
211                 }
212
213                 #region Properties
214
215                 public TypeParameters OriginalTypeParameters { get; private set; }
216
217                 public StateMachineMethod StateMachineMethod {
218                         get {
219                                 return method;
220                         }
221                 }
222
223                 public Field PC {
224                         get {
225                                 return pc_field;
226                         }
227                 }
228
229                 #endregion
230
231                 public void AddEntryMethod (StateMachineMethod method)
232                 {
233                         if (this.method != null)
234                                 throw new InternalErrorException ();
235
236                         this.method = method;
237                         Members.Add (method);
238                 }
239
240                 protected override bool DoDefineMembers ()
241                 {
242                         pc_field = AddCompilerGeneratedField ("$PC", new TypeExpression (Compiler.BuiltinTypes.Int, Location));
243
244                         return base.DoDefineMembers ();
245                 }
246
247                 protected override string GetVariableMangledName (ResolveContext rc, LocalVariable local_info)
248                 {
249                         if (local_info.IsCompilerGenerated)
250                                 return base.GetVariableMangledName (rc, local_info);
251
252                         //
253                         // Special format which encodes original variable name and
254                         // it's scope to support lifted variables debugging. This
255                         // is same what csc does and allows to correctly set fields
256                         // scope information (like ambiguity, out of scope, etc).
257                         //
258                         var id = rc.CurrentBlock.Explicit.GetDebugSymbolScopeIndex ();
259                         return "<" + local_info.Name + ">__" + id;
260                 }
261         }
262
263         class IteratorStorey : StateMachine
264         {
265                 class GetEnumeratorMethod : StateMachineMethod
266                 {
267                         sealed class GetEnumeratorStatement : Statement
268                         {
269                                 readonly IteratorStorey host;
270                                 readonly StateMachineMethod host_method;
271
272                                 Expression new_storey;
273
274                                 public GetEnumeratorStatement (IteratorStorey host, StateMachineMethod host_method)
275                                 {
276                                         this.host = host;
277                                         this.host_method = host_method;
278                                         loc = host_method.Location;
279                                 }
280
281                                 protected override void CloneTo (CloneContext clonectx, Statement target)
282                                 {
283                                         throw new NotSupportedException ();
284                                 }
285
286                                 public override bool Resolve (BlockContext ec)
287                                 {
288                                         TypeExpression storey_type_expr = new TypeExpression (host.Definition, loc);
289                                         List<Expression> init = null;
290                                         if (host.hoisted_this != null) {
291                                                 init = new List<Expression> (host.hoisted_params == null ? 1 : host.HoistedParameters.Count + 1);
292                                                 HoistedThis ht = host.hoisted_this;
293                                                 FieldExpr from = new FieldExpr (ht.Field, loc);
294                                                 from.InstanceExpression = new CompilerGeneratedThis (ec.CurrentType, loc);
295                                                 init.Add (new ElementInitializer (ht.Field.Name, from, loc));
296                                         }
297
298                                         if (host.hoisted_params != null) {
299                                                 if (init == null)
300                                                         init = new List<Expression> (host.HoistedParameters.Count);
301
302                                                 for (int i = 0; i < host.hoisted_params.Count; ++i) {
303                                                         HoistedParameter hp = host.hoisted_params [i];
304                                                         HoistedParameter hp_cp = host.hoisted_params_copy [i] ?? hp;
305
306                                                         FieldExpr from = new FieldExpr (hp_cp.Field, loc);
307                                                         from.InstanceExpression = new CompilerGeneratedThis (ec.CurrentType, loc);
308
309                                                         init.Add (new ElementInitializer (hp.Field.Name, from, loc));
310                                                 }
311                                         }
312
313                                         if (init != null) {
314                                                 new_storey = new NewInitialize (storey_type_expr, null,
315                                                         new CollectionOrObjectInitializers (init, loc), loc);
316                                         } else {
317                                                 new_storey = new New (storey_type_expr, null, loc);
318                                         }
319
320                                         new_storey = new_storey.Resolve (ec);
321                                         if (new_storey != null)
322                                                 new_storey = Convert.ImplicitConversionRequired (ec, new_storey, host_method.MemberType, loc);
323
324                                         return true;
325                                 }
326
327                                 protected override void DoEmit (EmitContext ec)
328                                 {
329                                         Label label_init = ec.DefineLabel ();
330
331                                         ec.EmitThis ();
332                                         ec.Emit (OpCodes.Ldflda, host.PC.Spec);
333                                         ec.EmitInt ((int) State.Start);
334                                         ec.EmitInt ((int) State.Uninitialized);
335
336                                         var m = ec.Module.PredefinedMembers.InterlockedCompareExchange.Resolve (loc);
337                                         if (m != null)
338                                                 ec.Emit (OpCodes.Call, m);
339
340                                         ec.EmitInt ((int) State.Uninitialized);
341                                         ec.Emit (OpCodes.Bne_Un_S, label_init);
342
343                                         ec.EmitThis ();
344                                         ec.Emit (OpCodes.Ret);
345
346                                         ec.MarkLabel (label_init);
347
348                                         new_storey.Emit (ec);
349                                         ec.Emit (OpCodes.Ret);
350                                 }
351
352                                 protected override bool DoFlowAnalysis (FlowAnalysisContext fc)
353                                 {
354                                         throw new NotImplementedException ();
355                                 }
356
357                                 public override Reachability MarkReachable (Reachability rc)
358                                 {
359                                         base.MarkReachable (rc);
360                                         return Reachability.CreateUnreachable ();
361                                 }
362                         }
363
364                         GetEnumeratorMethod (IteratorStorey host, FullNamedExpression returnType, MemberName name)
365                                 : base (host, null, returnType, Modifiers.DEBUGGER_HIDDEN, name, ToplevelBlock.Flags.CompilerGenerated | ToplevelBlock.Flags.NoFlowAnalysis)
366                         {
367                         }
368
369                         public static GetEnumeratorMethod Create (IteratorStorey host, FullNamedExpression returnType, MemberName name)
370                         {
371                                 return Create (host, returnType, name, null);
372                         }
373
374                         public static GetEnumeratorMethod Create (IteratorStorey host, FullNamedExpression returnType, MemberName name, Statement statement)
375                         {
376                                 var m = new GetEnumeratorMethod (host, returnType, name);
377                                 var stmt = statement ?? new GetEnumeratorStatement (host, m);
378                                 m.block.AddStatement (stmt);
379                                 return m;
380                         }
381                 }
382
383                 class DisposeMethod : StateMachineMethod
384                 {
385                         sealed class DisposeMethodStatement : Statement
386                         {
387                                 Iterator iterator;
388
389                                 public DisposeMethodStatement (Iterator iterator)
390                                 {
391                                         this.iterator = iterator;
392                                         this.loc = iterator.Location;
393                                 }
394
395                                 protected override void CloneTo (CloneContext clonectx, Statement target)
396                                 {
397                                         throw new NotSupportedException ();
398                                 }
399
400                                 public override bool Resolve (BlockContext ec)
401                                 {
402                                         return true;
403                                 }
404
405                                 protected override void DoEmit (EmitContext ec)
406                                 {
407                                         ec.CurrentAnonymousMethod = iterator;
408                                         iterator.EmitDispose (ec);
409                                 }
410
411                                 protected override bool DoFlowAnalysis (FlowAnalysisContext fc)
412                                 {
413                                         throw new NotImplementedException ();
414                                 }
415                         }
416
417                         public DisposeMethod (IteratorStorey host)
418                                 : base (host, null, new TypeExpression (host.Compiler.BuiltinTypes.Void, host.Location), Modifiers.PUBLIC | Modifiers.DEBUGGER_HIDDEN,
419                                         new MemberName ("Dispose", host.Location), ToplevelBlock.Flags.CompilerGenerated | ToplevelBlock.Flags.NoFlowAnalysis)
420                         {
421                                 host.Members.Add (this);
422
423                                 Block.AddStatement (new DisposeMethodStatement (host.Iterator));
424                         }
425                 }
426
427                 //
428                 // Uses Method as method info
429                 //
430                 class DynamicMethodGroupExpr : MethodGroupExpr
431                 {
432                         readonly Method method;
433
434                         public DynamicMethodGroupExpr (Method method, Location loc)
435                                 : base ((IList<MemberSpec>) null, null, loc)
436                         {
437                                 this.method = method;
438                                 eclass = ExprClass.Unresolved;
439                         }
440
441                         protected override Expression DoResolve (ResolveContext ec)
442                         {
443                                 Methods = new List<MemberSpec> (1) { method.Spec };
444                                 type = method.Parent.Definition;
445                                 InstanceExpression = new CompilerGeneratedThis (type, Location);
446                                 return base.DoResolve (ec);
447                         }
448                 }
449
450                 class DynamicFieldExpr : FieldExpr
451                 {
452                         readonly Field field;
453
454                         public DynamicFieldExpr (Field field, Location loc)
455                                 : base (loc)
456                         {
457                                 this.field = field;
458                         }
459
460                         protected override Expression DoResolve (ResolveContext ec)
461                         {
462                                 spec = field.Spec;
463                                 type = spec.MemberType;
464                                 InstanceExpression = new CompilerGeneratedThis (type, Location);
465                                 return base.DoResolve (ec);
466                         }
467                 }
468
469                 public readonly Iterator Iterator;
470
471                 List<HoistedParameter> hoisted_params_copy;
472
473                 TypeExpr iterator_type_expr;
474                 Field current_field;
475                 Field disposing_field;
476
477                 TypeSpec generic_enumerator_type;
478                 TypeSpec generic_enumerable_type;
479
480                 public IteratorStorey (Iterator iterator)
481                         : base (iterator.Container.ParametersBlock, iterator.Host,
482                           iterator.OriginalMethod as MemberBase, iterator.OriginalMethod.CurrentTypeParameters, "Iterator", MemberKind.Class)
483                 {
484                         this.Iterator = iterator;
485                 }
486
487                 public Field CurrentField {
488                         get {
489                                 return current_field;
490                         }
491                 }
492
493                 public Field DisposingField {
494                         get {
495                                 return disposing_field;
496                         }
497                 }
498
499                 public IList<HoistedParameter> HoistedParameters {
500                         get { return hoisted_params; }
501                 }
502
503                 protected override Constructor DefineDefaultConstructor (bool is_static)
504                 {
505                         var ctor = base.DefineDefaultConstructor (is_static);
506                         ctor.ModFlags |= Modifiers.DEBUGGER_HIDDEN;
507                         return ctor;
508                 }
509
510                 protected override TypeSpec[] ResolveBaseTypes (out FullNamedExpression base_class)
511                 {
512                         var mtype = Iterator.OriginalIteratorType;
513                         if (Mutator != null)
514                                 mtype = Mutator.Mutate (mtype);
515
516                         iterator_type_expr = new TypeExpression (mtype, Location);
517
518                         var ifaces = new List<TypeSpec> (5);
519                         if (Iterator.IsEnumerable) {
520                                 ifaces.Add (Compiler.BuiltinTypes.IEnumerable);
521
522                                 if (Module.PredefinedTypes.IEnumerableGeneric.Define ()) {
523                                         generic_enumerable_type = Module.PredefinedTypes.IEnumerableGeneric.TypeSpec.MakeGenericType (Module, new[] { mtype });
524                                         ifaces.Add (generic_enumerable_type);
525                                 }
526                         }
527
528                         ifaces.Add (Compiler.BuiltinTypes.IEnumerator);
529                         ifaces.Add (Compiler.BuiltinTypes.IDisposable);
530
531                         var ienumerator_generic = Module.PredefinedTypes.IEnumeratorGeneric;
532                         if (ienumerator_generic.Define ()) {
533                                 generic_enumerator_type = ienumerator_generic.TypeSpec.MakeGenericType (Module, new [] { mtype });
534                                 ifaces.Add (generic_enumerator_type);
535                         }
536
537                         base_class = null;
538
539                         base_type = Compiler.BuiltinTypes.Object;
540                         return ifaces.ToArray ();
541                 }
542
543                 protected override bool DoDefineMembers ()
544                 {
545                         current_field = AddCompilerGeneratedField ("$current", iterator_type_expr);
546                         disposing_field = AddCompilerGeneratedField ("$disposing", new TypeExpression (Compiler.BuiltinTypes.Bool, Location));
547
548                         if (Iterator.IsEnumerable && hoisted_params != null) {
549                                 //
550                                 // Iterators are independent, each GetEnumerator call has to
551                                 // create same enumerator therefore we have to keep original values
552                                 // around for re-initialization
553                                 //
554                                 hoisted_params_copy = new List<HoistedParameter> (hoisted_params.Count);
555                                 foreach (HoistedParameter hp in hoisted_params) {
556
557                                         //
558                                         // Don't create field copy for unmodified captured parameters
559                                         //
560                                         HoistedParameter hp_copy;
561                                         if (hp.IsAssigned) {
562                                                 hp_copy = new HoistedParameter (hp, "<$>" + hp.Field.Name);
563                                         } else {
564                                                 hp_copy = null;
565                                         }
566
567                                         hoisted_params_copy.Add (hp_copy);
568                                 }
569                         }
570
571                         if (generic_enumerator_type != null)
572                                 Define_Current (true);
573
574                         Define_Current (false);
575                         new DisposeMethod (this);
576                         Define_Reset ();
577
578                         if (Iterator.IsEnumerable) {
579                                 FullNamedExpression explicit_iface = new TypeExpression (Compiler.BuiltinTypes.IEnumerable, Location);
580                                 var name = new MemberName ("GetEnumerator", null, explicit_iface, Location.Null);
581
582                                 if (generic_enumerator_type != null) {
583                                         explicit_iface = new TypeExpression (generic_enumerable_type, Location);
584                                         var gname = new MemberName ("GetEnumerator", null, explicit_iface, Location.Null);
585                                         Method gget_enumerator = GetEnumeratorMethod.Create (this, new TypeExpression (generic_enumerator_type, Location), gname);
586
587                                         //
588                                         // Just call generic GetEnumerator implementation
589                                         //
590                                         var stmt = new Return (new Invocation (new DynamicMethodGroupExpr (gget_enumerator, Location), null), Location);
591                                         Method get_enumerator = GetEnumeratorMethod.Create (this, new TypeExpression (Compiler.BuiltinTypes.IEnumerator, Location), name, stmt);
592
593                                         Members.Add (get_enumerator);
594                                         Members.Add (gget_enumerator);
595                                 } else {
596                                         Members.Add (GetEnumeratorMethod.Create (this, new TypeExpression (Compiler.BuiltinTypes.IEnumerator, Location), name));
597                                 }
598                         }
599
600                         return base.DoDefineMembers ();
601                 }
602
603                 void Define_Current (bool is_generic)
604                 {
605                         TypeExpr type;
606                         FullNamedExpression explicit_iface;
607
608                         if (is_generic) {
609                                 explicit_iface = new TypeExpression (generic_enumerator_type, Location);
610                                 type = iterator_type_expr;
611                         } else {
612                                 explicit_iface = new TypeExpression (Module.Compiler.BuiltinTypes.IEnumerator, Location);
613                                 type = new TypeExpression (Compiler.BuiltinTypes.Object, Location);
614                         }
615
616                         var name = new MemberName ("Current", null, explicit_iface, Location);
617
618                         ToplevelBlock get_block = new ToplevelBlock (Compiler, ParametersCompiled.EmptyReadOnlyParameters, Location,
619                                 Block.Flags.CompilerGenerated | Block.Flags.NoFlowAnalysis);
620                         get_block.AddStatement (new Return (new DynamicFieldExpr (CurrentField, Location), Location));
621                                 
622                         Property current = new Property (this, type, Modifiers.DEBUGGER_HIDDEN | Modifiers.COMPILER_GENERATED, name, null);
623                         current.Get = new Property.GetMethod (current, Modifiers.COMPILER_GENERATED, null, Location);
624                         current.Get.Block = get_block;
625
626                         Members.Add (current);
627                 }
628
629                 void Define_Reset ()
630                 {
631                         Method reset = new Method (
632                                 this, new TypeExpression (Compiler.BuiltinTypes.Void, Location),
633                                 Modifiers.PUBLIC | Modifiers.DEBUGGER_HIDDEN | Modifiers.COMPILER_GENERATED,
634                                 new MemberName ("Reset", Location),
635                                 ParametersCompiled.EmptyReadOnlyParameters, null);
636                         Members.Add (reset);
637
638                         reset.Block = new ToplevelBlock (Compiler, reset.ParameterInfo, Location,
639                                 Block.Flags.CompilerGenerated | Block.Flags.NoFlowAnalysis);
640
641                         TypeSpec ex_type = Module.PredefinedTypes.NotSupportedException.Resolve ();
642                         if (ex_type == null)
643                                 return;
644
645                         reset.Block.AddStatement (new Throw (new New (new TypeExpression (ex_type, Location), null, Location), Location));
646                 }
647
648                 protected override void EmitHoistedParameters (EmitContext ec, List<HoistedParameter> hoisted)
649                 {
650                         base.EmitHoistedParameters (ec, hoisted);
651                         if (hoisted_params_copy != null)
652                                 base.EmitHoistedParameters (ec, hoisted_params_copy);
653                 }
654         }
655
656         public class StateMachineMethod : Method
657         {
658                 readonly StateMachineInitializer expr;
659
660                 public StateMachineMethod (StateMachine host, StateMachineInitializer expr, FullNamedExpression returnType,
661                         Modifiers mod, MemberName name, ToplevelBlock.Flags blockFlags)
662                         : base (host, returnType, mod | Modifiers.COMPILER_GENERATED,
663                           name, ParametersCompiled.EmptyReadOnlyParameters, null)
664                 {
665                         this.expr = expr;
666                         Block = new ToplevelBlock (host.Compiler, ParametersCompiled.EmptyReadOnlyParameters, Location.Null, blockFlags);
667                 }
668
669                 public override EmitContext CreateEmitContext (ILGenerator ig, SourceMethodBuilder sourceMethod)
670                 {
671                         EmitContext ec = new EmitContext (this, ig, MemberType, sourceMethod);
672                         ec.CurrentAnonymousMethod = expr;
673
674                         if (expr is AsyncInitializer)
675                                 ec.With (BuilderContext.Options.AsyncBody, true);
676
677                         return ec;
678                 }
679         }
680
681         public abstract class StateMachineInitializer : AnonymousExpression
682         {
683                 sealed class MoveNextBodyStatement : Statement
684                 {
685                         readonly StateMachineInitializer state_machine;
686
687                         public MoveNextBodyStatement (StateMachineInitializer stateMachine)
688                         {
689                                 this.state_machine = stateMachine;
690                                 this.loc = stateMachine.Location;
691                         }
692
693                         protected override void CloneTo (CloneContext clonectx, Statement target)
694                         {
695                                 throw new NotSupportedException ();
696                         }
697
698                         public override bool Resolve (BlockContext ec)
699                         {
700                                 return true;
701                         }
702
703                         protected override void DoEmit (EmitContext ec)
704                         {
705                                 state_machine.EmitMoveNext (ec);
706                         }
707
708                         public override void Emit (EmitContext ec)
709                         {
710                                 // Don't create sequence point
711                                 DoEmit (ec);
712                         }
713
714                         protected override bool DoFlowAnalysis (FlowAnalysisContext fc)
715                         {
716                                 return state_machine.ReturnType.Kind != MemberKind.Void;
717                         }
718
719                         public override Reachability MarkReachable (Reachability rc)
720                         {
721                                 base.MarkReachable (rc);
722
723                                 if (state_machine.ReturnType.Kind != MemberKind.Void)
724                                         rc = Reachability.CreateUnreachable ();
725
726                                 return rc;
727                         }
728                 }
729
730                 public readonly TypeDefinition Host;
731                 protected StateMachine storey;
732
733                 //
734                 // The state as we generate the machine
735                 //
736                 protected Label move_next_ok;
737                 protected Label move_next_error;
738                 LocalBuilder skip_finally;
739                 protected LocalBuilder current_pc;
740                 protected List<ResumableStatement> resume_points;
741
742                 protected StateMachineInitializer (ParametersBlock block, TypeDefinition host, TypeSpec returnType)
743                         : base (block, returnType, block.StartLocation)
744                 {
745                         this.Host = host;
746                 }
747
748                 #region Properties
749
750                 public Label BodyEnd { get; set; }
751
752                 public LocalBuilder CurrentPC
753                 {
754                         get {
755                                 return current_pc;
756                         }
757                 }
758
759                 public LocalBuilder SkipFinally {
760                         get {
761                                 return skip_finally;
762                         }
763                 }
764
765                 public override AnonymousMethodStorey Storey {
766                         get {
767                                 return storey;
768                         }
769                 }
770
771                 #endregion
772
773                 public int AddResumePoint (ResumableStatement stmt)
774                 {
775                         if (resume_points == null)
776                                 resume_points = new List<ResumableStatement> ();
777
778                         resume_points.Add (stmt);
779                         return resume_points.Count;
780                 }
781
782                 public override Expression CreateExpressionTree (ResolveContext ec)
783                 {
784                         throw new NotSupportedException ("ET");
785                 }
786
787                 protected virtual BlockContext CreateBlockContext (BlockContext bc)
788                 {
789                         var ctx = new BlockContext (bc, block, bc.ReturnType);
790                         ctx.CurrentAnonymousMethod = this;
791
792                         ctx.AssignmentInfoOffset = bc.AssignmentInfoOffset;
793                         ctx.EnclosingLoop = bc.EnclosingLoop;
794                         ctx.EnclosingLoopOrSwitch = bc.EnclosingLoopOrSwitch;
795                         ctx.Switch = bc.Switch;
796
797                         return ctx;
798                 }
799
800                 protected override Expression DoResolve (ResolveContext rc)
801                 {
802                         var bc = (BlockContext) rc;
803                         var ctx = CreateBlockContext (bc);
804
805                         Block.Resolve (ctx);
806
807                         if (!rc.IsInProbingMode) {
808                                 var move_next = new StateMachineMethod (storey, this, new TypeExpression (ReturnType, loc), Modifiers.PUBLIC, new MemberName ("MoveNext", loc), 0);
809                                 move_next.Block.AddStatement (new MoveNextBodyStatement (this));
810                                 storey.AddEntryMethod (move_next);
811                         }
812
813                         bc.AssignmentInfoOffset = ctx.AssignmentInfoOffset;
814                         eclass = ExprClass.Value;
815                         return this;
816                 }
817
818                 public override void Emit (EmitContext ec)
819                 {
820                         //
821                         // Load state machine instance
822                         //
823                         storey.Instance.Emit (ec);
824                 }
825
826                 void EmitMoveNext_NoResumePoints (EmitContext ec)
827                 {
828                         ec.EmitThis ();
829                         ec.Emit (OpCodes.Ldfld, storey.PC.Spec);
830
831                         ec.EmitThis ();
832                         ec.EmitInt ((int) IteratorStorey.State.After);
833                         ec.Emit (OpCodes.Stfld, storey.PC.Spec);
834
835                         // We only care if the PC is zero (start executing) or non-zero (don't do anything)
836                         ec.Emit (OpCodes.Brtrue, move_next_error);
837
838                         BodyEnd = ec.DefineLabel ();
839
840                         var async_init = this as AsyncInitializer;
841                         if (async_init != null)
842                                 ec.BeginExceptionBlock ();
843
844                         block.EmitEmbedded (ec);
845
846                         if (async_init != null)
847                                 async_init.EmitCatchBlock (ec);
848
849                         ec.MarkLabel (BodyEnd);
850
851                         EmitMoveNextEpilogue (ec);
852
853                         ec.MarkLabel (move_next_error);
854
855                         if (ReturnType.Kind != MemberKind.Void) {
856                                 ec.EmitInt (0);
857                                 ec.Emit (OpCodes.Ret);
858                         }
859
860                         ec.MarkLabel (move_next_ok);
861                 }
862
863                 void EmitMoveNext (EmitContext ec)
864                 {
865                         move_next_ok = ec.DefineLabel ();
866                         move_next_error = ec.DefineLabel ();
867
868                         if (resume_points == null) {
869                                 EmitMoveNext_NoResumePoints (ec);
870                                 return;
871                         }
872                         
873                         current_pc = ec.GetTemporaryLocal (ec.BuiltinTypes.UInt);
874                         ec.EmitThis ();
875                         ec.Emit (OpCodes.Ldfld, storey.PC.Spec);
876                         ec.Emit (OpCodes.Stloc, current_pc);
877
878                         // We're actually in state 'running', but this is as good a PC value as any if there's an abnormal exit
879                         ec.EmitThis ();
880                         ec.EmitInt ((int) IteratorStorey.State.After);
881                         ec.Emit (OpCodes.Stfld, storey.PC.Spec);
882
883                         Label[] labels = new Label[1 + resume_points.Count];
884                         labels[0] = ec.DefineLabel ();
885
886                         bool need_skip_finally = false;
887                         for (int i = 0; i < resume_points.Count; ++i) {
888                                 ResumableStatement s = resume_points[i];
889                                 need_skip_finally |= s is ExceptionStatement;
890                                 labels[i + 1] = s.PrepareForEmit (ec);
891                         }
892
893                         if (need_skip_finally) {
894                                 skip_finally = ec.GetTemporaryLocal (ec.BuiltinTypes.Bool);
895                                 ec.EmitInt (0);
896                                 ec.Emit (OpCodes.Stloc, skip_finally);
897                         }
898
899                         var async_init = this as AsyncInitializer;
900                         if (async_init != null)
901                                 ec.BeginExceptionBlock ();
902
903                         ec.Emit (OpCodes.Ldloc, current_pc);
904                         ec.Emit (OpCodes.Switch, labels);
905
906                         ec.Emit (async_init != null ? OpCodes.Leave : OpCodes.Br, move_next_error);
907
908                         ec.MarkLabel (labels[0]);
909
910                         BodyEnd = ec.DefineLabel ();
911
912                         block.EmitEmbedded (ec);
913
914                         ec.MarkLabel (BodyEnd);
915
916                         if (async_init != null) {
917                                 async_init.EmitCatchBlock (ec);
918                         }
919
920                         ec.Mark (Block.Original.EndLocation);
921                         ec.EmitThis ();
922                         ec.EmitInt ((int) IteratorStorey.State.After);
923                         ec.Emit (OpCodes.Stfld, storey.PC.Spec);
924
925                         EmitMoveNextEpilogue (ec);
926
927                         ec.MarkLabel (move_next_error);
928                         
929                         if (ReturnType.Kind != MemberKind.Void) {
930                                 ec.EmitInt (0);
931                                 ec.Emit (OpCodes.Ret);
932                         }
933
934                         ec.MarkLabel (move_next_ok);
935
936                         if (ReturnType.Kind != MemberKind.Void) {
937                                 ec.EmitInt (1);
938                                 ec.Emit (OpCodes.Ret);
939                         }
940                 }
941
942                 protected virtual void EmitMoveNextEpilogue (EmitContext ec)
943                 {
944                 }
945
946                 public void EmitLeave (EmitContext ec, bool unwind_protect)
947                 {
948                         // Return ok
949                         ec.Emit (unwind_protect ? OpCodes.Leave : OpCodes.Br, move_next_ok);
950                 }
951
952                 //
953                 // Called back from YieldStatement
954                 //
955                 public virtual void InjectYield (EmitContext ec, Expression expr, int resume_pc, bool unwind_protect, Label resume_point)
956                 {
957                         //
958                         // Guard against being disposed meantime
959                         //
960                         Label disposed = ec.DefineLabel ();
961                         var iterator = storey as IteratorStorey;
962                         if (iterator != null) {
963                                 ec.EmitThis ();
964                                 ec.Emit (OpCodes.Ldfld, iterator.DisposingField.Spec);
965                                 ec.Emit (OpCodes.Brtrue_S, disposed);
966                         }
967
968                         //
969                         // store resume program-counter
970                         //
971                         ec.EmitThis ();
972                         ec.EmitInt (resume_pc);
973                         ec.Emit (OpCodes.Stfld, storey.PC.Spec);
974
975                         if (iterator != null) {
976                                 ec.MarkLabel (disposed);
977                         }
978
979                         // mark finally blocks as disabled
980                         if (unwind_protect && skip_finally != null) {
981                                 ec.EmitInt (1);
982                                 ec.Emit (OpCodes.Stloc, skip_finally);
983                         }
984                 }
985
986                 public void SetStateMachine (StateMachine stateMachine)
987                 {
988                         this.storey = stateMachine;
989                 }
990         }
991
992         //
993         // Iterators are implemented as state machine blocks
994         //
995         public class Iterator : StateMachineInitializer
996         {
997                 sealed class TryFinallyBlockProxyStatement : Statement
998                 {
999                         TryFinallyBlock block;
1000                         Iterator iterator;
1001
1002                         public TryFinallyBlockProxyStatement (Iterator iterator, TryFinallyBlock block)
1003                         {
1004                                 this.iterator = iterator;
1005                                 this.block = block;
1006                         }
1007
1008                         protected override void CloneTo (CloneContext clonectx, Statement target)
1009                         {
1010                                 throw new NotSupportedException ();
1011                         }
1012
1013                         protected override bool DoFlowAnalysis (FlowAnalysisContext fc)
1014                         {
1015                                 throw new NotSupportedException ();
1016                         }
1017
1018                         protected override void DoEmit (EmitContext ec)
1019                         {
1020                                 //
1021                                 // Restore redirection for any captured variables
1022                                 //
1023                                 ec.CurrentAnonymousMethod = iterator;
1024
1025                                 using (ec.With (BuilderContext.Options.OmitDebugInfo, !ec.HasMethodSymbolBuilder)) {
1026                                         block.EmitFinallyBody (ec);
1027                                 }
1028                         }
1029                 }
1030
1031                 public readonly IMethodData OriginalMethod;
1032                 public readonly bool IsEnumerable;
1033                 public readonly TypeSpec OriginalIteratorType;
1034                 int finally_hosts_counter;
1035
1036                 public Iterator (ParametersBlock block, IMethodData method, TypeDefinition host, TypeSpec iterator_type, bool is_enumerable)
1037                         : base (block, host, host.Compiler.BuiltinTypes.Bool)
1038                 {
1039                         this.OriginalMethod = method;
1040                         this.OriginalIteratorType = iterator_type;
1041                         this.IsEnumerable = is_enumerable;
1042                         this.type = method.ReturnType;
1043                 }
1044
1045                 #region Properties
1046
1047                 public ToplevelBlock Container {
1048                         get { return OriginalMethod.Block; }
1049                 }
1050
1051                 public override string ContainerType {
1052                         get { return "iterator"; }
1053                 }
1054
1055                 public override bool IsIterator {
1056                         get { return true; }
1057                 }
1058
1059                 #endregion
1060
1061                 public Method CreateFinallyHost (TryFinallyBlock block)
1062                 {
1063                         var method = new Method (storey, new TypeExpression (storey.Compiler.BuiltinTypes.Void, loc),
1064                                 Modifiers.COMPILER_GENERATED, new MemberName (CompilerGeneratedContainer.MakeName (null, null, "Finally", finally_hosts_counter++), loc),
1065                                 ParametersCompiled.EmptyReadOnlyParameters, null);
1066
1067                         method.Block = new ToplevelBlock (method.Compiler, method.ParameterInfo, loc,
1068                                 ToplevelBlock.Flags.CompilerGenerated | ToplevelBlock.Flags.NoFlowAnalysis);
1069
1070                         method.Block.AddStatement (new TryFinallyBlockProxyStatement (this, block));
1071
1072                         // Cannot it add to storey because it'd be emitted before nested
1073                         // anonoymous methods which could capture shared variable
1074
1075                         return method;
1076                 }
1077
1078                 public void EmitYieldBreak (EmitContext ec, bool unwind_protect)
1079                 {
1080                         ec.Emit (unwind_protect ? OpCodes.Leave : OpCodes.Br, move_next_error);
1081                 }
1082
1083                 public override string GetSignatureForError ()
1084                 {
1085                         return OriginalMethod.GetSignatureForError ();
1086                 }
1087
1088                 public override void Emit (EmitContext ec)
1089                 {
1090                         //
1091                         // Load Iterator storey instance
1092                         //
1093                         storey.Instance.Emit (ec);
1094
1095                         //
1096                         // Initialize iterator PC when it's unitialized
1097                         //
1098                         if (IsEnumerable) {
1099                                 ec.Emit (OpCodes.Dup);
1100                                 ec.EmitInt ((int)IteratorStorey.State.Uninitialized);
1101
1102                                 var field = storey.PC.Spec;
1103                                 if (storey.MemberName.IsGeneric) {
1104                                         field = MemberCache.GetMember (Storey.Instance.Type, field);
1105                                 }
1106
1107                                 ec.Emit (OpCodes.Stfld, field);
1108                         }
1109                 }
1110
1111                 public void EmitDispose (EmitContext ec)
1112                 {
1113                         if (resume_points == null)
1114                                 return;
1115
1116                         Label end = ec.DefineLabel ();
1117
1118                         Label[] labels = null;
1119                         for (int i = 0; i < resume_points.Count; ++i) {
1120                                 ResumableStatement s = resume_points[i];
1121                                 Label ret = s.PrepareForDispose (ec, end);
1122                                 if (ret.Equals (end) && labels == null)
1123                                         continue;
1124                                 if (labels == null) {
1125                                         labels = new Label[resume_points.Count + 1];
1126                                         for (int j = 0; j <= i; ++j)
1127                                                 labels[j] = end;
1128                                 }
1129
1130                                 labels[i + 1] = ret;
1131                         }
1132
1133                         if (labels != null) {
1134                                 current_pc = ec.GetTemporaryLocal (ec.BuiltinTypes.UInt);
1135                                 ec.EmitThis ();
1136                                 ec.Emit (OpCodes.Ldfld, storey.PC.Spec);
1137                                 ec.Emit (OpCodes.Stloc, current_pc);
1138                         }
1139
1140                         ec.EmitThis ();
1141                         ec.EmitInt (1);
1142                         ec.Emit (OpCodes.Stfld, ((IteratorStorey) storey).DisposingField.Spec);
1143
1144                         ec.EmitThis ();
1145                         ec.EmitInt ((int) IteratorStorey.State.After);
1146                         ec.Emit (OpCodes.Stfld, storey.PC.Spec);
1147
1148                         if (labels != null) {
1149                                 //SymbolWriter.StartIteratorDispatcher (ec.ig);
1150                                 ec.Emit (OpCodes.Ldloc, current_pc);
1151                                 ec.Emit (OpCodes.Switch, labels);
1152                                 //SymbolWriter.EndIteratorDispatcher (ec.ig);
1153
1154                                 foreach (ResumableStatement s in resume_points)
1155                                         s.EmitForDispose (ec, current_pc, end, true);
1156                         }
1157
1158                         ec.MarkLabel (end);
1159                 }
1160
1161                 public override void EmitStatement (EmitContext ec)
1162                 {
1163                         throw new NotImplementedException ();
1164                 }
1165
1166                 public override void InjectYield (EmitContext ec, Expression expr, int resume_pc, bool unwind_protect, Label resume_point)
1167                 {
1168                         // Store the new value into current
1169                         var fe = new FieldExpr (((IteratorStorey) storey).CurrentField, loc);
1170                         fe.InstanceExpression = new CompilerGeneratedThis (storey.CurrentType, loc);
1171                         fe.EmitAssign (ec, expr, false, false);
1172
1173                         base.InjectYield (ec, expr, resume_pc, unwind_protect, resume_point);
1174
1175                         EmitLeave (ec, unwind_protect);
1176
1177                         ec.MarkLabel (resume_point);
1178                 }
1179
1180                 public static void CreateIterator (IMethodData method, TypeDefinition parent, Modifiers modifiers)
1181                 {
1182                         bool is_enumerable;
1183                         TypeSpec iterator_type;
1184
1185                         TypeSpec ret = method.ReturnType;
1186                         if (ret == null)
1187                                 return;
1188
1189                         if (!CheckType (ret, parent, out iterator_type, out is_enumerable)) {
1190                                 parent.Compiler.Report.Error (1624, method.Location,
1191                                               "The body of `{0}' cannot be an iterator block " +
1192                                               "because `{1}' is not an iterator interface type",
1193                                               method.GetSignatureForError (),
1194                                               ret.GetSignatureForError ());
1195                                 return;
1196                         }
1197
1198                         ParametersCompiled parameters = method.ParameterInfo;
1199                         for (int i = 0; i < parameters.Count; i++) {
1200                                 Parameter p = parameters [i];
1201                                 Parameter.Modifier mod = p.ModFlags;
1202                                 if ((mod & Parameter.Modifier.RefOutMask) != 0) {
1203                                         parent.Compiler.Report.Error (1623, p.Location,
1204                                                 "Iterators cannot have ref or out parameters");
1205                                         return;
1206                                 }
1207
1208                                 if (p is ArglistParameter) {
1209                                         parent.Compiler.Report.Error (1636, method.Location,
1210                                                 "__arglist is not allowed in parameter list of iterators");
1211                                         return;
1212                                 }
1213
1214                                 if (parameters.Types [i].IsPointer) {
1215                                         parent.Compiler.Report.Error (1637, p.Location,
1216                                                 "Iterators cannot have unsafe parameters or yield types");
1217                                         return;
1218                                 }
1219                         }
1220
1221                         if ((modifiers & Modifiers.UNSAFE) != 0) {
1222                                 Expression.UnsafeInsideIteratorError (parent.Compiler.Report, method.Location);
1223                         }
1224
1225                         method.Block = method.Block.ConvertToIterator (method, parent, iterator_type, is_enumerable);
1226                 }
1227
1228                 static bool CheckType (TypeSpec ret, TypeContainer parent, out TypeSpec original_iterator_type, out bool is_enumerable)
1229                 {
1230                         original_iterator_type = null;
1231                         is_enumerable = false;
1232
1233                         if (ret.BuiltinType == BuiltinTypeSpec.Type.IEnumerable) {
1234                                 original_iterator_type = parent.Compiler.BuiltinTypes.Object;
1235                                 is_enumerable = true;
1236                                 return true;
1237                         }
1238                         if (ret.BuiltinType == BuiltinTypeSpec.Type.IEnumerator) {
1239                                 original_iterator_type = parent.Compiler.BuiltinTypes.Object;
1240                                 is_enumerable = false;
1241                                 return true;
1242                         }
1243
1244                         InflatedTypeSpec inflated = ret as InflatedTypeSpec;
1245                         if (inflated == null)
1246                                 return false;
1247
1248                         var member_definition = inflated.MemberDefinition;
1249                         PredefinedType ptype = parent.Module.PredefinedTypes.IEnumerableGeneric;
1250
1251                         if (ptype.Define () && ptype.TypeSpec.MemberDefinition == member_definition) {
1252                                 original_iterator_type = inflated.TypeArguments[0];
1253                                 is_enumerable = true;
1254                                 return true;
1255                         }
1256
1257                         ptype = parent.Module.PredefinedTypes.IEnumeratorGeneric;
1258                         if (ptype.Define () && ptype.TypeSpec.MemberDefinition == member_definition) {
1259                                 original_iterator_type = inflated.TypeArguments[0];
1260                                 is_enumerable = false;
1261                                 return true;
1262                         }
1263
1264                         return false;
1265                 }
1266         }
1267 }
1268