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