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