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