minor fix for bug 9520:
[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];
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 TypeSpec[] ResolveBaseTypes (out FullNamedExpression base_class)
435                 {
436                         var mtype = Iterator.OriginalIteratorType;
437                         if (Mutator != null)
438                                 mtype = Mutator.Mutate (mtype);
439
440                         iterator_type_expr = new TypeExpression (mtype, Location);
441
442                         var ifaces = new List<TypeSpec> (5);
443                         if (Iterator.IsEnumerable) {
444                                 ifaces.Add (Compiler.BuiltinTypes.IEnumerable);
445
446                                 if (Module.PredefinedTypes.IEnumerableGeneric.Define ()) {
447                                         generic_enumerable_type = Module.PredefinedTypes.IEnumerableGeneric.TypeSpec.MakeGenericType (Module, new[] { mtype });
448                                         ifaces.Add (generic_enumerable_type);
449                                 }
450                         }
451
452                         ifaces.Add (Compiler.BuiltinTypes.IEnumerator);
453                         ifaces.Add (Compiler.BuiltinTypes.IDisposable);
454
455                         var ienumerator_generic = Module.PredefinedTypes.IEnumeratorGeneric;
456                         if (ienumerator_generic.Define ()) {
457                                 generic_enumerator_type = ienumerator_generic.TypeSpec.MakeGenericType (Module, new [] { mtype });
458                                 ifaces.Add (generic_enumerator_type);
459                         }
460
461                         base_class = null;
462
463                         base_type = Compiler.BuiltinTypes.Object;
464                         return ifaces.ToArray ();
465                 }
466
467                 protected override bool DoDefineMembers ()
468                 {
469                         current_field = AddCompilerGeneratedField ("$current", iterator_type_expr);
470                         disposing_field = AddCompilerGeneratedField ("$disposing", new TypeExpression (Compiler.BuiltinTypes.Bool, Location));
471
472                         if (hoisted_params != null) {
473                                 //
474                                 // Iterators are independent, each GetEnumerator call has to
475                                 // create same enumerator therefore we have to keep original values
476                                 // around for re-initialization
477                                 //
478                                 // TODO: Do it for assigned/modified parameters only
479                                 //
480                                 hoisted_params_copy = new List<HoistedParameter> (hoisted_params.Count);
481                                 foreach (HoistedParameter hp in hoisted_params) {
482                                         hoisted_params_copy.Add (new HoistedParameter (hp, "<$>" + hp.Field.Name));
483                                 }
484                         }
485
486                         if (generic_enumerator_type != null)
487                                 Define_Current (true);
488
489                         Define_Current (false);
490                         new DisposeMethod (this);
491                         Define_Reset ();
492
493                         if (Iterator.IsEnumerable) {
494                                 FullNamedExpression explicit_iface = new TypeExpression (Compiler.BuiltinTypes.IEnumerable, Location);
495                                 var name = new MemberName ("GetEnumerator", null, explicit_iface, Location.Null);
496
497                                 if (generic_enumerator_type != null) {
498                                         explicit_iface = new TypeExpression (generic_enumerable_type, Location);
499                                         var gname = new MemberName ("GetEnumerator", null, explicit_iface, Location.Null);
500                                         Method gget_enumerator = GetEnumeratorMethod.Create (this, new TypeExpression (generic_enumerator_type, Location), gname);
501
502                                         //
503                                         // Just call generic GetEnumerator implementation
504                                         //
505                                         var stmt = new Return (new Invocation (new DynamicMethodGroupExpr (gget_enumerator, Location), null), Location);
506                                         Method get_enumerator = GetEnumeratorMethod.Create (this, new TypeExpression (Compiler.BuiltinTypes.IEnumerator, Location), name, stmt);
507
508                                         Members.Add (get_enumerator);
509                                         Members.Add (gget_enumerator);
510                                 } else {
511                                         Members.Add (GetEnumeratorMethod.Create (this, new TypeExpression (Compiler.BuiltinTypes.IEnumerator, Location), name));
512                                 }
513                         }
514
515                         return base.DoDefineMembers ();
516                 }
517
518                 void Define_Current (bool is_generic)
519                 {
520                         TypeExpr type;
521                         FullNamedExpression explicit_iface;
522
523                         if (is_generic) {
524                                 explicit_iface = new TypeExpression (generic_enumerator_type, Location);
525                                 type = iterator_type_expr;
526                         } else {
527                                 explicit_iface = new TypeExpression (Module.Compiler.BuiltinTypes.IEnumerator, Location);
528                                 type = new TypeExpression (Compiler.BuiltinTypes.Object, Location);
529                         }
530
531                         var name = new MemberName ("Current", null, explicit_iface, Location);
532
533                         ToplevelBlock get_block = new ToplevelBlock (Compiler, Location) {
534                                 IsCompilerGenerated = true
535                         };
536                         get_block.AddStatement (new Return (new DynamicFieldExpr (CurrentField, Location), Location));
537                                 
538                         Property current = new Property (this, type, Modifiers.DEBUGGER_HIDDEN | Modifiers.COMPILER_GENERATED, name, null);
539                         current.Get = new Property.GetMethod (current, Modifiers.COMPILER_GENERATED, null, Location);
540                         current.Get.Block = get_block;
541
542                         Members.Add (current);
543                 }
544
545                 void Define_Reset ()
546                 {
547                         Method reset = new Method (
548                                 this, new TypeExpression (Compiler.BuiltinTypes.Void, Location),
549                                 Modifiers.PUBLIC | Modifiers.DEBUGGER_HIDDEN | Modifiers.COMPILER_GENERATED,
550                                 new MemberName ("Reset", Location),
551                                 ParametersCompiled.EmptyReadOnlyParameters, null);
552                         Members.Add (reset);
553
554                         reset.Block = new ToplevelBlock (Compiler, Location) {
555                                 IsCompilerGenerated = true
556                         };
557
558                         TypeSpec ex_type = Module.PredefinedTypes.NotSupportedException.Resolve ();
559                         if (ex_type == null)
560                                 return;
561
562                         reset.Block.AddStatement (new Throw (new New (new TypeExpression (ex_type, Location), null, Location), Location));
563                 }
564
565                 protected override void EmitHoistedParameters (EmitContext ec, List<HoistedParameter> hoisted)
566                 {
567                         base.EmitHoistedParameters (ec, hoisted);
568                         base.EmitHoistedParameters (ec, hoisted_params_copy);
569                 }
570         }
571
572         public class StateMachineMethod : Method
573         {
574                 readonly StateMachineInitializer expr;
575
576                 public StateMachineMethod (StateMachine host, StateMachineInitializer expr, FullNamedExpression returnType, Modifiers mod, MemberName name)
577                         : base (host, returnType, mod | Modifiers.COMPILER_GENERATED,
578                           name, ParametersCompiled.EmptyReadOnlyParameters, null)
579                 {
580                         this.expr = expr;
581                         Block = new ToplevelBlock (host.Compiler, ParametersCompiled.EmptyReadOnlyParameters, Location.Null);
582                 }
583
584                 public override EmitContext CreateEmitContext (ILGenerator ig, SourceMethodBuilder sourceMethod)
585                 {
586                         EmitContext ec = new EmitContext (this, ig, MemberType, sourceMethod);
587                         ec.CurrentAnonymousMethod = expr;
588
589                         if (expr is AsyncInitializer)
590                                 ec.With (BuilderContext.Options.AsyncBody, true);
591
592                         return ec;
593                 }
594         }
595
596         public abstract class StateMachineInitializer : AnonymousExpression
597         {
598                 sealed class MoveNextBodyStatement : Statement
599                 {
600                         readonly StateMachineInitializer state_machine;
601
602                         public MoveNextBodyStatement (StateMachineInitializer stateMachine)
603                         {
604                                 this.state_machine = stateMachine;
605                                 this.loc = stateMachine.Location;
606                         }
607
608                         protected override void CloneTo (CloneContext clonectx, Statement target)
609                         {
610                                 throw new NotSupportedException ();
611                         }
612
613                         public override bool Resolve (BlockContext ec)
614                         {
615                                 return true;
616                         }
617
618                         protected override void DoEmit (EmitContext ec)
619                         {
620                                 state_machine.EmitMoveNext (ec);
621                         }
622
623                         public override void Emit (EmitContext ec)
624                         {
625                                 // Don't create sequence point
626                                 DoEmit (ec);
627                         }
628                 }
629
630                 public readonly TypeDefinition Host;
631                 protected StateMachine storey;
632
633                 //
634                 // The state as we generate the machine
635                 //
636                 Label move_next_ok;
637                 Label iterator_body_end;
638                 protected Label move_next_error;
639                 LocalBuilder skip_finally;
640                 protected LocalBuilder current_pc;
641                 protected List<ResumableStatement> resume_points;
642
643                 protected StateMachineInitializer (ParametersBlock block, TypeDefinition host, TypeSpec returnType)
644                         : base (block, returnType, block.StartLocation)
645                 {
646                         this.Host = host;
647                 }
648
649                 #region Properties
650
651                 public Label BodyEnd {
652                         get {
653                                 return iterator_body_end;
654                         }
655                 }
656
657                 public LocalBuilder CurrentPC
658                 {
659                         get {
660                                 return current_pc;
661                         }
662                 }
663
664                 public LocalBuilder SkipFinally {
665                         get {
666                                 return skip_finally;
667                         }
668                 }
669
670                 public override AnonymousMethodStorey Storey {
671                         get {
672                                 return storey;
673                         }
674                 }
675
676                 #endregion
677
678                 public int AddResumePoint (ResumableStatement stmt)
679                 {
680                         if (resume_points == null)
681                                 resume_points = new List<ResumableStatement> ();
682
683                         resume_points.Add (stmt);
684                         return resume_points.Count;
685                 }
686
687                 public override Expression CreateExpressionTree (ResolveContext ec)
688                 {
689                         throw new NotSupportedException ("ET");
690                 }
691
692                 protected virtual BlockContext CreateBlockContext (ResolveContext rc)
693                 {
694                         var ctx = new BlockContext (rc, block, ((BlockContext) rc).ReturnType);
695                         ctx.CurrentAnonymousMethod = this;
696                         return ctx;
697                 }
698
699                 protected override Expression DoResolve (ResolveContext ec)
700                 {
701                         var ctx = CreateBlockContext (ec);
702
703                         Block.Resolve (ctx);
704
705                         //
706                         // Explicit return is required for Task<T> state machine
707                         //
708                         var task_storey = storey as AsyncTaskStorey;
709                         if (task_storey == null || (task_storey.ReturnType != null && !task_storey.ReturnType.IsGenericTask))
710                                 ctx.CurrentBranching.CurrentUsageVector.Goto ();
711
712                         ctx.EndFlowBranching ();
713
714                         if (!ec.IsInProbingMode) {
715                                 var move_next = new StateMachineMethod (storey, this, new TypeExpression (ReturnType, loc), Modifiers.PUBLIC, new MemberName ("MoveNext", loc));
716                                 move_next.Block.AddStatement (new MoveNextBodyStatement (this));
717                                 storey.AddEntryMethod (move_next);
718                         }
719
720                         eclass = ExprClass.Value;
721                         return this;
722                 }
723
724                 public override void Emit (EmitContext ec)
725                 {
726                         //
727                         // Load state machine instance
728                         //
729                         storey.Instance.Emit (ec);
730                 }
731
732                 void EmitMoveNext_NoResumePoints (EmitContext ec)
733                 {
734                         ec.EmitThis ();
735                         ec.Emit (OpCodes.Ldfld, storey.PC.Spec);
736
737                         ec.EmitThis ();
738                         ec.EmitInt ((int) IteratorStorey.State.After);
739                         ec.Emit (OpCodes.Stfld, storey.PC.Spec);
740
741                         // We only care if the PC is zero (start executing) or non-zero (don't do anything)
742                         ec.Emit (OpCodes.Brtrue, move_next_error);
743
744                         iterator_body_end = ec.DefineLabel ();
745
746                         block.EmitEmbedded (ec);
747
748                         ec.MarkLabel (iterator_body_end);
749
750                         EmitMoveNextEpilogue (ec);
751
752                         ec.MarkLabel (move_next_error);
753
754                         if (ReturnType.Kind != MemberKind.Void) {
755                                 ec.EmitInt (0);
756                                 ec.Emit (OpCodes.Ret);
757                         }
758                 }
759
760                 void EmitMoveNext (EmitContext ec)
761                 {
762                         move_next_ok = ec.DefineLabel ();
763                         move_next_error = ec.DefineLabel ();
764
765                         if (resume_points == null) {
766                                 EmitMoveNext_NoResumePoints (ec);
767                                 return;
768                         }
769                         
770                         current_pc = ec.GetTemporaryLocal (ec.BuiltinTypes.UInt);
771                         ec.EmitThis ();
772                         ec.Emit (OpCodes.Ldfld, storey.PC.Spec);
773                         ec.Emit (OpCodes.Stloc, current_pc);
774
775                         // We're actually in state 'running', but this is as good a PC value as any if there's an abnormal exit
776                         ec.EmitThis ();
777                         ec.EmitInt ((int) IteratorStorey.State.After);
778                         ec.Emit (OpCodes.Stfld, storey.PC.Spec);
779
780                         Label[] labels = new Label[1 + resume_points.Count];
781                         labels[0] = ec.DefineLabel ();
782
783                         bool need_skip_finally = false;
784                         for (int i = 0; i < resume_points.Count; ++i) {
785                                 ResumableStatement s = resume_points[i];
786                                 need_skip_finally |= s is ExceptionStatement;
787                                 labels[i + 1] = s.PrepareForEmit (ec);
788                         }
789
790                         if (need_skip_finally) {
791                                 skip_finally = ec.GetTemporaryLocal (ec.BuiltinTypes.Bool);
792                                 ec.EmitInt (0);
793                                 ec.Emit (OpCodes.Stloc, skip_finally);
794                         }
795
796                         var async_init = this as AsyncInitializer;
797                         if (async_init != null)
798                                 ec.BeginExceptionBlock ();
799
800                         ec.Emit (OpCodes.Ldloc, current_pc);
801                         ec.Emit (OpCodes.Switch, labels);
802
803                         ec.Emit (async_init != null ? OpCodes.Leave : OpCodes.Br, move_next_error);
804
805                         ec.MarkLabel (labels[0]);
806
807                         iterator_body_end = ec.DefineLabel ();
808
809                         block.EmitEmbedded (ec);
810
811                         ec.MarkLabel (iterator_body_end);
812
813                         if (async_init != null) {
814                                 var catch_value = LocalVariable.CreateCompilerGenerated (ec.Module.Compiler.BuiltinTypes.Exception, block, Location);
815
816                                 ec.BeginCatchBlock (catch_value.Type);
817                                 catch_value.EmitAssign (ec);
818
819                                 ec.EmitThis ();
820                                 ec.EmitInt ((int) IteratorStorey.State.After);
821                                 ec.Emit (OpCodes.Stfld, storey.PC.Spec);
822
823                                 ((AsyncTaskStorey) async_init.Storey).EmitSetException (ec, new LocalVariableReference (catch_value, Location));
824
825                                 ec.Emit (OpCodes.Leave, move_next_ok);
826                                 ec.EndExceptionBlock ();
827                         }
828
829                         ec.Mark (Block.Original.EndLocation);
830                         ec.EmitThis ();
831                         ec.EmitInt ((int) IteratorStorey.State.After);
832                         ec.Emit (OpCodes.Stfld, storey.PC.Spec);
833
834                         EmitMoveNextEpilogue (ec);
835
836                         ec.MarkLabel (move_next_error);
837                         
838                         if (ReturnType.Kind != MemberKind.Void) {
839                                 ec.EmitInt (0);
840                                 ec.Emit (OpCodes.Ret);
841                         }
842
843                         ec.MarkLabel (move_next_ok);
844
845                         if (ReturnType.Kind != MemberKind.Void) {
846                                 ec.EmitInt (1);
847                                 ec.Emit (OpCodes.Ret);
848                         }
849                 }
850
851                 protected virtual void EmitMoveNextEpilogue (EmitContext ec)
852                 {
853                 }
854
855                 public void EmitLeave (EmitContext ec, bool unwind_protect)
856                 {
857                         // Return ok
858                         ec.Emit (unwind_protect ? OpCodes.Leave : OpCodes.Br, move_next_ok);
859                 }
860
861                 //
862                 // Called back from YieldStatement
863                 //
864                 public virtual void InjectYield (EmitContext ec, Expression expr, int resume_pc, bool unwind_protect, Label resume_point)
865                 {
866                         //
867                         // Guard against being disposed meantime
868                         //
869                         Label disposed = ec.DefineLabel ();
870                         var iterator = storey as IteratorStorey;
871                         if (iterator != null) {
872                                 ec.EmitThis ();
873                                 ec.Emit (OpCodes.Ldfld, iterator.DisposingField.Spec);
874                                 ec.Emit (OpCodes.Brtrue_S, disposed);
875                         }
876
877                         //
878                         // store resume program-counter
879                         //
880                         ec.EmitThis ();
881                         ec.EmitInt (resume_pc);
882                         ec.Emit (OpCodes.Stfld, storey.PC.Spec);
883
884                         if (iterator != null) {
885                                 ec.MarkLabel (disposed);
886                         }
887
888                         // mark finally blocks as disabled
889                         if (unwind_protect && skip_finally != null) {
890                                 ec.EmitInt (1);
891                                 ec.Emit (OpCodes.Stloc, skip_finally);
892                         }
893                 }
894
895                 public void SetStateMachine (StateMachine stateMachine)
896                 {
897                         this.storey = stateMachine;
898                 }
899         }
900
901         //
902         // Iterators are implemented as state machine blocks
903         //
904         public class Iterator : StateMachineInitializer
905         {
906                 sealed class TryFinallyBlockProxyStatement : Statement
907                 {
908                         TryFinallyBlock block;
909                         Iterator iterator;
910
911                         public TryFinallyBlockProxyStatement (Iterator iterator, TryFinallyBlock block)
912                         {
913                                 this.iterator = iterator;
914                                 this.block = block;
915                         }
916
917                         protected override void CloneTo (CloneContext clonectx, Statement target)
918                         {
919                                 throw new NotSupportedException ();
920                         }
921
922                         protected override void DoEmit (EmitContext ec)
923                         {
924                                 //
925                                 // Restore redirection for any captured variables
926                                 //
927                                 ec.CurrentAnonymousMethod = iterator;
928
929                                 using (ec.With (BuilderContext.Options.OmitDebugInfo, !ec.HasMethodSymbolBuilder)) {
930                                         block.EmitFinallyBody (ec);
931                                 }
932                         }
933                 }
934
935                 public readonly IMethodData OriginalMethod;
936                 public readonly bool IsEnumerable;
937                 public readonly TypeSpec OriginalIteratorType;
938                 int finally_hosts_counter;
939
940                 public Iterator (ParametersBlock block, IMethodData method, TypeDefinition host, TypeSpec iterator_type, bool is_enumerable)
941                         : base (block, host, host.Compiler.BuiltinTypes.Bool)
942                 {
943                         this.OriginalMethod = method;
944                         this.OriginalIteratorType = iterator_type;
945                         this.IsEnumerable = is_enumerable;
946                         this.type = method.ReturnType;
947                 }
948
949                 #region Properties
950
951                 public ToplevelBlock Container {
952                         get { return OriginalMethod.Block; }
953                 }
954
955                 public override string ContainerType {
956                         get { return "iterator"; }
957                 }
958
959                 public override bool IsIterator {
960                         get { return true; }
961                 }
962
963                 #endregion
964
965                 public Method CreateFinallyHost (TryFinallyBlock block)
966                 {
967                         var method = new Method (storey, new TypeExpression (storey.Compiler.BuiltinTypes.Void, loc),
968                                 Modifiers.COMPILER_GENERATED, new MemberName (CompilerGeneratedContainer.MakeName (null, null, "Finally", finally_hosts_counter++), loc),
969                                 ParametersCompiled.EmptyReadOnlyParameters, null);
970
971                         method.Block = new ToplevelBlock (method.Compiler, method.ParameterInfo, loc);
972                         method.Block.IsCompilerGenerated = true;
973                         method.Block.AddStatement (new TryFinallyBlockProxyStatement (this, block));
974
975                         // Cannot it add to storey because it'd be emitted before nested
976                         // anonoymous methods which could capture shared variable
977
978                         return method;
979                 }
980
981                 public void EmitYieldBreak (EmitContext ec, bool unwind_protect)
982                 {
983                         ec.Emit (unwind_protect ? OpCodes.Leave : OpCodes.Br, move_next_error);
984                 }
985
986                 public override string GetSignatureForError ()
987                 {
988                         return OriginalMethod.GetSignatureForError ();
989                 }
990
991                 public override void Emit (EmitContext ec)
992                 {
993                         //
994                         // Load Iterator storey instance
995                         //
996                         storey.Instance.Emit (ec);
997
998                         //
999                         // Initialize iterator PC when it's unitialized
1000                         //
1001                         if (IsEnumerable) {
1002                                 ec.Emit (OpCodes.Dup);
1003                                 ec.EmitInt ((int)IteratorStorey.State.Uninitialized);
1004
1005                                 var field = storey.PC.Spec;
1006                                 if (storey.MemberName.IsGeneric) {
1007                                         field = MemberCache.GetMember (Storey.Instance.Type, field);
1008                                 }
1009
1010                                 ec.Emit (OpCodes.Stfld, field);
1011                         }
1012                 }
1013
1014                 public void EmitDispose (EmitContext ec)
1015                 {
1016                         if (resume_points == null)
1017                                 return;
1018
1019                         Label end = ec.DefineLabel ();
1020
1021                         Label[] labels = null;
1022                         for (int i = 0; i < resume_points.Count; ++i) {
1023                                 ResumableStatement s = resume_points[i];
1024                                 Label ret = s.PrepareForDispose (ec, end);
1025                                 if (ret.Equals (end) && labels == null)
1026                                         continue;
1027                                 if (labels == null) {
1028                                         labels = new Label[resume_points.Count + 1];
1029                                         for (int j = 0; j <= i; ++j)
1030                                                 labels[j] = end;
1031                                 }
1032
1033                                 labels[i + 1] = ret;
1034                         }
1035
1036                         if (labels != null) {
1037                                 current_pc = ec.GetTemporaryLocal (ec.BuiltinTypes.UInt);
1038                                 ec.EmitThis ();
1039                                 ec.Emit (OpCodes.Ldfld, storey.PC.Spec);
1040                                 ec.Emit (OpCodes.Stloc, current_pc);
1041                         }
1042
1043                         ec.EmitThis ();
1044                         ec.EmitInt (1);
1045                         ec.Emit (OpCodes.Stfld, ((IteratorStorey) storey).DisposingField.Spec);
1046
1047                         ec.EmitThis ();
1048                         ec.EmitInt ((int) IteratorStorey.State.After);
1049                         ec.Emit (OpCodes.Stfld, storey.PC.Spec);
1050
1051                         if (labels != null) {
1052                                 //SymbolWriter.StartIteratorDispatcher (ec.ig);
1053                                 ec.Emit (OpCodes.Ldloc, current_pc);
1054                                 ec.Emit (OpCodes.Switch, labels);
1055                                 //SymbolWriter.EndIteratorDispatcher (ec.ig);
1056
1057                                 foreach (ResumableStatement s in resume_points)
1058                                         s.EmitForDispose (ec, current_pc, end, true);
1059                         }
1060
1061                         ec.MarkLabel (end);
1062                 }
1063
1064                 public override void EmitStatement (EmitContext ec)
1065                 {
1066                         throw new NotImplementedException ();
1067                 }
1068
1069                 public override void InjectYield (EmitContext ec, Expression expr, int resume_pc, bool unwind_protect, Label resume_point)
1070                 {
1071                         // Store the new value into current
1072                         var fe = new FieldExpr (((IteratorStorey) storey).CurrentField, loc);
1073                         fe.InstanceExpression = new CompilerGeneratedThis (storey.CurrentType, loc);
1074                         fe.EmitAssign (ec, expr, false, false);
1075
1076                         base.InjectYield (ec, expr, resume_pc, unwind_protect, resume_point);
1077
1078                         EmitLeave (ec, unwind_protect);
1079
1080                         ec.MarkLabel (resume_point);
1081                 }
1082
1083                 protected override BlockContext CreateBlockContext (ResolveContext rc)
1084                 {
1085                         var bc = base.CreateBlockContext (rc);
1086                         bc.StartFlowBranching (this, rc.CurrentBranching);
1087                         return bc;
1088                 }
1089
1090                 public static void CreateIterator (IMethodData method, TypeDefinition parent, Modifiers modifiers)
1091                 {
1092                         bool is_enumerable;
1093                         TypeSpec iterator_type;
1094
1095                         TypeSpec ret = method.ReturnType;
1096                         if (ret == null)
1097                                 return;
1098
1099                         if (!CheckType (ret, parent, out iterator_type, out is_enumerable)) {
1100                                 parent.Compiler.Report.Error (1624, method.Location,
1101                                               "The body of `{0}' cannot be an iterator block " +
1102                                               "because `{1}' is not an iterator interface type",
1103                                               method.GetSignatureForError (),
1104                                               TypeManager.CSharpName (ret));
1105                                 return;
1106                         }
1107
1108                         ParametersCompiled parameters = method.ParameterInfo;
1109                         for (int i = 0; i < parameters.Count; i++) {
1110                                 Parameter p = parameters [i];
1111                                 Parameter.Modifier mod = p.ModFlags;
1112                                 if ((mod & Parameter.Modifier.RefOutMask) != 0) {
1113                                         parent.Compiler.Report.Error (1623, p.Location,
1114                                                 "Iterators cannot have ref or out parameters");
1115                                         return;
1116                                 }
1117
1118                                 if (p is ArglistParameter) {
1119                                         parent.Compiler.Report.Error (1636, method.Location,
1120                                                 "__arglist is not allowed in parameter list of iterators");
1121                                         return;
1122                                 }
1123
1124                                 if (parameters.Types [i].IsPointer) {
1125                                         parent.Compiler.Report.Error (1637, p.Location,
1126                                                 "Iterators cannot have unsafe parameters or yield types");
1127                                         return;
1128                                 }
1129                         }
1130
1131                         if ((modifiers & Modifiers.UNSAFE) != 0) {
1132                                 parent.Compiler.Report.Error (1629, method.Location, "Unsafe code may not appear in iterators");
1133                         }
1134
1135                         method.Block = method.Block.ConvertToIterator (method, parent, iterator_type, is_enumerable);
1136                 }
1137
1138                 static bool CheckType (TypeSpec ret, TypeContainer parent, out TypeSpec original_iterator_type, out bool is_enumerable)
1139                 {
1140                         original_iterator_type = null;
1141                         is_enumerable = false;
1142
1143                         if (ret.BuiltinType == BuiltinTypeSpec.Type.IEnumerable) {
1144                                 original_iterator_type = parent.Compiler.BuiltinTypes.Object;
1145                                 is_enumerable = true;
1146                                 return true;
1147                         }
1148                         if (ret.BuiltinType == BuiltinTypeSpec.Type.IEnumerator) {
1149                                 original_iterator_type = parent.Compiler.BuiltinTypes.Object;
1150                                 is_enumerable = false;
1151                                 return true;
1152                         }
1153
1154                         InflatedTypeSpec inflated = ret as InflatedTypeSpec;
1155                         if (inflated == null)
1156                                 return false;
1157
1158                         var member_definition = inflated.MemberDefinition;
1159                         PredefinedType ptype = parent.Module.PredefinedTypes.IEnumerableGeneric;
1160
1161                         if (ptype.Define () && ptype.TypeSpec.MemberDefinition == member_definition) {
1162                                 original_iterator_type = inflated.TypeArguments[0];
1163                                 is_enumerable = true;
1164                                 return true;
1165                         }
1166
1167                         ptype = parent.Module.PredefinedTypes.IEnumeratorGeneric;
1168                         if (ptype.Define () && ptype.TypeSpec.MemberDefinition == member_definition) {
1169                                 original_iterator_type = inflated.TypeArguments[0];
1170                                 is_enumerable = false;
1171                                 return true;
1172                         }
1173
1174                         return false;
1175                 }
1176         }
1177 }
1178