2008-06-11 Martin Baulig <martin@ximian.com>
[mono.git] / mcs / mcs / iterators.cs
index a8ebfdd844017ed868e18e9264a72f56877521e4..c659678a52c50f3e9585de8066ab5498cda067ba 100644 (file)
@@ -4,7 +4,7 @@
 // Author:
 //   Miguel de Icaza (miguel@ximian.com)
 //
-// (C) 2003 Ximian, Inc.
+// Copyright 2003 Ximian, Inc.
 //
 // TODO:
 //    Flow analysis for Yield.
@@ -21,17 +21,11 @@ using System.Reflection.Emit;
 
 namespace Mono.CSharp {
 
-       public interface IIteratorContainer {
-
-               //
-               // Invoked if a yield statement is found in the body
-               //
-               void SetYields ();
-       }
-       
-       public class Yield : Statement {
+       public class Yield : ResumableStatement {
                Expression expr;
-               ArrayList finally_blocks;
+               bool unwind_protect;
+
+               int resume_pc;
 
                public Yield (Expression expr, Location l)
                {
@@ -39,985 +33,928 @@ namespace Mono.CSharp {
                        loc = l;
                }
 
-               public static bool CheckContext (EmitContext ec, Location loc)
+               public static bool CheckContext (EmitContext ec, Location loc, bool isYieldBreak)
                {
-                       if (ec.InFinally) {
-                               Report.Error (1625, loc, "Cannot yield in the body of a " +
-                                             "finally clause");
-                               return false;
-                       } 
-                       
-                       if (ec.InUnsafe) {
+                       for (Block block = ec.CurrentBlock; block != null; block = block.Parent) {
+                               if (!block.Unsafe)
+                                       continue;
+
                                Report.Error (1629, loc, "Unsafe code may not appear in iterators");
                                return false;
                        }
-                       if (ec.InCatch){
-                               Report.Error (1631, loc, "Cannot yield a value in the body of a catch clause");
-                               return false;
-                       }
 
-                       AnonymousContainer am = ec.CurrentAnonymousMethod;
-                       if ((am != null) && !am.IsIterator){
-                               Report.Error (1621, loc, "The yield statement cannot be used inside anonymous method blocks");
+                       //
+                       // We can't use `ec.InUnsafe' here because it's allowed to have an iterator
+                       // inside an unsafe class.  See test-martin-29.cs for an example.
+                       //
+                       if (!ec.CurrentAnonymousMethod.IsIterator) {
+                               Report.Error (1621, loc,
+                                             "The yield statement cannot be used inside " +
+                                             "anonymous method blocks");
                                return false;
                        }
 
-                       if (ec.CurrentBranching.InTryWithCatch ()) {
-                               Report.Error (1626, loc, "Cannot yield a value in the body of a " +
-                                       "try block with a catch clause");
-                               return false;
-                       }
                        return true;
                }
                
                public override bool Resolve (EmitContext ec)
                {
+                       Report.Debug (64, "RESOLVE YIELD", this, ec, expr, expr.GetType ());
                        expr = expr.Resolve (ec);
                        if (expr == null)
                                return false;
 
-                       if (!CheckContext (ec, loc))
+                       Report.Debug (64, "RESOLVE YIELD #1", this, ec, expr, expr.GetType (),
+                                     ec.CurrentAnonymousMethod, ec.CurrentIterator);
+
+                       if (!CheckContext (ec, loc, false))
                                return false;
 
                        Iterator iterator = ec.CurrentIterator;
-
-                       if (expr.Type != iterator.IteratorType){
+                       if (expr.Type != iterator.IteratorType) {
                                expr = Convert.ImplicitConversionRequired (
                                        ec, expr, iterator.IteratorType, loc);
                                if (expr == null)
                                        return false;
                        }
 
-                       ec.CurrentBranching.StealFinallyClauses (ref finally_blocks);
+                       unwind_protect = ec.CurrentBranching.AddResumePoint (this, loc, out resume_pc);
+
                        return true;
                }
 
                protected override void DoEmit (EmitContext ec)
                {
-                       ec.CurrentIterator.MarkYield (ec, expr, finally_blocks);
+                       ec.CurrentIterator.MarkYield (ec, expr, resume_pc, unwind_protect, resume_point);
                }
-       }
 
-       public class YieldBreak : Statement {
+               protected override void CloneTo (CloneContext clonectx, Statement t)
+               {
+                       Yield target = (Yield) t;
 
+                       target.expr = expr.Clone (clonectx);
+               }
+       }
+
+       public class YieldBreak : ExitStatement {
                public YieldBreak (Location l)
                {
                        loc = l;
                }
 
-               public override bool Resolve (EmitContext ec)
+               public override void Error_FinallyClause ()
                {
-                       if (!Yield.CheckContext (ec, loc))
-                               return false;
+                       Report.Error (1625, loc, "Cannot yield in the body of a finally clause");
+               }
 
-                       ec.CurrentBranching.CurrentUsageVector.Goto ();
-                       return true;
+               protected override bool DoResolve (EmitContext ec)
+               {
+                       return Yield.CheckContext (ec, loc, true);
                }
 
                protected override void DoEmit (EmitContext ec)
                {
-                       ec.CurrentIterator.EmitYieldBreak (ec.ig);
+                       ec.CurrentIterator.EmitYieldBreak (ec.ig, unwind_protect);
                }
        }
 
-       public class Iterator : Class {
-               protected ToplevelBlock original_block;
-               protected ToplevelBlock block;
+       public class IteratorHost : RootScopeInfo
+       {
+               public readonly Iterator Iterator;
 
-               Type iterator_type;
                TypeExpr iterator_type_expr;
-               bool is_enumerable;
-               public readonly bool IsStatic;
-
-               //
-               // The state as we generate the iterator
-               //
-               Label move_next_ok, move_next_error;
-               ArrayList resume_points = new ArrayList ();
-               int pc;
+               Field pc_field;
+               Field current_field;
+               MethodInfo dispose_method;
+
+               TypeExpr enumerator_type;
+               TypeExpr enumerable_type;
+               TypeArguments generic_args;
+               TypeExpr generic_enumerator_type;
+#if GMCS_SOURCE                
+               TypeExpr generic_enumerable_type;
+#endif
                
-               //
-               // Context from the original method
-               //
-               TypeContainer container;
-               Type this_type;
-               InternalParameters parameters;
-               IMethodData orig_method;
-
-               MoveNextMethod move_next_method;
-               Constructor ctor;
-               CaptureContext cc;
-
-               protected enum State {
-                       Uninitialized   = -2,
-                       After,
-                       Running
-               }
-
-               static int proxy_count;
-
-               public void EmitYieldBreak (ILGenerator ig)
+               public IteratorHost (Iterator iterator)
+                       : base (iterator.Container.Toplevel, iterator.Host, iterator.GenericMethod,
+                               iterator.Location)
                {
-                       ig.Emit (OpCodes.Ldarg_0);
-                       IntConstant.EmitInt (ig, (int) State.After);
-                       ig.Emit (OpCodes.Stfld, pc_field.FieldBuilder);
-                       ig.Emit (OpCodes.Br, move_next_error);
+                       this.Iterator = iterator;
                }
 
-               public void EmitMoveNext (EmitContext ec)
-               {
-                       ILGenerator ig = ec.ig;
-
-                       move_next_ok = ig.DefineLabel ();
-                       move_next_error = ig.DefineLabel ();
-
-                       LocalBuilder retval = ec.GetTemporaryLocal (TypeManager.int32_type);
+               public override bool IsIterator {
+                       get { return true; }
+               }
 
-                       ig.BeginExceptionBlock ();
+               public MethodInfo Dispose {
+                       get { return dispose_method; }
+               }
 
-                       Label dispatcher = ig.DefineLabel ();
-                       ig.Emit (OpCodes.Br, dispatcher);
+               public Field PC {
+                       get { return pc_field; }
+               }
 
-                       ResumePoint entry_point = new ResumePoint (null);
-                       resume_points.Add (entry_point);
-                       entry_point.Define (ig);
+               public Field CurrentField {
+                       get { return current_field; }
+               }
 
-                       ec.EmitTopBlock (orig_method, original_block, parameters);
+               public Type IteratorType {
+                       get { return iterator_type_expr.Type; }
+               }
 
-                       EmitYieldBreak (ig);
+               public override TypeExpr [] GetClassBases (out TypeExpr base_class)
+               {
+                       iterator_type_expr = InflateType (Iterator.OriginalIteratorType);
 
-                       ig.MarkLabel (dispatcher);
+#if GMCS_SOURCE
+                       generic_args = new TypeArguments (Location);
+                       generic_args.Add (iterator_type_expr);
+#endif
 
-                       Label [] labels = new Label [resume_points.Count];
-                       for (int i = 0; i < labels.Length; i++)
-                               labels [i] = ((ResumePoint) resume_points [i]).Label;
+                       ArrayList list = new ArrayList ();
+                       if (Iterator.IsEnumerable) {
+                               enumerable_type = new TypeExpression (
+                                       TypeManager.ienumerable_type, Location);
+                               list.Add (enumerable_type);
+
+#if GMCS_SOURCE
+                               generic_enumerable_type = new ConstructedType (
+                                       TypeManager.generic_ienumerable_type,
+                                       generic_args, Location);
+                               list.Add (generic_enumerable_type);
+#endif
+                       }
 
-                       ig.Emit (OpCodes.Ldarg_0);
-                       ig.Emit (OpCodes.Ldfld, pc_field.FieldBuilder);
-                       ig.Emit (OpCodes.Switch, labels);
+                       enumerator_type = new TypeExpression (
+                               TypeManager.ienumerator_type, Location);
+                       list.Add (enumerator_type);
 
-                       Label end = ig.DefineLabel ();
+                       list.Add (new TypeExpression (TypeManager.idisposable_type, Location));
 
-                       ig.MarkLabel (move_next_error);
-                       ig.Emit (OpCodes.Ldc_I4_0); 
-                       ig.Emit (OpCodes.Stloc, retval);
-                       ig.Emit (OpCodes.Leave, end);
+#if GMCS_SOURCE
+                       generic_enumerator_type = new ConstructedType (
+                               TypeManager.generic_ienumerator_type,
+                               generic_args, Location);
+                       list.Add (generic_enumerator_type);
+#endif
 
-                       ig.MarkLabel (move_next_ok);
-                       ig.Emit (OpCodes.Ldc_I4_1);
-                       ig.Emit (OpCodes.Stloc, retval);
-                       ig.Emit (OpCodes.Leave, end);
+                       type_bases = list;
 
-                       ig.BeginFaultBlock ();
+                       return base.GetClassBases (out base_class);
+               }
 
-                       ig.Emit (OpCodes.Ldarg_0);
-                       ig.Emit (OpCodes.Callvirt, dispose.MethodBuilder);
+               protected override bool DoResolveMembers ()
+               {
+                       pc_field = CaptureVariable ("$PC", TypeManager.system_int32_expr);
+                       current_field = CaptureVariable ("$current", iterator_type_expr);
+
+#if GMCS_SOURCE
+                       Define_Current (true);
+#endif
+                       Define_Current (false);
+                       new DisposeMethod (this);
+                       Define_Reset ();
 
-                       ig.EndExceptionBlock ();
+                       if (Iterator.IsEnumerable) {
+                               new GetEnumeratorMethod (this, false);
+#if GMCS_SOURCE
+                               new GetEnumeratorMethod (this, true);
+#endif
+                       }
 
-                       ig.MarkLabel (end);
-                       ig.Emit (OpCodes.Ldloc, retval);
-                       ig.Emit (OpCodes.Ret);
+                       return base.DoResolveMembers ();
                }
 
-               public void EmitDispose (EmitContext ec)
+               public void CaptureScopes ()
                {
-                       ILGenerator ig = ec.ig;
-
-                       Label end = ig.DefineLabel ();
-                       Label dispatcher = ig.DefineLabel ();
-                       ig.Emit (OpCodes.Br, dispatcher);
+                       Report.Debug (128, "DEFINE ITERATOR HOST", this, scopes);
+
+                       foreach (ScopeInfo si in scopes)
+                               CaptureScope (si);
+
+                       foreach (ScopeInfo si in scopes) {
+                               if (!si.Define ())
+                                       throw new InternalErrorException ();
+                               if (si.DefineType () == null)
+                                       throw new InternalErrorException ();
+                               if (!si.ResolveType ())
+                                       throw new InternalErrorException ();
+                               if (!si.ResolveMembers ())
+                                       throw new InternalErrorException ();
+                               if (!si.DefineMembers ())
+                                       throw new InternalErrorException ();
+                       }
+               }
 
-                       Label [] labels = new Label [resume_points.Count];
-                       for (int i = 0; i < labels.Length; i++) {
-                               ResumePoint point = (ResumePoint) resume_points [i];
+               protected override bool DoDefineMembers ()
+               {
+                       if (!base.DoDefineMembers ())
+                               return false;
 
-                               if (point.FinallyBlocks == null) {
-                                       labels [i] = end;
-                                       continue;
-                               }
+                       FetchMethodDispose ();
 
-                               labels [i] = ig.DefineLabel ();
-                               ig.MarkLabel (labels [i]);
+                       return true;
+               }
 
-                               ig.BeginExceptionBlock ();
-                               ig.BeginFinallyBlock ();
+               protected override void EmitScopeConstructor (EmitContext ec)
+               {
+                       ec.ig.Emit (OpCodes.Ldarg_0);
+                       ec.ig.Emit (OpCodes.Ldarg_1);
+                       ec.ig.Emit (OpCodes.Stfld, pc_field.FieldBuilder);
+                       base.EmitScopeConstructor (ec);
+               }
 
-                               foreach (ExceptionStatement stmt in point.FinallyBlocks) {
-                                       if (stmt != null)
-                                               stmt.EmitFinally (ec);
-                               }
+               void FetchMethodDispose ()
+               {
+                       MemberList dispose_list;
 
-                               ig.EndExceptionBlock ();
-                               ig.Emit (OpCodes.Br, end);
-                       }
-                       
-                       ig.MarkLabel (dispatcher);
-                       ig.Emit (OpCodes.Ldarg_0);
-                       ig.Emit (OpCodes.Ldfld, pc_field.FieldBuilder);
-                       ig.Emit (OpCodes.Switch, labels);
+                       dispose_list = FindMembers (
+                               CurrentType != null ? CurrentType : TypeBuilder,
+                               MemberTypes.Method, BindingFlags.Public | BindingFlags.Instance,
+                               Type.FilterName, "Dispose");
 
-                       ig.Emit (OpCodes.Ldarg_0);
-                       IntConstant.EmitInt (ig, (int) State.After);
-                       ig.Emit (OpCodes.Stfld, pc_field.FieldBuilder);
+                       if (dispose_list.Count != 1)
+                               throw new InternalErrorException ("Cannot find Dipose() method.");
 
-                       ig.MarkLabel (end);
+                       dispose_method = (MethodInfo) dispose_list [0];
                }
 
-               protected class ResumePoint
+               void Define_Current (bool is_generic)
                {
-                       public Label Label;
-                       public readonly ExceptionStatement[] FinallyBlocks;
-
-                       public ResumePoint (ArrayList list)
-                       {
-                               if (list != null) {
-                                       FinallyBlocks = new ExceptionStatement [list.Count];
-                                       list.CopyTo (FinallyBlocks, 0);
-                               }
+                       MemberName left;
+                       TypeExpr type;
+
+                       if (is_generic) {
+                               left = new MemberName (
+                                       "System.Collections.Generic.IEnumerator",
+                                       generic_args, Location);
+                               type = iterator_type_expr;
+                       } else {
+                               left = new MemberName ("System.Collections.IEnumerator", Location);
+                               type = TypeManager.system_object_expr;
                        }
 
-                       public void Define (ILGenerator ig)
-                       {
-                               Label = ig.DefineLabel ();
-                               ig.MarkLabel (Label);
-                       }
-               }
+                       MemberName name = new MemberName (left, "Current", null, Location);
 
-               //
-               // Called back from Yield
-               //
-               public void MarkYield (EmitContext ec, Expression expr,
-                                      ArrayList finally_blocks)
-               {
-                       ILGenerator ig = ec.ig;
+                       ToplevelBlock get_block = new ToplevelBlock (Location);
+                       get_block.AddStatement (new CurrentBlock (this, is_generic));
 
-                       // Store the new current
-                       ig.Emit (OpCodes.Ldarg_0);
-                       expr.Emit (ec);
-                       ig.Emit (OpCodes.Stfld, current_field.FieldBuilder);
+                       Accessor getter = new Accessor (get_block, 0, null, Location);
 
-                       // increment pc
-                       pc++;
-                       ig.Emit (OpCodes.Ldarg_0);
-                       IntConstant.EmitInt (ig, pc);
-                       ig.Emit (OpCodes.Stfld, pc_field.FieldBuilder);
+                       Property current = new Property (
+                               this, type, 0, false, name, null, getter, null, false);
+                       AddProperty (current);
+               }
 
-                       // Return ok
-                       ig.Emit (OpCodes.Br, move_next_ok);
+               void Define_Reset ()
+               {
+                       Method reset = new Method (
+                               this, null, TypeManager.system_void_expr, Modifiers.PUBLIC,
+                               false, new MemberName ("Reset", Location),
+                               Parameters.EmptyReadOnlyParameters, null);
+                       AddMethod (reset);
 
-                       ResumePoint point = new ResumePoint (finally_blocks);
-                       resume_points.Add (point);
-                       point.Define (ig);
+                       reset.Block = new ToplevelBlock (Location);
+                       reset.Block.AddStatement (Create_ThrowNotSupported ());
                }
 
-               public void MarkFinally (EmitContext ec, ArrayList finally_blocks)
+               Statement Create_ThrowNotSupported ()
                {
-                       ILGenerator ig = ec.ig;
+                       TypeExpr ex_type = new TypeLookupExpression ("System.NotSupportedException");
 
-                       // increment pc
-                       pc++;
-                       ig.Emit (OpCodes.Ldarg_0);
-                       IntConstant.EmitInt (ig, pc);
-                       ig.Emit (OpCodes.Stfld, pc_field.FieldBuilder);
-
-                       ResumePoint point = new ResumePoint (finally_blocks);
-                       resume_points.Add (point);
-                       point.Define (ig);
+                       return new Throw (new New (ex_type, null, Location), Location);
                }
 
-               private static MemberName MakeProxyName (string name, Location loc)
+               protected override ScopeInitializer CreateScopeInitializer ()
                {
-                       int pos = name.LastIndexOf ('.');
-                       if (pos > 0)
-                               name = name.Substring (pos + 1);
-
-                       return new MemberName ("<" + name + ">__" + (proxy_count++), loc);
+                       return new IteratorHostInitializer (this);
                }
 
-               //
-               // Our constructor
-               //
-               public Iterator (IMethodData m_container, TypeContainer container,
-                                InternalParameters parameters,
-                                int modifiers)
-                       : base (container.NamespaceEntry, container, MakeProxyName (m_container.MethodName.Name, m_container.Location),
-                               (modifiers & Modifiers.UNSAFE) | Modifiers.PRIVATE, null)
+               protected class IteratorHostInitializer : RootScopeInitializer
                {
-                       this.orig_method = m_container;
+                       new public readonly IteratorHost Host;
+                       protected Iterator.State state;
 
-                       this.container = container;
-                       this.parameters = parameters;
-                       this.original_block = orig_method.Block;
-                       this.block = new ToplevelBlock (orig_method.Block, parameters.Parameters, orig_method.Location);
+                       public IteratorHostInitializer (IteratorHost host)
+                               : base (host)
+                       {
+                               this.Host = host;
+                       }
 
-                       IsStatic = (modifiers & Modifiers.STATIC) != 0;
-               }
+                       protected override bool DoResolveInternal (EmitContext ec)
+                       {
+                               if (this is EnumeratorScopeInitializer)
+                                       state = Iterator.State.Start;
+                               else if (Host.Iterator.IsEnumerable)
+                                       state = Iterator.State.Uninitialized;
+                               else
+                                       state = Iterator.State.Start;
 
-               public AnonymousContainer Host {
-                       get { return move_next_method; }
-               }
+                               return base.DoResolveInternal (ec);
+                       }
 
-               public bool DefineIterator ()
-               {
-                       ec = new EmitContext (this, Mono.CSharp.Location.Null, null, null, ModFlags);
-                       ec.CurrentAnonymousMethod = move_next_method;
-                       ec.CurrentIterator = this;
-                       ec.InIterator = true;
-
-                       if (!CheckType ()) {
-                               Report.Error (1624, Location,
-                                       "The body of `{0}' cannot be an iterator block because `{1}' is not an iterator interface type",
-                                       orig_method.GetSignatureForError (), TypeManager.CSharpName (orig_method.ReturnType));
-                               return false;
+                       protected override void EmitScopeConstructor (EmitContext ec)
+                       {
+                               ec.ig.Emit (OpCodes.Ldc_I4, (int) state);
+                               base.EmitScopeConstructor (ec);
                        }
+               }
 
-                       for (int i = 0; i < parameters.Count; i++){
-                               Parameter.Modifier mod = parameters.ParameterModifier (i);
-                               if ((mod & (Parameter.Modifier.REF | Parameter.Modifier.OUT)) != 0){
-                                       Report.Error (
-                                               1623, Location,
-                                               "Iterators cannot have ref or out parameters");
-                                       return false;
-                               }
+               protected class GetEnumeratorMethod : Method
+               {
+                       public IteratorHost Host;
 
-                               if ((mod & Parameter.Modifier.ARGLIST) != 0) {
-                                       Report.Error (1636, Location, "__arglist is not allowed in parameter list of iterators");
-                                       return false;
+                       static MemberName GetMemberName (IteratorHost host, bool is_generic)
+                       {
+                               MemberName left;
+                               if (is_generic) {
+                                       left = new MemberName (
+                                               "System.Collections.Generic.IEnumerable",
+                                               host.generic_args, host.Location);
+                               } else {
+                                       left = new MemberName (
+                                               "System.Collections.IEnumerable", host.Location);
                                }
 
-                               if (parameters.ParameterType (i).IsPointer) {
-                                       Report.Error (1637, Location, "Iterators cannot have unsafe parameters or yield types");
-                                       return false;
-                               }
+                               return new MemberName (left, "GetEnumerator", host.Location);
                        }
 
-                       this_type = container.TypeBuilder;
+                       public GetEnumeratorMethod (IteratorHost host, bool is_generic)
+                               : base (host, null, is_generic ?
+                                       host.generic_enumerator_type : host.enumerator_type,
+                                       0, false, GetMemberName (host, is_generic),
+                                       Parameters.EmptyReadOnlyParameters, null)
+                       {
+                               this.Host = host;
 
-                       ArrayList list = new ArrayList ();
-                       if (is_enumerable)
-                               list.Add (new TypeExpression (
-                                                 TypeManager.ienumerable_type, Location));
-                       list.Add (new TypeExpression (TypeManager.ienumerator_type, Location));
-                       list.Add (new TypeExpression (TypeManager.idisposable_type, Location));
+                               host.AddMethod (this);
 
-                       iterator_type_expr = new TypeExpression (iterator_type, Location);
+                               Block = new ToplevelBlock (host.Iterator.Container.Toplevel, null, Location);
+                               Block.AddStatement (new GetEnumeratorStatement (host, type_name));
+                       }
 
-                       container.AddIterator (this);
+                       public override EmitContext CreateEmitContext (DeclSpace tc, ILGenerator ig)
+                       {
+                               EmitContext ec = new EmitContext (
+                                       this, tc, this.ds, Location, ig, MemberType, ModFlags, false);
 
-                       Bases = list;
-                       orig_method.Block = block;
-                       return true;
-               }
+                               ec.CurrentAnonymousMethod = Host.Iterator;
+                               return ec;
+                       }
 
-               protected override bool DoDefineMembers ()
-               {
-                       ec.InIterator = true;
-                       ec.CurrentIterator = this;
-                       ec.CurrentAnonymousMethod = move_next_method;
-                       ec.capture_context = cc;
+                       public override void EmitExtraSymbolInfo (SourceMethod source)
+                       {
+                               source.SetCompilerGenerated ();
+                       }
 
-                       if (!base.DoDefineMembers ())
-                               return false;
+                       protected class GetEnumeratorStatement : Statement
+                       {
+                               IteratorHost host;
+                               Expression type;
+
+                               ExpressionStatement initializer;
+                               Expression cast;
+                               MethodInfo ce;
+
+                               public GetEnumeratorStatement (IteratorHost host, Expression type)
+                               {
+                                       this.host = host;
+                                       this.type = type;
+                                       loc = host.Location;
+                               }
 
-                       return true;
-               }
+                               public override bool Resolve (EmitContext ec)
+                               {
+                                       type = type.ResolveAsTypeTerminal (ec, false);
+                                       if ((type == null) || (type.Type == null))
+                                               return false;
 
-               public override bool Define ()
-               {
-                       if (!base.Define ())
-                               return false;
+                                       initializer = host.GetEnumeratorInitializer (ec);
+                                       if (initializer == null)
+                                               return false;
 
-                       ec.InIterator = true;
-                       ec.CurrentIterator = this;
-                       ec.CurrentAnonymousMethod = move_next_method;
-                       ec.capture_context = cc;
-                       ec.TypeContainer = ec.TypeContainer.Parent;
+                                       cast = new ClassCast (initializer, type.Type);
 
-                       ec.ContainerType = ec.TypeContainer.TypeBuilder;
+                                       if (TypeManager.int_interlocked_compare_exchange == null) {
+                                               Type t = TypeManager.CoreLookupType ("System.Threading", "Interlocked", Kind.Class, true);
+                                               if (t != null) {
+                                                       TypeManager.int_interlocked_compare_exchange = TypeManager.GetPredefinedMethod (
+                                                               t, "CompareExchange", loc, TypeManager.GetReferenceType (TypeManager.int32_type),
+                                                               TypeManager.int32_type, TypeManager.int32_type);
+                                               }
+                                       }
 
-                       ec.ig = move_next_method.method.MethodBuilder.GetILGenerator ();
+                                       ce = TypeManager.int_interlocked_compare_exchange;
 
-                       if (!ctor.Define ())
-                               return false;
+                                       ec.CurrentBranching.CurrentUsageVector.Goto ();
+                                       return true;
+                               }
 
-                       bool unreachable;
+                               protected override void DoEmit (EmitContext ec)
+                               {
+                                       ILGenerator ig = ec.ig;
+                                       Label label_init = ig.DefineLabel ();
 
-                       if (!ec.ResolveTopBlock (null, original_block, parameters, orig_method, out unreachable))
-                               return false;
+                                       ig.Emit (OpCodes.Ldarg_0);
+                                       ig.Emit (OpCodes.Ldflda, host.PC.FieldBuilder);
+                                       ig.Emit (OpCodes.Ldc_I4, (int) Iterator.State.Start);
+                                       ig.Emit (OpCodes.Ldc_I4, (int) Iterator.State.Uninitialized);
+                                       ig.Emit (OpCodes.Call, ce);
 
-                       if (!ec.ResolveTopBlock (null, block, parameters, orig_method, out unreachable))
-                               return false;
+                                       ig.Emit (OpCodes.Ldc_I4, (int) Iterator.State.Uninitialized);
+                                       ig.Emit (OpCodes.Bne_Un, label_init);
 
-                       original_block.CompleteContexts ();
+                                       ig.Emit (OpCodes.Ldarg_0);
+                                       ig.Emit (OpCodes.Ret);
 
-                       cc.EmitAnonymousHelperClasses (ec);
+                                       ig.MarkLabel (label_init);
 
-                       return true;
+                                       initializer.EmitStatement (ec);
+                                       cast.Emit (ec);
+                                       ig.Emit (OpCodes.Ret);
+                               }
+                       }
                }
 
-               //
-               // Returns the new block for the method, or null on failure
-               //
-               protected override bool DefineNestedTypes ()
+               protected class DisposeMethod : Method
                {
-                       Define_Fields ();
-                       Define_Current ();
-                       Define_MoveNext ();
-                       Define_Reset ();
-                       Define_Dispose ();
-
-                       Create_Block ();
-
-                       Define_Constructor ();
+                       public IteratorHost Host;
 
-                       if (is_enumerable)
-                               Define_GetEnumerator ();
+                       public DisposeMethod (IteratorHost host)
+                               : base (host, null, TypeManager.system_void_expr, Modifiers.PUBLIC,
+                                       false, new MemberName ("Dispose", host.Location),
+                                       Parameters.EmptyReadOnlyParameters, null)
+                       {
+                               this.Host = host;
 
-                       return base.DefineNestedTypes ();
-               }
+                               host.AddMethod (this);
 
-               Field pc_field;
-               Field current_field;
-               Method dispose;
+                               Block = new ToplevelBlock (host.Iterator.Block, null, Location);
+                               Block.AddStatement (new DisposeMethodStatement (Host.Iterator));
 
-               void Create_Block ()
-               {
-                       original_block.SetHaveAnonymousMethods (Location, move_next_method);
-                       block.SetHaveAnonymousMethods (Location, move_next_method);
+                               Report.Debug (64, "DISPOSE METHOD", host, Block);
+                       }
 
-                       cc = original_block.CaptureContext;
+                       public override EmitContext CreateEmitContext (DeclSpace tc, ILGenerator ig)
+                       {
+                               EmitContext ec = new EmitContext (
+                                       this, tc, this.ds, Location, ig, MemberType, ModFlags, false);
 
-                       int first = IsStatic ? 0 : 1;
+                               ec.CurrentAnonymousMethod = Host.Iterator;
+                               return ec;
+                       }
 
-                       ArrayList args = new ArrayList ();
-                       if (!IsStatic) {
-                               Type t = container.TypeBuilder;
-                               args.Add (new Argument (
-                                       new ThisParameterReference (t, Location)));
-                               cc.CaptureThis ();
+                       public override void EmitExtraSymbolInfo (SourceMethod source)
+                       {
+                               source.SetCompilerGenerated ();
                        }
 
-                       args.Add (new Argument (new BoolLiteral (false)));
+                       protected class DisposeMethodStatement : Statement
+                       {
+                               Iterator iterator;
 
-                       for (int i = 0; i < parameters.Count; i++) {
-                               Type t = parameters.ParameterType (i);
-                               string name = parameters.ParameterName (i);
+                               public DisposeMethodStatement (Iterator iterator)
+                               {
+                                       this.iterator = iterator;
+                                       this.loc = iterator.Location;
+                               }
 
-                               args.Add (new Argument (
-                                       new SimpleParameterReference (t, first + i, Location)));
+                               public override bool Resolve (EmitContext ec)
+                               {
+                                       return true;
+                               }
 
-                               cc.AddParameterToContext (move_next_method, name, t, first + i);
+                               protected override void DoEmit (EmitContext ec)
+                               {
+                                       iterator.EmitDispose (ec);
+                               }
                        }
-
-                       Expression new_expr = new New (
-                               new TypeExpression (TypeBuilder, Location), args, Location);
-
-                       block.AddStatement (new NoCheckReturn (new_expr, Location));
                }
 
-               void Define_Fields ()
+               protected ScopeInitializer GetEnumeratorInitializer (EmitContext ec)
                {
-                       pc_field = new Field (
-                               this, TypeManager.system_int32_expr, Modifiers.PRIVATE, "$PC",
-                               null, null, Location);
-                       AddField (pc_field);
-
-                       current_field = new Field (
-                               this, iterator_type_expr, Modifiers.PRIVATE, "$current",
-                               null, null, Location);
-                       AddField (current_field);
+                       ScopeInitializer init = new EnumeratorScopeInitializer (this);
+                       if (init.Resolve (ec) == null)
+                               throw new InternalErrorException ();
+                       return init;
                }
 
-               void Define_Constructor ()
+               protected class EnumeratorScopeInitializer : IteratorHostInitializer
                {
-                       Parameters ctor_params;
-
-                       ArrayList list = new ArrayList ();
+                       IteratorHost host;
 
-                       if (!IsStatic)
-                               list.Add (new Parameter (
-                                       new TypeExpression (container.TypeBuilder, Location),
-                                       "this", Parameter.Modifier.NONE,
-                                       null, Location));
-                       list.Add (new Parameter (
-                               TypeManager.system_boolean_expr, "initialized",
-                               Parameter.Modifier.NONE, null, Location));
+                       public EnumeratorScopeInitializer (IteratorHost host)
+                               : base (host)
+                       {
+                               this.host = host;
+                       }
 
-                       Parameter[] old_fixed = parameters.Parameters.FixedParameters;
-                       if (old_fixed != null)
-                               list.AddRange (old_fixed);
+                       protected override bool DoResolveInternal (EmitContext ec)
+                       {
+                               type = host.IsGeneric ? host.CurrentType : host.TypeBuilder;
+                               return base.DoResolveInternal (ec);
+                       }
 
-                       Parameter[] fixed_params = new Parameter [list.Count];
-                       list.CopyTo (fixed_params);
+                       protected override void DoEmit (EmitContext ec)
+                       {
+                               DoEmitInstance (ec);
+                       }
 
-                       ctor_params = new Parameters (
-                               fixed_params, parameters.Parameters.ArrayParameter);
+                       protected override bool IsGetEnumerator {
+                               get { return true; }
+                       }
 
-                       ctor = new Constructor (
-                               this, Name, Modifiers.PUBLIC, ctor_params,
-                               new ConstructorBaseInitializer (null, Location),
-                               Location);
-                       AddConstructor (ctor);
+                       protected override void EmitParameterReference (EmitContext ec,
+                                                                       CapturedParameter cp)
+                       {
+                               ec.ig.Emit (OpCodes.Ldarg_0);
+                               ec.ig.Emit (OpCodes.Ldfld, cp.Field.FieldBuilder);
+                       }
+               }
 
-                       ctor.Block = new ToplevelBlock (block, parameters.Parameters, Location);
+               protected class CurrentBlock : Statement {
+                       IteratorHost host;
+                       bool is_generic;
 
-                       int first = IsStatic ? 2 : 3;
+                       public CurrentBlock (IteratorHost host, bool is_generic)
+                       {
+                               this.host = host;
+                               this.is_generic = is_generic;
+                               loc = host.Location;
+                       }
 
-                       State initial = is_enumerable ? State.Uninitialized : State.Running;
-                       ctor.Block.AddStatement (new SetState (this, initial, Location));
+                       public override bool Resolve (EmitContext ec)
+                       {
+                               // We emit a 'ret', so prevent the enclosing TopLevelBlock from emitting one too
+                               ec.CurrentBranching.CurrentUsageVector.Goto ();
+                               return true;
+                       }
 
-                       ctor.Block.AddStatement (new If (
-                               new SimpleParameterReference (
-                                       TypeManager.bool_type, first - 1, Location),
-                               new SetState (this, State.Running, Location),
-                               Location));
+                       protected override void DoEmit (EmitContext ec)
+                       {
+                               ILGenerator ig = ec.ig;
 
-                       ctor.Block.AddStatement (new InitScope (this, Location));
+                               ig.Emit (OpCodes.Ldarg_0);
+                               ig.Emit (OpCodes.Ldfld, host.CurrentField.FieldBuilder);
+                               if (!is_generic)
+                                       ig.Emit (OpCodes.Box, host.CurrentField.MemberType);
+                               ig.Emit (OpCodes.Ret);
+                       }
                }
+       }
 
-               Statement Create_ThrowInvalidOperation ()
-               {
-                       TypeExpr ex_type = new TypeExpression (
-                               TypeManager.invalid_operation_exception_type, Location);
+       public class Iterator : AnonymousContainer {
+               protected readonly ToplevelBlock OriginalBlock;
+               protected readonly IMethodData OriginalMethod;
+               protected ToplevelBlock block;
 
-                       return new Throw (new New (ex_type, null, Location), Location);
-               }
+               public readonly bool IsEnumerable;
+               public readonly bool IsStatic;
 
-               Statement Create_ThrowNotSupported ()
-               {
-                       TypeExpr ex_type = new TypeExpression (
-                               TypeManager.not_supported_exception_type, Location);
+               //
+               // The state as we generate the iterator
+               //
+               Label move_next_ok, move_next_error;
+               LocalBuilder skip_finally, current_pc;
 
-                       return new Throw (new New (ex_type, null, Location), Location);
+               public LocalBuilder SkipFinally {
+                       get { return skip_finally; }
                }
 
-               void Define_Current ()
-               {
-                       ToplevelBlock get_block = new ToplevelBlock (
-                               block, parameters.Parameters, Location);
-                       MemberName left = new MemberName ("System.Collections.IEnumerator");
-                       MemberName name = new MemberName (left, "Current", Location);
-
-                       get_block.AddStatement (new If (
-                               new Binary (
-                                       Binary.Operator.LessThanOrEqual,
-                                       new FieldExpression (this, pc_field),
-                                       new IntLiteral ((int) State.Running)),
-                               Create_ThrowInvalidOperation (),
-                               new Return (
-                                       new FieldExpression (this, current_field), Location),
-                               Location));
+               public LocalBuilder CurrentPC {
+                       get { return current_pc; }
+               }
 
-                       Accessor getter = new Accessor (get_block, 0, null, Location);
+               public readonly Type OriginalIteratorType;
+               public readonly IteratorHost IteratorHost;
 
-                       Property current = new Property (
-                               this, iterator_type_expr, 0,
-                               false, name, null, getter, null);
-                       AddProperty (current);
+               public enum State {
+                       Running = -3, // Used only in CurrentPC, never stored into $PC
+                       Uninitialized = -2,
+                       After = -1,
+                       Start = 0
                }
 
-               void Define_MoveNext ()
+               public void EmitYieldBreak (ILGenerator ig, bool unwind_protect)
                {
-                       move_next_method = new MoveNextMethod (this, Location);
-
-                       original_block.ReParent (block, move_next_method);
-
-                       move_next_method.CreateMethod (ec);
-
-                       AddMethod (move_next_method.method);
+                       ig.Emit (unwind_protect ? OpCodes.Leave : OpCodes.Br, move_next_error);
                }
 
-               void Define_GetEnumerator ()
+               void EmitMoveNext_NoResumePoints (EmitContext ec, Block original_block)
                {
-                       MemberName left = new MemberName ("System.Collections.IEnumerable");
+                       ILGenerator ig = ec.ig;
 
-                       MemberName name = new MemberName (left, "GetEnumerator", Location);
+                       ig.Emit (OpCodes.Ldarg_0);
+                       ig.Emit (OpCodes.Ldfld, IteratorHost.PC.FieldBuilder);
 
-                       Method get_enumerator = new Method (
-                               this,
-                               new TypeExpression (TypeManager.ienumerator_type, Location),
-                               0, false, name,
-                               Parameters.EmptyReadOnlyParameters, null);
-                       AddMethod (get_enumerator);
-
-                       get_enumerator.Block = new ToplevelBlock (
-                               block, parameters.Parameters, Location);
-
-                       get_enumerator.Block.SetHaveAnonymousMethods (Location, move_next_method);
-
-                       Expression ce = new MemberAccess (
-                               new SimpleName ("System.Threading.Interlocked", Location),
-                               "CompareExchange", Location);
-
-                       Expression pc = new FieldExpression (this, pc_field);
-                       Expression before = new IntLiteral ((int) State.Running);
-                       Expression uninitialized = new IntLiteral ((int) State.Uninitialized);
-
-                       ArrayList args = new ArrayList ();
-                       args.Add (new Argument (pc, Argument.AType.Ref));
-                       args.Add (new Argument (before, Argument.AType.Expression));
-                       args.Add (new Argument (uninitialized, Argument.AType.Expression));
-
-                       get_enumerator.Block.AddStatement (new If (
-                               new Binary (
-                                       Binary.Operator.Equality,
-                                       new Invocation (ce, args),
-                                       uninitialized),
-                               new Return (new ThisParameterReference (
-                                                   TypeManager.ienumerator_type, Location),
-                                           Location),
-                               Location));
-
-                       args = new ArrayList ();
-                       if (!IsStatic) {
-                               args.Add (new Argument (new CapturedThisReference (this, Location)));
-                       }
+                       ig.Emit (OpCodes.Ldarg_0);
+                       IntConstant.EmitInt (ig, (int) State.After);
+                       ig.Emit (OpCodes.Stfld, IteratorHost.PC.FieldBuilder);
 
-                       args.Add (new Argument (new BoolLiteral (true)));
+                       // We only care if the PC is zero (start executing) or non-zero (don't do anything)
+                       ig.Emit (OpCodes.Brtrue, move_next_error);
 
-                       for (int i = 0; i < parameters.Count; i++) {
-                               Expression cp = new CapturedParameterReference (
-                                       this, parameters.ParameterType (i),
-                                       parameters.ParameterName (i), Location);
-                               args.Add (new Argument (cp));
-                       }
+                       SymbolWriter.StartIteratorBody (ec.ig);
+                       original_block.Emit (ec);
+                       SymbolWriter.EndIteratorBody (ec.ig);
 
-                       Expression new_expr = new New (
-                               new TypeExpression (TypeBuilder, Location), args, Location);
-                       get_enumerator.Block.AddStatement (new Return (new_expr, Location));
+                       ig.MarkLabel (move_next_error);
+                       ig.Emit (OpCodes.Ldc_I4_0);
+                       ig.Emit (OpCodes.Ret);
                }
 
-               protected class SimpleParameterReference : Expression
+               internal void EmitMoveNext (EmitContext ec, Block original_block)
                {
-                       int idx;
+                       ILGenerator ig = ec.ig;
 
-                       public SimpleParameterReference (Type type, int idx, Location loc)
-                       {
-                               this.idx = idx;
-                               this.loc = loc;
-                               this.type = type;
-                               eclass = ExprClass.Variable;
-                       }
+                       move_next_ok = ig.DefineLabel ();
+                       move_next_error = ig.DefineLabel ();
 
-                       public override Expression DoResolve (EmitContext ec)
-                       {
-                               return this;
+                       if (resume_points == null) {
+                               EmitMoveNext_NoResumePoints (ec, original_block);
+                               return;
                        }
 
-                       public override void Emit (EmitContext ec)
-                       {
-                               DoEmit (ec);
-                       }
+                       current_pc = ec.GetTemporaryLocal (TypeManager.uint32_type);
+                       ig.Emit (OpCodes.Ldarg_0);
+                       ig.Emit (OpCodes.Ldfld, IteratorHost.PC.FieldBuilder);
+                       ig.Emit (OpCodes.Stloc, current_pc);
 
-                       protected virtual void DoEmit (EmitContext ec)
-                       {
-                               ParameterReference.EmitLdArg (ec.ig, idx);
-                       }
-               }
+                       // We're actually in state 'running', but this is as good a PC value as any if there's an abnormal exit
+                       ig.Emit (OpCodes.Ldarg_0);
+                       IntConstant.EmitInt (ig, (int) State.After);
+                       ig.Emit (OpCodes.Stfld, IteratorHost.PC.FieldBuilder);
 
-               protected class ThisParameterReference : SimpleParameterReference, IMemoryLocation
-               {
-                       public ThisParameterReference (Type type, Location loc)
-                               : base (type, 0, loc)
-                       { }
+                       Label [] labels = new Label [1 + resume_points.Count];
+                       labels [0] = ig.DefineLabel ();
 
-                       protected override void DoEmit (EmitContext ec)
-                       {
-                               base.DoEmit (ec);
-                               if (ec.TypeContainer is Struct)
-                                       ec.ig.Emit (OpCodes.Ldobj, type);
+                       bool need_skip_finally = false;
+                       for (int i = 0; i < resume_points.Count; ++i) {
+                               ResumableStatement s = (ResumableStatement) resume_points [i];
+                               need_skip_finally |= s is ExceptionStatement;
+                               labels [i+1] = s.PrepareForEmit (ec);
                        }
 
-                       public void AddressOf (EmitContext ec, AddressOp mode)
-                       {
-                               if (ec.TypeContainer is Struct)
-                                       ec.ig.Emit (OpCodes.Ldarga, 0);
-                               else
-                                       ec.ig.Emit (OpCodes.Ldarg, 0);
+                       if (need_skip_finally) {
+                               skip_finally = ec.GetTemporaryLocal (TypeManager.bool_type);
+                               ig.Emit (OpCodes.Ldc_I4_0);
+                               ig.Emit (OpCodes.Stloc, skip_finally);
                        }
-               }
 
-               protected class CapturedParameterReference : Expression
-               {
-                       Iterator iterator;
-                       string name;
+                       SymbolWriter.StartIteratorDispatcher (ec.ig);
+                       ig.Emit (OpCodes.Ldloc, current_pc);
+                       ig.Emit (OpCodes.Switch, labels);
 
-                       public CapturedParameterReference (Iterator iterator, Type type,
-                                                          string name, Location loc)
-                       {
-                               this.iterator = iterator;
-                               this.loc = loc;
-                               this.type = type;
-                               this.name = name;
-                               eclass = ExprClass.Variable;
-                       }
+                       ig.Emit (OpCodes.Br, move_next_error);
+                       SymbolWriter.EndIteratorDispatcher (ec.ig);
 
-                       public override Expression DoResolve (EmitContext ec)
-                       {
-                               return this;
-                       }
+                       ig.MarkLabel (labels [0]);
 
-                       public override void Emit (EmitContext ec)
-                       {
-                               ec.CurrentAnonymousMethod = iterator.move_next_method;
+                       SymbolWriter.StartIteratorBody (ec.ig);
+                       original_block.Emit (ec);
+                       SymbolWriter.EndIteratorBody (ec.ig);
 
-                               iterator.cc.EmitParameter (ec, name);
-                       }
-               }
+                       SymbolWriter.StartIteratorDispatcher (ec.ig);
 
-               protected class CapturedThisReference : Expression
-               {
-                       public CapturedThisReference (Iterator iterator, Location loc)
-                       {
-                               this.loc = loc;
-                               this.type = iterator.this_type;
-                               eclass = ExprClass.Variable;
-                       }
+                       ig.Emit (OpCodes.Ldarg_0);
+                       IntConstant.EmitInt (ig, (int) State.After);
+                       ig.Emit (OpCodes.Stfld, IteratorHost.PC.FieldBuilder);
 
-                       public override Expression DoResolve (EmitContext ec)
-                       {
-                               return this;
-                       }
+                       ig.MarkLabel (move_next_error);
+                       ig.Emit (OpCodes.Ldc_I4_0);
+                       ig.Emit (OpCodes.Ret);
 
-                       public override void Emit (EmitContext ec)
-                       {
-                               ec.EmitThis ();
-                       }
+                       ig.MarkLabel (move_next_ok);
+                       ig.Emit (OpCodes.Ldc_I4_1);
+                       ig.Emit (OpCodes.Ret);
+
+                       SymbolWriter.EndIteratorDispatcher (ec.ig);
                }
 
-               protected class FieldExpression : Expression
+               public void EmitDispose (EmitContext ec)
                {
-                       Iterator iterator;
-                       Field field;
+                       ILGenerator ig = ec.ig;
 
-                       public FieldExpression (Iterator iterator, Field field)
-                       {
-                               this.iterator = iterator;
-                               this.field = field;
-                               this.loc = iterator.Location;
-                       }
+                       Label end = ig.DefineLabel ();
 
-                       public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
-                       {
-                               FieldExpr fexpr = new FieldExpr (field.FieldBuilder, loc);
-                               fexpr.InstanceExpression = new ThisParameterReference (
-                                       iterator.this_type, loc);
-                               return fexpr.ResolveLValue (ec, right_side, loc);
+                       Label [] labels = null;
+                       int n_resume_points = resume_points == null ? 0 : resume_points.Count;
+                       for (int i = 0; i < n_resume_points; ++i) {
+                               ResumableStatement s = (ResumableStatement) resume_points [i];
+                               Label ret = s.PrepareForDispose (ec, end);
+                               if (ret.Equals (end) && labels == null)
+                                       continue;
+                               if (labels == null) {
+                                       labels = new Label [resume_points.Count + 1];
+                                       for (int j = 0; j <= i; ++j)
+                                               labels [j] = end;
+                               }
+                               labels [i+1] = ret;
                        }
 
-                       public override Expression DoResolve (EmitContext ec)
-                       {
-                               FieldExpr fexpr = new FieldExpr (field.FieldBuilder, loc);
-                               fexpr.InstanceExpression = new ThisParameterReference (
-                                       iterator.this_type, loc);
-                               return fexpr.Resolve (ec);
+                       if (labels != null) {
+                               current_pc = ec.GetTemporaryLocal (TypeManager.uint32_type);
+                               ig.Emit (OpCodes.Ldarg_0);
+                               ig.Emit (OpCodes.Ldfld, IteratorHost.PC.FieldBuilder);
+                               ig.Emit (OpCodes.Stloc, current_pc);
                        }
 
-                       public override void Emit (EmitContext ec)
-                       {
-                               throw new InvalidOperationException ();
-                       }
-               }
+                       ig.Emit (OpCodes.Ldarg_0);
+                       IntConstant.EmitInt (ig, (int) State.After);
+                       ig.Emit (OpCodes.Stfld, IteratorHost.PC.FieldBuilder);
 
-               protected class MoveNextMethod : AnonymousContainer
-               {
-                       Iterator iterator;
+                       if (labels != null) {
+                               //SymbolWriter.StartIteratorDispatcher (ec.ig);
+                               ig.Emit (OpCodes.Ldloc, current_pc);
+                               ig.Emit (OpCodes.Switch, labels);
+                               //SymbolWriter.EndIteratorDispatcher (ec.ig);
 
-                       public MoveNextMethod (Iterator iterator, Location loc)
-                               : base (iterator.parameters.Parameters, iterator.original_block, loc)
-                       {
-                               this.iterator = iterator;
+                               foreach (ResumableStatement s in resume_points)
+                                       s.EmitForDispose (ec, this, end, true);
                        }
 
-                       protected override bool CreateMethodHost (EmitContext ec)
-                       {
-                               method = new Method (
-                                       iterator, TypeManager.system_boolean_expr,
-                                       Modifiers.PUBLIC, false, new MemberName ("MoveNext", loc),
-                                       Parameters.EmptyReadOnlyParameters, null);
+                       ig.MarkLabel (end);
+               }
 
-                               method.Block = Block;
+               ArrayList resume_points;
+               public int AddResumePoint (ResumableStatement stmt, Location loc)
+               {
+                       if (resume_points == null)
+                               resume_points = new ArrayList ();
+                       resume_points.Add (stmt);
+                       return resume_points.Count;
+               }
 
-                               MoveNextStatement inline = new MoveNextStatement (iterator, loc);
-                               Block.AddStatement (inline);
+               //
+               // Called back from Yield
+               //
+               public void MarkYield (EmitContext ec, Expression expr, int resume_pc, bool unwind_protect, Label resume_point)
+               {
+                       ILGenerator ig = ec.ig;
 
-                               return true;
-                       }
+                       // Store the new current
+                       ig.Emit (OpCodes.Ldarg_0);
+                       expr.Emit (ec);
+                       ig.Emit (OpCodes.Stfld, IteratorHost.CurrentField.FieldBuilder);
 
-                       public bool CreateMethod (EmitContext ec)
-                       {
-                               return CreateMethodHost (ec);
-                       }
+                       // store resume program-counter
+                       ig.Emit (OpCodes.Ldarg_0);
+                       IntConstant.EmitInt (ig, resume_pc);
+                       ig.Emit (OpCodes.Stfld, IteratorHost.PC.FieldBuilder);
 
-                       public override bool IsIterator {
-                               get { return true; }
+                       // mark finally blocks as disabled
+                       if (unwind_protect && skip_finally != null) {
+                               ig.Emit (OpCodes.Ldc_I4_1);
+                               ig.Emit (OpCodes.Stloc, skip_finally);
                        }
 
-                       public override void CreateScopeType (EmitContext ec, ScopeInfo scope)
-                       {
-                               scope.ScopeTypeBuilder = iterator.TypeBuilder;
-                               scope.ScopeConstructor = iterator.ctor.ConstructorBuilder;
-                       }
+                       // Return ok
+                       ig.Emit (unwind_protect ? OpCodes.Leave : OpCodes.Br, move_next_ok);
 
-                       public override void Emit (EmitContext ec)
-                       {
-                               throw new InternalErrorException ();
-                       }
+                       ig.MarkLabel (resume_point);
                }
 
-               protected class MoveNextStatement : Statement {
-                       Iterator iterator;
-
-                       public MoveNextStatement (Iterator iterator, Location loc)
-                       {
-                               this.loc = loc;
-                               this.iterator = iterator;
-                       }
+               public override string ContainerType {
+                       get { return "iterator"; }
+               }
 
-                       public override bool Resolve (EmitContext ec)
-                       {
-                               return true;
-                       }
+               public override bool IsIterator {
+                       get { return true; }
+               }
 
-                       protected override void DoEmit (EmitContext ec)
-                       {
-                               ec.CurrentIterator = iterator;
-                               ec.CurrentAnonymousMethod = iterator.move_next_method;
-                               ec.InIterator = true;
+               public override RootScopeInfo RootScope {
+                       get { return IteratorHost; }
+               }
 
-                               iterator.EmitMoveNext (ec);
-                       }
+               public override ScopeInfo Scope {
+                       get { return IteratorHost; }
                }
 
-               protected class DisposeMethod : Statement {
-                       Iterator iterator;
+               //
+               // Our constructor
+               //
+               private Iterator (IMethodData m_container, DeclSpace host, GenericMethod generic,
+                                int modifiers, Type iterator_type, bool is_enumerable)
+                       : base (host, generic, m_container.ParameterInfo,
+                               new ToplevelBlock (m_container.ParameterInfo, m_container.Location),
+                               m_container.Block, TypeManager.bool_type, modifiers,
+                               m_container.Location)
+               {
+                       this.OriginalBlock = m_container.Block;
+                       this.OriginalMethod = m_container;
+                       this.OriginalIteratorType = iterator_type;
+                       this.IsEnumerable = is_enumerable;
 
-                       public DisposeMethod (Iterator iterator, Location loc)
-                       {
-                               this.loc = loc;
-                               this.iterator = iterator;
-                       }
+                       Report.Debug (64, "NEW ITERATOR", host, generic, OriginalBlock,
+                                     Container, Block);
 
-                       public override bool Resolve (EmitContext ec)
-                       {
-                               return true;
-                       }
+                       IteratorHost = new IteratorHost (this);
+                       Block.CreateIteratorHost (IteratorHost);
 
-                       protected override void DoEmit (EmitContext ec)
-                       {
-                               iterator.EmitDispose (ec);
-                       }
-               }
+                       OriginalBlock.ReParent (Container.Toplevel);
 
-               protected class StatementList : Statement {
-                       ArrayList statements;
+                       m_container.Block = Container.Toplevel;
 
-                       public StatementList (Location loc)
-                       {
-                               this.loc = loc;
-                               statements = new ArrayList ();
-                       }
-
-                       public void Add (Statement statement)
-                       {
-                               statements.Add (statement);
-                       }
+                       OriginalBlock.MakeIterator (this);
+               }
 
+               protected class TestStatement : Statement
+               {
                        public override bool Resolve (EmitContext ec)
                        {
-                               foreach (Statement stmt in statements) {
-                                       if (!stmt.Resolve (ec))
-                                               return false;
-                               }
-
                                return true;
                        }
 
                        protected override void DoEmit (EmitContext ec)
                        {
-                               foreach (Statement stmt in statements)
-                                       stmt.Emit (ec);
+                               ec.ig.Emit (OpCodes.Nop);
+                               ec.ig.Emit (OpCodes.Neg);
+                               ec.ig.Emit (OpCodes.Pop);
+                               ec.ig.Emit (OpCodes.Ret);
                        }
                }
 
-               protected class SetState : Statement
+               public override string GetSignatureForError ()
                {
-                       Iterator iterator;
-                       State state;
+                       return OriginalMethod.GetSignatureForError ();
+               }
 
-                       public SetState (Iterator iterator, State state, Location loc)
-                       {
-                               this.iterator = iterator;
-                               this.state = state;
-                               this.loc = loc;
-                       }
+               public override bool Define (EmitContext ec)
+               {
+                       Report.Debug (64, "RESOLVE ITERATOR", this, Container, Block);
 
-                       public override bool Resolve (EmitContext ec)
-                       {
-                               return true;
+                       Parameters parameters = OriginalMethod.ParameterInfo;
+                       for (int i = 0; i < parameters.Count; i++){
+                               Parameter.Modifier mod = parameters.ParameterModifier (i);
+                               if ((mod & (Parameter.Modifier.REF | Parameter.Modifier.OUT)) != 0){
+                                       Report.Error (1623, Location,
+                                                     "Iterators cannot have ref or out parameters");
+                                       return false;
+                               }
+
+                               if ((mod & Parameter.Modifier.ARGLIST) != 0) {
+                                       Report.Error (1636, Location,
+                                                     "__arglist is not allowed in parameter list " +
+                                                     "of iterators");
+                                       return false;
+                               }
+
+                               if (parameters.ParameterType (i).IsPointer) {
+                                       Report.Error (1637, Location,
+                                                     "Iterators cannot have unsafe parameters or " +
+                                                     "yield types");
+                                       return false;
+                               }
                        }
 
-                       protected override void DoEmit (EmitContext ec)
-                       {
-                               ec.ig.Emit (OpCodes.Ldarg_0);
-                               IntConstant.EmitInt (ec.ig, (int) state);
-                               ec.ig.Emit (OpCodes.Stfld, iterator.pc_field.FieldBuilder);
+                       if ((ModFlags & Modifiers.UNSAFE) != 0) {
+                               Report.Error (1629, Location, "Unsafe code may not appear in iterators");
+                               return false;
                        }
-               }
 
-               protected class InitScope : Statement
-               {
-                       Iterator iterator;
+                       if (!base.Define (ec))
+                               return false;
 
-                       public InitScope (Iterator iterator, Location loc)
-                       {
-                               this.iterator = iterator;
-                               this.loc = loc;
-                       }
+                       Report.Debug (64, "RESOLVE ITERATOR #1", this, method, method.Parent,
+                                     RootScope, ec);
 
-                       public override bool Resolve (EmitContext ec)
-                       {
-                               return true;
-                       }
+                       if (!RootScope.ResolveType ())
+                               return false;
+                       if (!RootScope.ResolveMembers ())
+                               return false;
+                       if (!RootScope.DefineMembers ())
+                               return false;
 
-                       protected override void DoEmit (EmitContext ec)
-                       {
-                               iterator.cc.EmitInitScope (ec);
-                       }
+                       ExpressionStatement scope_init = RootScope.GetScopeInitializer (ec);
+                       Container.AddStatement (new StatementExpression (scope_init));
+                       Expression cast = new ClassCast (scope_init, OriginalMethod.ReturnType);
+                       Container.AddStatement (new NoCheckReturn (cast));
+
+                       return true;
                }
 
-               void Define_Reset ()
+               protected override Method DoCreateMethodHost (EmitContext ec)
                {
-                       Method reset = new Method (
-                               this, TypeManager.system_void_expr, Modifiers.PUBLIC,
-                               false, new MemberName ("Reset", Location),
-                               Parameters.EmptyReadOnlyParameters, null);
-                       AddMethod (reset);
+                       Report.Debug (128, "CREATE METHOD HOST", this, IteratorHost);
 
-                       reset.Block = new ToplevelBlock (Location);
-                       reset.Block = new ToplevelBlock (block, parameters.Parameters, Location);
-                       reset.Block.SetHaveAnonymousMethods (Location, move_next_method);
+                       MemberCore mc = ec.ResolveContext as MemberCore;
 
-                       reset.Block.AddStatement (Create_ThrowNotSupported ());
+                       IteratorHost.CaptureScopes ();
+
+                       return new AnonymousMethodMethod (
+                               this, RootScope, null, TypeManager.system_boolean_expr,
+                               Modifiers.PUBLIC, mc.GetSignatureForError (),
+                               new MemberName ("MoveNext", Location),
+                               Parameters.EmptyReadOnlyParameters);
                }
 
-               void Define_Dispose ()
+               public override Expression DoResolve (EmitContext ec)
                {
-                       dispose = new Method (
-                               this, TypeManager.system_void_expr, Modifiers.PUBLIC,
-                               false, new MemberName ("Dispose", Location),
-                               Parameters.EmptyReadOnlyParameters, null);
-                       AddMethod (dispose);
-
-                       dispose.Block = new ToplevelBlock (block, parameters.Parameters, Location);
-                       dispose.Block.SetHaveAnonymousMethods (Location, move_next_method);
-
-                       dispose.Block.AddStatement (new DisposeMethod (this, Location));
+                       throw new NotSupportedException ();
                }
 
                public Type IteratorType {
-                       get { return iterator_type; }
+                       get { return IteratorHost.IteratorType; }
                }
 
                //
@@ -1027,10 +964,10 @@ namespace Mono.CSharp {
                class NoCheckReturn : Statement {
                        public Expression Expr;
                
-                       public NoCheckReturn (Expression expr, Location l)
+                       public NoCheckReturn (Expression expr)
                        {
                                Expr = expr;
-                               loc = l;
+                               loc = expr.Location;
                        }
 
                        public override bool Resolve (EmitContext ec)
@@ -1039,7 +976,7 @@ namespace Mono.CSharp {
                                if (Expr == null)
                                        return false;
 
-                               ec.CurrentBranching.CurrentUsageVector.Return ();
+                               ec.CurrentBranching.CurrentUsageVector.Goto ();
 
                                return true;
                        }
@@ -1051,20 +988,69 @@ namespace Mono.CSharp {
                        }
                }
 
-               bool CheckType ()
+               public override Expression CreateExpressionTree (EmitContext ec)
+               {
+                       throw new NotSupportedException ("ET");
+               }
+
+               public static Iterator CreateIterator (IMethodData method, DeclSpace parent,
+                                                      GenericMethod generic, int modifiers)
+               {
+                       bool is_enumerable;
+                       Type iterator_type;
+
+                       Type ret = method.ReturnType;
+                       if (ret == null)
+                               return null;
+
+                       if (!CheckType (ret, out iterator_type, out is_enumerable)) {
+                               Report.Error (1624, method.Location,
+                                             "The body of `{0}' cannot be an iterator block " +
+                                             "because `{1}' is not an iterator interface type",
+                                             method.GetSignatureForError (),
+                                             TypeManager.CSharpName (ret));
+                               return null;
+                       }
+
+                       return new Iterator (method, parent, generic, modifiers,
+                                            iterator_type, is_enumerable);
+               }
+
+               static bool CheckType (Type ret, out Type original_iterator_type, out bool is_enumerable)
                {
-                       Type ret = orig_method.ReturnType;
+                       original_iterator_type = null;
+                       is_enumerable = false;
 
                        if (ret == TypeManager.ienumerable_type) {
-                               iterator_type = TypeManager.object_type;
+                               original_iterator_type = TypeManager.object_type;
                                is_enumerable = true;
                                return true;
                        }
                        if (ret == TypeManager.ienumerator_type) {
-                               iterator_type = TypeManager.object_type;
+                               original_iterator_type = TypeManager.object_type;
+                               is_enumerable = false;
+                               return true;
+                       }
+
+#if GMCS_SOURCE
+                       if (!ret.IsGenericType)
+                               return false;
+
+                       Type[] args = TypeManager.GetTypeArguments (ret);
+                       if (args.Length != 1)
+                               return false;
+
+                       Type gt = ret.GetGenericTypeDefinition ();
+                       if (gt == TypeManager.generic_ienumerable_type) {
+                               original_iterator_type = args [0];
+                               is_enumerable = true;
+                               return true;
+                       } else if (gt == TypeManager.generic_ienumerator_type) {
+                               original_iterator_type = args [0];
                                is_enumerable = false;
                                return true;
                        }
+#endif
 
                        return false;
                }