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