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