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