2008-09-17 Marek Safar <marek.safar@gmail.com>
[mono.git] / mcs / mcs / statement.cs
index fb8391d611e68f3feca8efa5c954c2259af85e7f..1f42cbdabd0b1873671e424bea8dd1ff3c90fa00 100644 (file)
@@ -6,8 +6,8 @@
 //   Martin Baulig (martin@ximian.com)
 //   Marek Safar (marek.safar@seznam.cz)
 //
-// (C) 2001, 2002, 2003 Ximian, Inc.
-// (C) 2003, 2004 Novell, Inc.
+// Copyright 2001, 2002, 2003 Ximian, Inc.
+// Copyright 2003, 2004 Novell, Inc.
 //
 
 using System;
@@ -83,7 +83,7 @@ namespace Mono.CSharp {
                /// </summary>
                public virtual void Emit (EmitContext ec)
                {
-                       ec.Mark (loc, true);
+                       ec.Mark (loc);
                        DoEmit (ec);
                }
 
@@ -91,21 +91,21 @@ namespace Mono.CSharp {
                // This routine must be overrided in derived classes and make copies
                // of all the data that might be modified if resolved
                // 
-               protected virtual void CloneTo (CloneContext clonectx, Statement target)
-               {
-                       throw new Exception (String.Format ("Statement.CloneTo not implemented for {0}", this.GetType ()));
-               }
-               
+               protected abstract void CloneTo (CloneContext clonectx, Statement target);
+
                public Statement Clone (CloneContext clonectx)
                {
                        Statement s = (Statement) this.MemberwiseClone ();
-                       if (s is Block)
-                               clonectx.AddBlockMap ((Block) this, (Block) s);
-                       
                        CloneTo (clonectx, s);
                        return s;
                }
 
+               public virtual Expression CreateExpressionTree (EmitContext ec)
+               {
+                       Report.Error (834, loc, "A lambda expression with statement body cannot be converted to an expresion tree");
+                       return null;
+               }
+
                public Statement PerformClone ()
                {
                        CloneContext clonectx = new CloneContext ();
@@ -113,6 +113,7 @@ namespace Mono.CSharp {
                        return Clone (clonectx);
                }
 
+               public abstract void MutateHoistedGenericType (AnonymousMethodStorey storey);
        }
 
        //
@@ -146,6 +147,18 @@ namespace Mono.CSharp {
                        return result;
                }
 
+               ///
+               /// Remaps block to cloned copy if one exists.
+               ///
+               public Block RemapBlockCopy (Block from)
+               {
+                       Block mapped_to = (Block)block_map[from];
+                       if (mapped_to == null)
+                               return from;
+
+                       return mapped_to;
+               }
+
                public void AddVariableMap (LocalInfo from, LocalInfo to)
                {
                        if (variable_map == null)
@@ -186,6 +199,15 @@ namespace Mono.CSharp {
                protected override void DoEmit (EmitContext ec)
                {
                }
+
+               public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
+               {
+               }
+
+               protected override void CloneTo (CloneContext clonectx, Statement target)
+               {
+                       // nothing needed.
+               }
        }
        
        public class If : Statement {
@@ -195,24 +217,32 @@ namespace Mono.CSharp {
 
                bool is_true_ret;
                
-               public If (Expression expr, Statement trueStatement, Location l)
+               public If (Expression expr, Statement true_statement, Location l)
                {
                        this.expr = expr;
-                       TrueStatement = trueStatement;
+                       TrueStatement = true_statement;
                        loc = l;
                }
 
                public If (Expression expr,
-                          Statement trueStatement,
-                          Statement falseStatement,
+                          Statement true_statement,
+                          Statement false_statement,
                           Location l)
                {
                        this.expr = expr;
-                       TrueStatement = trueStatement;
-                       FalseStatement = falseStatement;
+                       TrueStatement = true_statement;
+                       FalseStatement = false_statement;
                        loc = l;
                }
 
+               public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
+               {
+                       expr.MutateHoistedGenericType (storey);
+                       TrueStatement.MutateHoistedGenericType (storey);
+                       if (FalseStatement != null)
+                               FalseStatement.MutateHoistedGenericType (storey);
+               }
+
                public override bool Resolve (EmitContext ec)
                {
                        bool ok = true;
@@ -233,8 +263,8 @@ namespace Mono.CSharp {
                        //
                        // Dead code elimination
                        //
-                       if (expr is BoolConstant){
-                               bool take = ((BoolConstant) expr).Value;
+                       if (expr is Constant){
+                               bool take = !((Constant) expr).IsDefaultValue;
 
                                if (take){
                                        if (!TrueStatement.Resolve (ec))
@@ -282,19 +312,20 @@ namespace Mono.CSharp {
                        Label end;
 
                        //
-                       // If we're a boolean expression, Resolve() already
+                       // If we're a boolean constant, Resolve() already
                        // eliminated dead code for us.
                        //
-                       if (expr is BoolConstant){
-                               bool take = ((BoolConstant) expr).Value;
+                       Constant c = expr as Constant;
+                       if (c != null){
+                               c.EmitSideEffect (ec);
 
-                               if (take)
+                               if (!c.IsDefaultValue)
                                        TrueStatement.Emit (ec);
                                else if (FalseStatement != null)
                                        FalseStatement.Emit (ec);
 
                                return;
-                       }
+                       }                       
                        
                        expr.EmitBranchable (ec, false_target, false);
                        
@@ -333,11 +364,10 @@ namespace Mono.CSharp {
        public class Do : Statement {
                public Expression expr;
                public Statement  EmbeddedStatement;
-               bool infinite;
                
-               public Do (Statement statement, Expression boolExpr, Location l)
+               public Do (Statement statement, Expression bool_expr, Location l)
                {
-                       expr = boolExpr;
+                       expr = bool_expr;
                        EmbeddedStatement = statement;
                        loc = l;
                }
@@ -361,14 +391,11 @@ namespace Mono.CSharp {
                        expr = Expression.ResolveBoolean (ec, expr, loc);
                        if (expr == null)
                                ok = false;
-                       else if (expr is BoolConstant){
-                               bool res = ((BoolConstant) expr).Value;
-
-                               if (res)
-                                       infinite = true;
+                       else if (expr is Constant){
+                               bool infinite = !((Constant) expr).IsDefaultValue;
+                               if (infinite)
+                                       ec.CurrentBranching.CurrentUsageVector.Goto ();
                        }
-                       if (infinite)
-                               ec.CurrentBranching.CurrentUsageVector.Goto ();
 
                        ec.EndFlowBranching ();
 
@@ -392,9 +419,10 @@ namespace Mono.CSharp {
                        //
                        // Dead code elimination
                        //
-                       if (expr is BoolConstant){
-                               bool res = ((BoolConstant) expr).Value;
+                       if (expr is Constant){
+                               bool res = !((Constant) expr).IsDefaultValue;
 
+                               expr.EmitSideEffect (ec);
                                if (res)
                                        ec.ig.Emit (OpCodes.Br, loop); 
                        } else
@@ -406,6 +434,12 @@ namespace Mono.CSharp {
                        ec.LoopEnd = old_end;
                }
 
+               public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
+               {
+                       expr.MutateHoistedGenericType (storey);
+                       EmbeddedStatement.MutateHoistedGenericType (storey);
+               }
+
                protected override void CloneTo (CloneContext clonectx, Statement t)
                {
                        Do target = (Do) t;
@@ -420,9 +454,9 @@ namespace Mono.CSharp {
                public Statement Statement;
                bool infinite, empty;
                
-               public While (Expression boolExpr, Statement statement, Location l)
+               public While (Expression bool_expr, Statement statement, Location l)
                {
-                       this.expr = boolExpr;
+                       this.expr = bool_expr;
                        Statement = statement;
                        loc = l;
                }
@@ -438,10 +472,10 @@ namespace Mono.CSharp {
                        //
                        // Inform whether we are infinite or not
                        //
-                       if (expr is BoolConstant){
-                               BoolConstant bc = (BoolConstant) expr;
+                       if (expr is Constant){
+                               bool value = !((Constant) expr).IsDefaultValue;
 
-                               if (bc.Value == false){
+                               if (value == false){
                                        if (!Statement.ResolveUnreachable (ec, true))
                                                return false;
                                        empty = true;
@@ -469,8 +503,10 @@ namespace Mono.CSharp {
                
                protected override void DoEmit (EmitContext ec)
                {
-                       if (empty)
+                       if (empty) {
+                               expr.EmitSideEffect (ec);
                                return;
+                       }
 
                        ILGenerator ig = ec.ig;
                        Label old_begin = ec.LoopBegin;
@@ -482,8 +518,10 @@ namespace Mono.CSharp {
                        //
                        // Inform whether we are infinite or not
                        //
-                       if (expr is BoolConstant){
+                       if (expr is Constant){
+                               // expr is 'true', since the 'empty' case above handles the 'false' case
                                ig.MarkLabel (ec.LoopBegin);
+                               expr.EmitSideEffect (ec);
                                Statement.Emit (ec);
                                ig.Emit (OpCodes.Br, ec.LoopBegin);
                                        
@@ -501,6 +539,7 @@ namespace Mono.CSharp {
                                Statement.Emit (ec);
                        
                                ig.MarkLabel (ec.LoopBegin);
+                               ec.Mark (loc);
 
                                expr.EmitBranchable (ec, while_loop, true);
                                
@@ -511,6 +550,11 @@ namespace Mono.CSharp {
                        ec.LoopEnd = old_end;
                }
 
+               public override void Emit (EmitContext ec)
+               {
+                       DoEmit (ec);
+               }
+
                protected override void CloneTo (CloneContext clonectx, Statement t)
                {
                        While target = (While) t;
@@ -518,6 +562,12 @@ namespace Mono.CSharp {
                        target.expr = expr.Clone (clonectx);
                        target.Statement = Statement.Clone (clonectx);
                }
+
+               public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
+               {
+                       expr.MutateHoistedGenericType (storey);
+                       Statement.MutateHoistedGenericType (storey);
+               }
        }
 
        public class For : Statement {
@@ -527,13 +577,13 @@ namespace Mono.CSharp {
                public Statement Statement;
                bool infinite, empty;
                
-               public For (Statement initStatement,
+               public For (Statement init_statement,
                            Expression test,
                            Statement increment,
                            Statement statement,
                            Location l)
                {
-                       InitStatement = initStatement;
+                       InitStatement = init_statement;
                        Test = test;
                        Increment = increment;
                        Statement = statement;
@@ -553,10 +603,10 @@ namespace Mono.CSharp {
                                Test = Expression.ResolveBoolean (ec, Test, loc);
                                if (Test == null)
                                        ok = false;
-                               else if (Test is BoolConstant){
-                                       BoolConstant bc = (BoolConstant) Test;
+                               else if (Test is Constant){
+                                       bool value = !((Constant) Test).IsDefaultValue;
 
-                                       if (bc.Value == false){
+                                       if (value == false){
                                                if (!Statement.ResolveUnreachable (ec, true))
                                                        return false;
                                                if ((Increment != null) &&
@@ -598,20 +648,22 @@ namespace Mono.CSharp {
 
                        return ok;
                }
-               
+
                protected override void DoEmit (EmitContext ec)
                {
-                       if (empty)
+                       if (InitStatement != null && InitStatement != EmptyStatement.Value)
+                               InitStatement.Emit (ec);
+
+                       if (empty) {
+                               Test.EmitSideEffect (ec);
                                return;
+                       }
 
                        ILGenerator ig = ec.ig;
                        Label old_begin = ec.LoopBegin;
                        Label old_end = ec.LoopEnd;
                        Label loop = ig.DefineLabel ();
                        Label test = ig.DefineLabel ();
-                       
-                       if (InitStatement != null && InitStatement != EmptyStatement.Value)
-                               InitStatement.Emit (ec);
 
                        ec.LoopBegin = ig.DefineLabel ();
                        ec.LoopEnd = ig.DefineLabel ();
@@ -632,13 +684,15 @@ namespace Mono.CSharp {
                        if (Test != null){
                                //
                                // The Resolve code already catches the case for
-                               // Test == BoolConstant (false) so we know that
+                               // Test == Constant (false) so we know that
                                // this is true
                                //
-                               if (Test is BoolConstant)
+                               if (Test is Constant) {
+                                       Test.EmitSideEffect (ec);
                                        ig.Emit (OpCodes.Br, loop);
-                               else
+                               } else {
                                        Test.EmitBranchable (ec, loop, true);
+                               }
                                
                        } else
                                ig.Emit (OpCodes.Br, loop);
@@ -648,6 +702,18 @@ namespace Mono.CSharp {
                        ec.LoopEnd = old_end;
                }
 
+               public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
+               {
+                       if (InitStatement != null)
+                               InitStatement.MutateHoistedGenericType (storey);
+                       if (Test != null)
+                               Test.MutateHoistedGenericType (storey);
+                       if (Increment != null)
+                               Increment.MutateHoistedGenericType (storey);
+
+                       Statement.MutateHoistedGenericType (storey);
+               }
+
                protected override void CloneTo (CloneContext clonectx, Statement t)
                {
                        For target = (For) t;
@@ -683,6 +749,11 @@ namespace Mono.CSharp {
                        expr.EmitStatement (ec);
                }
 
+               public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
+               {
+                       expr.MutateHoistedGenericType (storey);
+               }
+
                public override string ToString ()
                {
                        return "StatementExpression (" + expr + ")";
@@ -696,69 +767,94 @@ namespace Mono.CSharp {
                }
        }
 
+       // A 'return' or a 'yield break'
+       public abstract class ExitStatement : Statement
+       {
+               protected bool unwind_protect;
+               protected abstract bool DoResolve (EmitContext ec);
+
+               public virtual void Error_FinallyClause ()
+               {
+                       Report.Error (157, loc, "Control cannot leave the body of a finally clause");
+               }
+
+               public sealed override bool Resolve (EmitContext ec)
+               {
+                       if (!DoResolve (ec))
+                               return false;
+
+                       unwind_protect = ec.CurrentBranching.AddReturnOrigin (ec.CurrentBranching.CurrentUsageVector, this);
+                       if (unwind_protect)
+                               ec.NeedReturnLabel ();
+                       ec.CurrentBranching.CurrentUsageVector.Goto ();
+                       return true;
+               }
+       }
+
        /// <summary>
        ///   Implements the return statement
        /// </summary>
-       public class Return : Statement {
-               public Expression Expr;
-               
+       public class Return : ExitStatement {
+               protected Expression Expr;
                public Return (Expression expr, Location l)
                {
                        Expr = expr;
                        loc = l;
                }
-
-               bool unwind_protect;
-
-               public override bool Resolve (EmitContext ec)
+               
+               protected override bool DoResolve (EmitContext ec)
                {
-                       AnonymousContainer am = ec.CurrentAnonymousMethod;
-                       if ((am != null) && am.IsIterator && ec.InIterator) {
-                               Report.Error (1622, loc, "Cannot return a value from iterators. Use the yield return " +
-                                             "statement to return a value, or yield break to end the iteration");
+                       if (Expr == null) {
+                               if (ec.ReturnType == TypeManager.void_type)
+                                       return true;
+                               
+                               Error (126, "An object of a type convertible to `{0}' is required " +
+                                          "for the return statement",
+                                          TypeManager.CSharpName (ec.ReturnType));
                                return false;
                        }
 
-                       if (ec.ReturnType == null){
-                               if (Expr != null){
-                                       if (am != null){
-                                               Report.Error (1662, loc,
-                                                       "Cannot convert anonymous method block to delegate type `{0}' because some of the return types in the block are not implicitly convertible to the delegate return type",
-                                                       am.GetSignatureForError ());
-                                       }
-                                       Error (127, "A return keyword must not be followed by any expression when method returns void");
-                                       return false;
-                               }
-                       } else {
-                               if (Expr == null){
-                                       Error (126, "An object of a type convertible to `{0}' is required " +
-                                              "for the return statement",
-                                              TypeManager.CSharpName (ec.ReturnType));
-                                       return false;
-                               }
+                       if (ec.CurrentBlock.Toplevel.IsIterator) {
+                               Report.Error (1622, loc, "Cannot return a value from iterators. Use the yield return " +
+                                                 "statement to return a value, or yield break to end the iteration");
+                       }
 
-                               Expr = Expr.Resolve (ec);
-                               if (Expr == null)
-                                       return false;
+                       AnonymousExpression am = ec.CurrentAnonymousMethod;
+                       if (am == null && ec.ReturnType == TypeManager.void_type) {
+                               MemberCore mc = ec.ResolveContext as MemberCore;
+                               Report.Error (127, loc, "`{0}': A return keyword must not be followed by any expression when method returns void",
+                                       mc.GetSignatureForError ());
+                       }
 
-                               if (Expr.Type != ec.ReturnType) {
-                                       if (ec.InferReturnType) {
-                                               ec.ReturnType = Expr.Type;
-                                       } else {
-                                               Expr = Convert.ImplicitConversionRequired (
-                                                       ec, Expr, ec.ReturnType, loc);
-                                               if (Expr == null)
-                                                       return false;
+                       Expr = Expr.Resolve (ec);
+                       if (Expr == null)
+                               return false;
+
+                       if (Expr.Type != ec.ReturnType) {
+                               if (ec.InferReturnType) {
+                                       //
+                                       // void cannot be used in contextual return
+                                       //
+                                       if (Expr.Type == TypeManager.void_type)
+                                               return false;
+
+                                       ec.ReturnType = Expr.Type;
+                               } else {
+                                       Expr = Convert.ImplicitConversionRequired (
+                                               ec, Expr, ec.ReturnType, loc);
+
+                                       if (Expr == null) {
+                                               if (am != null) {
+                                                       Report.Error (1662, loc,
+                                                               "Cannot convert `{0}' to delegate type `{1}' because some of the return types in the block are not implicitly convertible to the delegate return type",
+                                                               am.ContainerType, am.GetSignatureForError ());
+                                               }
+                                               return false;
                                        }
                                }
                        }
 
-                       int errors = Report.Errors;
-                       unwind_protect = ec.CurrentBranching.AddReturnOrigin (ec.CurrentBranching.CurrentUsageVector, loc);
-                       if (unwind_protect)
-                               ec.NeedReturnLabel ();
-                       ec.CurrentBranching.CurrentUsageVector.Goto ();
-                       return errors == Report.Errors;
+                       return true;                    
                }
                
                protected override void DoEmit (EmitContext ec)
@@ -776,11 +872,18 @@ namespace Mono.CSharp {
                                ec.ig.Emit (OpCodes.Ret);
                }
 
+               public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
+               {
+                       if (Expr != null)
+                               Expr.MutateHoistedGenericType (storey);
+               }
+
                protected override void CloneTo (CloneContext clonectx, Statement t)
                {
                        Return target = (Return) t;
-
-                       target.Expr = Expr.Clone (clonectx);
+                       // It's null for simple return;
+                       if (Expr != null)
+                               target.Expr = Expr.Clone (clonectx);
                }
        }
 
@@ -813,6 +916,11 @@ namespace Mono.CSharp {
                        label.AddReference ();
                }
 
+               protected override void CloneTo (CloneContext clonectx, Statement target)
+               {
+                       // Nothing to clone
+               }
+
                protected override void DoEmit (EmitContext ec)
                {
                        if (label == null)
@@ -820,6 +928,10 @@ namespace Mono.CSharp {
                        Label l = label.LabelTarget (ec);
                        ec.ig.Emit (unwind_protect ? OpCodes.Leave : OpCodes.Br, l);
                }
+
+               public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
+               {
+               }
        }
 
        public class LabeledStatement : Statement {
@@ -871,6 +983,11 @@ namespace Mono.CSharp {
                        vectors = vector;
                }
 
+               protected override void CloneTo (CloneContext clonectx, Statement target)
+               {
+                       // nothing to clone
+               }
+
                public override bool Resolve (EmitContext ec)
                {
                        // this flow-branching will be terminated when the surrounding block ends
@@ -886,6 +1003,10 @@ namespace Mono.CSharp {
                        ec.ig.MarkLabel (label);
                }
 
+               public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
+               {
+               }
+
                public void AddReference ()
                {
                        referenced = true;
@@ -903,6 +1024,11 @@ namespace Mono.CSharp {
                        loc = l;
                }
 
+               protected override void CloneTo (CloneContext clonectx, Statement target)
+               {
+                       // nothing to clone
+               }
+
                public override bool Resolve (EmitContext ec)
                {
                        ec.CurrentBranching.CurrentUsageVector.Goto ();
@@ -917,11 +1043,15 @@ namespace Mono.CSharp {
                        }
 
                        if (!ec.Switch.GotDefault){
-                               Report.Error (159, loc, "No such label `default:' within the scope of the goto statement");
+                               FlowBranchingBlock.Error_UnknownLabel (loc, "default");
                                return;
                        }
                        ec.ig.Emit (OpCodes.Br, ec.Switch.DefaultTarget);
                }
+
+               public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
+               {
+               }
        }
 
        /// <summary>
@@ -976,7 +1106,8 @@ namespace Mono.CSharp {
                        sl = (SwitchLabel) ec.Switch.Elements [val];
 
                        if (sl == null){
-                               Report.Error (159, loc, "No such label `case {0}:' within the scope of the goto statement", c.GetValue () == null ? "null" : val.ToString ());
+                               FlowBranchingBlock.Error_UnknownLabel (loc, "case " + 
+                                       (c.GetValue () == null ? "null" : val.ToString ()));
                                return false;
                        }
 
@@ -989,12 +1120,16 @@ namespace Mono.CSharp {
                        ec.ig.Emit (OpCodes.Br, sl.GetILLabelCode (ec));
                }
 
+               public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
+               {
+                       expr.MutateHoistedGenericType (storey);
+               }
+
                protected override void CloneTo (CloneContext clonectx, Statement t)
                {
                        GotoCase target = (GotoCase) t;
 
                        target.expr = expr.Clone (clonectx);
-                       target.sl = sl.Clone (clonectx);
                }
        }
        
@@ -1009,41 +1144,23 @@ namespace Mono.CSharp {
 
                public override bool Resolve (EmitContext ec)
                {
-                       ec.CurrentBranching.CurrentUsageVector.Goto ();
-
-                       if (expr != null){
-                               expr = expr.Resolve (ec);
-                               if (expr == null)
-                                       return false;
-
-                               ExprClass eclass = expr.eclass;
-
-                               if (!(eclass == ExprClass.Variable || eclass == ExprClass.PropertyAccess ||
-                                       eclass == ExprClass.Value || eclass == ExprClass.IndexerAccess)) {
-                                       expr.Error_UnexpectedKind (ec.DeclContainer, "value, variable, property or indexer access ", loc);
-                                       return false;
-                               }
-
-                               Type t = expr.Type;
-                               
-                               if ((t != TypeManager.exception_type) &&
-                                   !TypeManager.IsSubclassOf (t, TypeManager.exception_type) &&
-                                   !(expr is NullLiteral)) {
-                                       Error (155,
-                                               "The type caught or thrown must be derived " +
-                                               "from System.Exception");
-                                       return false;
-                               }
-                               return true;
+                       if (expr == null) {
+                               ec.CurrentBranching.CurrentUsageVector.Goto ();
+                               return ec.CurrentBranching.CheckRethrow (loc);
                        }
 
-                       if (!ec.InCatch) {
-                               Error (156, "A throw statement with no arguments is not allowed outside of a catch clause");
+                       expr = expr.Resolve (ec, ResolveFlags.Type | ResolveFlags.VariableOrValue);
+                       ec.CurrentBranching.CurrentUsageVector.Goto ();
+
+                       if (expr == null)
                                return false;
-                       }
 
-                       if (ec.InFinally) {
-                               Error (724, "A throw statement with no arguments is not allowed inside of a finally clause nested inside of the innermost catch clause");
+                       Type t = expr.Type;
+
+                       if ((t != TypeManager.exception_type) &&
+                           !TypeManager.IsSubclassOf (t, TypeManager.exception_type) &&
+                           !(expr is NullLiteral)) {
+                               Error (155, "The type caught or thrown must be derived from System.Exception");
                                return false;
                        }
                        return true;
@@ -1060,11 +1177,18 @@ namespace Mono.CSharp {
                        }
                }
 
+               public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
+               {
+                       if (expr != null)
+                               expr.MutateHoistedGenericType (storey);
+               }
+
                protected override void CloneTo (CloneContext clonectx, Statement t)
                {
                        Throw target = (Throw) t;
 
-                       target.expr = expr.Clone (clonectx);
+                       if (expr != null)
+                               target.expr = expr.Clone (clonectx);
                }
        }
 
@@ -1089,6 +1213,15 @@ namespace Mono.CSharp {
                {
                        ec.ig.Emit (unwind_protect ? OpCodes.Leave : OpCodes.Br, ec.LoopEnd);
                }
+
+               public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
+               {
+               }
+               
+               protected override void CloneTo (CloneContext clonectx, Statement t)
+               {
+                       // nothing needed
+               }
        }
 
        public class Continue : Statement {
@@ -1112,36 +1245,34 @@ namespace Mono.CSharp {
                {
                        ec.ig.Emit (unwind_protect ? OpCodes.Leave : OpCodes.Br, ec.LoopBegin);
                }
-       }
-
-       public abstract class Variable
-       {
-               public abstract Type Type {
-                       get;
-               }
 
-               public abstract bool HasInstance {
-                       get;
+               public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
+               {
                }
 
-               public abstract bool NeedsTemporary {
-                       get;
+               protected override void CloneTo (CloneContext clonectx, Statement t)
+               {
+                       // nothing needed.
                }
+       }
 
-               public abstract void EmitInstance (EmitContext ec);
-
-               public abstract void Emit (EmitContext ec);
-
-               public abstract void EmitAssign (EmitContext ec);
+       public interface ILocalVariable
+       {
+               void Emit (EmitContext ec);
+               void EmitAssign (EmitContext ec);
+               void EmitAddressOf (EmitContext ec);
+       }
 
-               public abstract void EmitAddressOf (EmitContext ec);
+       public interface IKnownVariable {
+               Block Block { get; }
+               Location Location { get; }
        }
 
        //
        // The information about a user-perceived local variable
        //
-       public class LocalInfo {
-               public Expression Type;
+       public class LocalInfo : IKnownVariable, ILocalVariable {
+               public readonly Expression Type;
 
                public Type VariableType;
                public readonly string Name;
@@ -1149,11 +1280,7 @@ namespace Mono.CSharp {
                public readonly Block Block;
 
                public VariableInfo VariableInfo;
-
-               Variable var;
-               public Variable Variable {
-                       get { return var; }
-               }
+               public HoistedVariable HoistedVariableReference;
 
                [Flags]
                enum Flags : byte {
@@ -1161,7 +1288,6 @@ namespace Mono.CSharp {
                        ReadOnly = 2,
                        Pinned = 4,
                        IsThis = 8,
-                       Captured = 16,
                        AddressTaken = 32,
                        CompilerGenerated = 64,
                        IsConstant = 128
@@ -1194,11 +1320,10 @@ namespace Mono.CSharp {
 
                public void ResolveVariable (EmitContext ec)
                {
-                       Block theblock = Block;
-                       if (theblock.ScopeInfo != null)
-                               var = theblock.ScopeInfo.GetCapturedVariable (this);
+                       if (HoistedVariableReference != null)
+                               return;
 
-                       if (var == null) {
+                       if (builder == null) {
                                if (Pinned)
                                        //
                                        // This is needed to compile on both .NET 1.x and .NET 2.x
@@ -1207,15 +1332,28 @@ namespace Mono.CSharp {
                                        builder = TypeManager.DeclareLocalPinned (ec.ig, VariableType);
                                else
                                        builder = ec.ig.DeclareLocal (VariableType);
-
-                               var = new LocalVariable (this, builder);
                        }
                }
 
-               public void EmitSymbolInfo (EmitContext ec, string name)
+               public void Emit (EmitContext ec)
+               {
+                       ec.ig.Emit (OpCodes.Ldloc, builder);
+               }
+
+               public void EmitAssign (EmitContext ec)
+               {
+                       ec.ig.Emit (OpCodes.Stloc, builder);
+               }
+
+               public void EmitAddressOf (EmitContext ec)
+               {
+                       ec.ig.Emit (OpCodes.Ldloca, builder);
+               }
+
+               public void EmitSymbolInfo (EmitContext ec)
                {
                        if (builder != null)
-                               ec.DefineLocalVariable (name, builder);
+                               ec.DefineLocalVariable (Name, builder);
                }
 
                public bool IsThisAssigned (EmitContext ec)
@@ -1239,22 +1377,18 @@ namespace Mono.CSharp {
 
                public bool Resolve (EmitContext ec)
                {
-                       if (VariableType == null) {
-                               TypeExpr texpr = Type.ResolveAsTypeTerminal (ec, false);
-                               if (texpr == null)
-                                       return false;
+                       if (VariableType != null)
+                               return true;
+
+                       TypeExpr texpr = Type.ResolveAsContextualType (ec, false);
+                       if (texpr == null)
+                               return false;
                                
-                               VariableType = texpr.Type;
-                       }
+                       VariableType = texpr.Type;
 
                        if (TypeManager.IsGenericParameter (VariableType))
                                return true;
 
-                       if (VariableType == TypeManager.void_type) {
-                               Expression.Error_VoidInvalidInTheContext (Location);
-                               return false;
-                       }
-
                        if (VariableType.IsAbstract && VariableType.IsSealed) {
                                FieldBase.Error_VariableOfStaticClass (Location, Name, VariableType);
                                return false;
@@ -1266,43 +1400,19 @@ namespace Mono.CSharp {
                        return true;
                }
 
-               public bool IsCaptured {
-                       get {
-                               return (flags & Flags.Captured) != 0;
-                       }
-
-                       set {
-                               flags |= Flags.Captured;
-                       }
-               }
-
                public bool IsConstant {
-                       get {
-                               return (flags & Flags.IsConstant) != 0;
-                       }
-                       set {
-                               flags |= Flags.IsConstant;
-                       }
+                       get { return (flags & Flags.IsConstant) != 0; }
+                       set { flags |= Flags.IsConstant; }
                }
 
                public bool AddressTaken {
-                       get {
-                               return (flags & Flags.AddressTaken) != 0;
-                       }
-
-                       set {
-                               flags |= Flags.AddressTaken;
-                       }
+                       get { return (flags & Flags.AddressTaken) != 0; }
+                       set { flags |= Flags.AddressTaken; }
                }
 
                public bool CompilerGenerated {
-                       get {
-                               return (flags & Flags.CompilerGenerated) != 0;
-                       }
-
-                       set {
-                               flags |= Flags.CompilerGenerated;
-                       }
+                       get { return (flags & Flags.CompilerGenerated) != 0; }
+                       set { flags |= Flags.CompilerGenerated; }
                }
 
                public override string ToString ()
@@ -1312,18 +1422,12 @@ namespace Mono.CSharp {
                }
 
                public bool Used {
-                       get {
-                               return (flags & Flags.Used) != 0;
-                       }
-                       set {
-                               flags = value ? (flags | Flags.Used) : (unchecked (flags & ~Flags.Used));
-                       }
+                       get { return (flags & Flags.Used) != 0; }
+                       set { flags = value ? (flags | Flags.Used) : (unchecked (flags & ~Flags.Used)); }
                }
 
                public bool ReadOnly {
-                       get {
-                               return (flags & Flags.ReadOnly) != 0;
-                       }
+                       get { return (flags & Flags.ReadOnly) != 0; }
                }
 
                public void SetReadOnlyContext (ReadOnlyContext context)
@@ -1353,73 +1457,39 @@ namespace Mono.CSharp {
                // allocated in a pinned slot with DeclareLocal.
                //
                public bool Pinned {
-                       get {
-                               return (flags & Flags.Pinned) != 0;
-                       }
-                       set {
-                               flags = value ? (flags | Flags.Pinned) : (flags & ~Flags.Pinned);
-                       }
+                       get { return (flags & Flags.Pinned) != 0; }
+                       set { flags = value ? (flags | Flags.Pinned) : (flags & ~Flags.Pinned); }
                }
 
                public bool IsThis {
-                       get {
-                               return (flags & Flags.IsThis) != 0;
-                       }
-                       set {
-                               flags = value ? (flags | Flags.IsThis) : (flags & ~Flags.IsThis);
-                       }
+                       get { return (flags & Flags.IsThis) != 0; }
+                       set { flags = value ? (flags | Flags.IsThis) : (flags & ~Flags.IsThis); }
                }
 
-               protected class LocalVariable : Variable
-               {
-                       public readonly LocalInfo LocalInfo;
-                       LocalBuilder builder;
-
-                       public LocalVariable (LocalInfo local, LocalBuilder builder)
-                       {
-                               this.LocalInfo = local;
-                               this.builder = builder;
-                       }
+               Block IKnownVariable.Block {
+                       get { return Block; }
+               }
 
-                       public override Type Type {
-                               get { return LocalInfo.VariableType; }
-                       }
+               Location IKnownVariable.Location {
+                       get { return Location; }
+               }
 
-                       public override bool HasInstance {
-                               get { return false; }
-                       }
+               public LocalInfo Clone (CloneContext clonectx)
+               {
+                       //
+                       // Variables in anonymous block are not resolved yet
+                       //
+                       if (VariableType == null)
+                               return new LocalInfo (Type.Clone (clonectx), Name, clonectx.LookupBlock (Block), Location);
 
-                       public override bool NeedsTemporary {
-                               get { return false; }
-                       }
-
-                       public override void EmitInstance (EmitContext ec)
-                       {
-                               // Do nothing.
-                       }
-
-                       public override void Emit (EmitContext ec)
-                       {
-                               ec.ig.Emit (OpCodes.Ldloc, builder);
-                       }
-
-                       public override void EmitAssign (EmitContext ec)
-                       {
-                               ec.ig.Emit (OpCodes.Stloc, builder);
-                       }
-
-                       public override void EmitAddressOf (EmitContext ec)
-                       {
-                               ec.ig.Emit (OpCodes.Ldloca, builder);
-                       }
-               }
-
-               public LocalInfo Clone (CloneContext clonectx)
-               {
-                       // Only this kind is created by the parser.
-                       return new LocalInfo (Type.Clone (clonectx), Name, clonectx.LookupBlock (Block), Location);
-               }
-       }
+                       //
+                       // Variables in method block are resolved
+                       //
+                       LocalInfo li = new LocalInfo (null, Name, clonectx.LookupBlock (Block), Location);
+                       li.VariableType = VariableType;
+                       return li;                      
+               }
+       }
 
        /// <summary>
        ///   Block represents a C# block.
@@ -1440,31 +1510,25 @@ namespace Mono.CSharp {
                public readonly Location  StartLocation;
                public Location EndLocation = Location.Null;
 
-               public readonly ToplevelBlock Toplevel;
+               public ExplicitBlock Explicit;
+               public ToplevelBlock Toplevel; // TODO: Use Explicit
 
                [Flags]
-               public enum Flags : ushort {
-                       Implicit  = 1,
-                       Unchecked = 2,
-                       BlockUsed = 4,
-                       VariablesInitialized = 8,
-                       HasRet = 16,
-                       IsDestructor = 32,
-                       IsToplevel = 64,
-                       Unsafe = 128,
-                       HasVarargs = 256, // Used in ToplevelBlock
-                       IsIterator = 512
-
+               public enum Flags : byte {
+                       Unchecked = 1,
+                       BlockUsed = 2,
+                       VariablesInitialized = 4,
+                       HasRet = 8,
+                       IsDestructor = 16,
+                       Unsafe = 32,
+                       IsIterator = 64,
+                       HasStoreyAccess = 128
                }
                protected Flags flags;
 
-               public bool Implicit {
-                       get { return (flags & Flags.Implicit) != 0; }
-               }
-
                public bool Unchecked {
                        get { return (flags & Flags.Unchecked) != 0; }
-                       set { flags |= Flags.Unchecked; }
+                       set { flags = value ? flags | Flags.Unchecked : flags & ~Flags.Unchecked; }
                }
 
                public bool Unsafe {
@@ -1476,8 +1540,6 @@ namespace Mono.CSharp {
                // The statements in this block
                //
                protected ArrayList statements;
-               protected int current_statement;
-               int num_statements;
 
                //
                // An array of Blocks.  We keep track of children just
@@ -1491,16 +1553,17 @@ namespace Mono.CSharp {
                //
                // Labels.  (label, block) pairs.
                //
-               Hashtable labels;
+               protected HybridDictionary labels;
 
                //
                // Keeps track of (name, type) pairs
                //
                IDictionary variables;
+               protected IDictionary range_variables;
 
                //
                // Keeps track of constants
-               Hashtable constants;
+               HybridDictionary constants;
 
                //
                // Temporary variables.
@@ -1512,13 +1575,17 @@ namespace Mono.CSharp {
                //
                Block switch_block;
 
-               ExpressionStatement scope_init;
+               ArrayList scope_initializers;
 
                ArrayList anonymous_children;
 
                protected static int id;
 
                int this_id;
+
+               int assignable_slots;
+               bool unreachable_shown;
+               bool unreachable;
                
                public Block (Block parent)
                        : this (parent, (Flags) 0, Location.Null, Location.Null)
@@ -1534,8 +1601,13 @@ namespace Mono.CSharp {
 
                public Block (Block parent, Flags flags, Location start, Location end)
                {
-                       if (parent != null)
+                       if (parent != null) {
                                parent.AddChild (this);
+
+                               // the appropriate constructors will fixup these fields
+                               Toplevel = parent.Toplevel;
+                               Explicit = parent.Explicit;
+                       }
                        
                        this.Parent = parent;
                        this.flags = flags;
@@ -1543,24 +1615,13 @@ namespace Mono.CSharp {
                        this.EndLocation = end;
                        this.loc = start;
                        this_id = id++;
-                       statements = new ArrayList ();
-
-                       if ((flags & Flags.IsToplevel) != 0)
-                               Toplevel = (ToplevelBlock) this;
-                       else
-                               Toplevel = parent.Toplevel;
-
-                       if (parent != null && Implicit) {
-                               if (parent.known_variables == null)
-                                       parent.known_variables = new Hashtable ();
-                               // share with parent
-                               known_variables = parent.known_variables;
-                       }
+                       statements = new ArrayList (4);
                }
 
                public Block CreateSwitchBlock (Location start)
                {
-                       Block new_block = new Block (this, start, start);
+                       // FIXME: should this be implicit?
+                       Block new_block = new ExplicitBlock (this, start, start);
                        new_block.switch_block = this;
                        return new_block;
                }
@@ -1580,7 +1641,7 @@ namespace Mono.CSharp {
                void AddChild (Block b)
                {
                        if (children == null)
-                               children = new ArrayList ();
+                               children = new ArrayList (1);
                        
                        children.Add (b);
                }
@@ -1593,7 +1654,7 @@ namespace Mono.CSharp {
                protected static void Error_158 (string name, Location loc)
                {
                        Report.Error (158, loc, "The label `{0}' shadows another label " +
-                                     "by the same name in a contained scope.", name);
+                                     "by the same name in a contained scope", name);
                }
 
                /// <summary>
@@ -1614,13 +1675,14 @@ namespace Mono.CSharp {
 
                        Block cur = this;
                        while (cur != null) {
-                               if (cur.DoLookupLabel (name) != null) {
-                                       Report.Error (140, target.loc,
-                                                     "The label `{0}' is a duplicate", name);
+                               LabeledStatement s = cur.DoLookupLabel (name);
+                               if (s != null) {
+                                       Report.SymbolRelatedToPreviousError (s.loc, s.Name);
+                                       Report.Error (140, target.loc, "The label `{0}' is a duplicate", name);
                                        return false;
                                }
 
-                               if (!Implicit)
+                               if (this == Explicit)
                                        break;
 
                                cur = cur.Parent;
@@ -1638,6 +1700,7 @@ namespace Mono.CSharp {
                                                if (s == null)
                                                        continue;
 
+                                               Report.SymbolRelatedToPreviousError (s.loc, s.Name);
                                                Error_158 (name, target.loc);
                                                return false;
                                        }
@@ -1649,7 +1712,7 @@ namespace Mono.CSharp {
                        Toplevel.CheckError158 (name, target.loc);
 
                        if (labels == null)
-                               labels = new Hashtable ();
+                               labels = new HybridDictionary();
 
                        labels.Add (name, target);
                        return true;
@@ -1665,7 +1728,7 @@ namespace Mono.CSharp {
                                return null;
 
                        foreach (Block child in children) {
-                               if (!child.Implicit)
+                               if (Explicit != child.Explicit)
                                        continue;
 
                                s = child.LookupLabel (name);
@@ -1688,59 +1751,22 @@ namespace Mono.CSharp {
                        return null;
                }
 
-               Hashtable known_variables;
-
-               // <summary>
-               //   Marks a variable with name @name as being used in this or a child block.
-               //   If a variable name has been used in a child block, it's illegal to
-               //   declare a variable with the same name in the current block.
-               // </summary>
-               void AddKnownVariable (string name, LocalInfo info)
-               {
-                       if (known_variables == null)
-                               known_variables = new Hashtable ();
-
-                       known_variables [name] = info;
-               }
-
-               LocalInfo GetKnownVariableInfo (string name, bool recurse)
-               {
-                       if (known_variables != null) {
-                               LocalInfo vi = (LocalInfo) known_variables [name];
-                               if (vi != null)
-                                       return vi;
-                       }
-
-                       if (!recurse || (children == null))
-                               return null;
-
-                       foreach (Block block in children) {
-                               LocalInfo vi = block.GetKnownVariableInfo (name, true);
-                               if (vi != null)
-                                       return vi;
-                       }
-
-                       return null;
-               }
-
                public bool CheckInvariantMeaningInBlock (string name, Expression e, Location loc)
                {
                        Block b = this;
-                       LocalInfo kvi = b.GetKnownVariableInfo (name, true);
+                       IKnownVariable kvi = b.Explicit.GetKnownVariable (name);
                        while (kvi == null) {
-                               while (b.Implicit)
-                                       b = b.Parent;
-                               b = b.Parent;
+                               b = b.Explicit.Parent;
                                if (b == null)
                                        return true;
-                               kvi = b.GetKnownVariableInfo (name, false);
+                               kvi = b.Explicit.GetKnownVariable (name);
                        }
 
                        if (kvi.Block == b)
                                return true;
 
                        // Is kvi.Block nested inside 'b'
-                       if (b.known_variables != kvi.Block.known_variables) {
+                       if (b.Explicit != kvi.Block.Explicit) {
                                //
                                // If a variable by the same name it defined in a nested block of this
                                // block, we violate the invariant meaning in a block.
@@ -1767,9 +1793,15 @@ namespace Mono.CSharp {
                        // an indirect check that depends on AddVariable doing its
                        // part in maintaining the invariant-meaning-in-block property.
                        //
-                       if (e is LocalVariableReference || (e is Constant && b.GetLocalInfo (name) != null))
+                       if (e is VariableReference || (e is Constant && b.GetLocalInfo (name) != null))
                                return true;
 
+                       if (this is ToplevelBlock) {
+                               Report.SymbolRelatedToPreviousError (kvi.Location, name);
+                               e.Error_VariableIsUsedBeforeItIsDeclared (name);
+                               return false;
+                       }
+
                        //
                        // Even though we detected the error when the name is used, we
                        // treat it as if the variable declaration was in error.
@@ -1779,144 +1811,93 @@ namespace Mono.CSharp {
                        return false;
                }
 
-               public bool CheckError136_InParents (string name, Location loc)
-               {
-                       for (Block b = Parent; b != null; b = b.Parent) {
-                               if (!b.DoCheckError136 (name, "parent or current", loc))
-                                       return false;
-                       }
-
-                       for (Block b = Toplevel.ContainerBlock; b != null; b = b.Toplevel.ContainerBlock) {
-                               if (!b.CheckError136_InParents (name, loc))
-                                       return false;
-                       }
-
-                       return true;
-               }
-
-               public bool CheckError136_InChildren (string name, Location loc)
-               {
-                       if (!DoCheckError136_InChildren (name, loc))
-                               return false;
-
-                       Block b = this;
-                       while (b.Implicit) {
-                               if (!b.Parent.DoCheckError136_InChildren (name, loc))
-                                       return false;
-                               b = b.Parent;
-                       }
-
-                       return true;
-               }
-
-               protected bool DoCheckError136_InChildren (string name, Location loc)
-               {
-                       if (!DoCheckError136 (name, "child", loc))
-                               return false;
-
-                       if (AnonymousChildren != null) {
-                               foreach (ToplevelBlock child in AnonymousChildren) {
-                                       if (!child.DoCheckError136_InChildren (name, loc))
-                                               return false;
-                               }
-                       }
-
-                       if (children != null) {
-                               foreach (Block child in children) {
-                                       if (!child.DoCheckError136_InChildren (name, loc))
-                                               return false;
-                               }
-                       }
-
-                       return true;
-               }
-
-               public bool CheckError136 (string name, string scope, bool check_parents,
-                                          bool check_children, Location loc)
-               {
-                       if (!DoCheckError136 (name, scope, loc))
-                               return false;
-
-                       if (check_parents) {
-                               if (!CheckError136_InParents (name, loc))
-                                       return false;
-                       }
-
-                       if (check_children) {
-                               if (!CheckError136_InChildren (name, loc))
-                                       return false;
-                       }
-
-                       for (Block c = Toplevel.ContainerBlock; c != null; c = c.Toplevel.ContainerBlock) {
-                               if (!c.DoCheckError136 (name, "parent or current", loc))
-                                       return false;
-                       }
-
-                       return true;
-               }
-
-               protected bool DoCheckError136 (string name, string scope, Location loc)
-               {
-                       LocalInfo vi = GetKnownVariableInfo (name, false);
-                       if (vi != null) {
-                               Report.SymbolRelatedToPreviousError (vi.Location, name);
-                               Error_AlreadyDeclared (loc, name, scope != null ? scope : "child");
-                               return false;
-                       }
-
-                       int idx;
-                       Parameter p = Toplevel.Parameters.GetParameterByName (name, out idx);
-                       if (p != null) {
-                               Report.SymbolRelatedToPreviousError (p.Location, name);
-                               Error_AlreadyDeclared (
-                                       loc, name, scope != null ? scope : "method argument");
-                               return false;
-                       }
-
-                       return true;
-               }
-
                public LocalInfo AddVariable (Expression type, string name, Location l)
                {
                        LocalInfo vi = GetLocalInfo (name);
                        if (vi != null) {
                                Report.SymbolRelatedToPreviousError (vi.Location, name);
-                               if (known_variables == vi.Block.known_variables)
-                                       Report.Error (128, l,
-                                               "A local variable named `{0}' is already defined in this scope", name);
-                               else
+                               if (Explicit == vi.Block.Explicit) {
+                                       if (type == Linq.ImplicitQueryParameter.ImplicitType.Instance && type == vi.Type)
+                                               Error_AlreadyDeclared (l, name);
+                                       else
+                                               Error_AlreadyDeclared (l, name, null);
+                               } else {
                                        Error_AlreadyDeclared (l, name, "parent");
+                               }
+                               return null;
+                       }
+
+                       ToplevelParameterInfo pi = Toplevel.GetParameterInfo (name);
+                       if (pi != null) {
+                               Report.SymbolRelatedToPreviousError (pi.Location, name);
+                               Error_AlreadyDeclared (loc, name,
+                                       pi.Block == Toplevel ? "method argument" : "parent or current");
                                return null;
                        }
+                       
+                       if (Toplevel.GenericMethod != null) {
+                               foreach (TypeParameter tp in Toplevel.GenericMethod.CurrentTypeParameters) {
+                                       if (tp.Name == name) {
+                                               Report.SymbolRelatedToPreviousError (tp);
+                                               Error_AlreadyDeclaredTypeParameter (loc, name);
+                                               return null;
+                                       }
+                               }
+                       }                       
 
-                       if (!CheckError136 (name, null, true, true, l))
+                       IKnownVariable kvi = Explicit.GetKnownVariable (name);
+                       if (kvi != null) {
+                               Report.SymbolRelatedToPreviousError (kvi.Location, name);
+                               Error_AlreadyDeclared (l, name, "child");
                                return null;
+                       }
 
                        vi = new LocalInfo (type, name, this, l);
-                       Variables.Add (name, vi);
-                       AddKnownVariable (name, vi);
+                       AddVariable (vi);
 
                        if ((flags & Flags.VariablesInitialized) != 0)
                                throw new InternalErrorException ("block has already been resolved");
 
                        return vi;
                }
+               
+               protected virtual void AddVariable (LocalInfo li)
+               {
+                       Variables.Add (li.Name, li);
+                       Explicit.AddKnownVariable (li.Name, li);
+               }
 
-               void Error_AlreadyDeclared (Location loc, string var, string reason)
+               protected virtual void Error_AlreadyDeclared (Location loc, string var, string reason)
                {
+                       if (reason == null) {
+                               Error_AlreadyDeclared (loc, var);
+                               return;
+                       }
+                       
                        Report.Error (136, loc, "A local variable named `{0}' cannot be declared " +
                                      "in this scope because it would give a different meaning " +
                                      "to `{0}', which is already used in a `{1}' scope " +
                                      "to denote something else", var, reason);
                }
 
+               protected virtual void Error_AlreadyDeclared (Location loc, string name)
+               {
+                       Report.Error (128, loc,
+                               "A local variable named `{0}' is already defined in this scope", name);
+               }
+                                       
+               protected virtual void Error_AlreadyDeclaredTypeParameter (Location loc, string name)
+               {
+                       GenericMethod.Error_ParameterNameCollision (loc, name, "local variable");
+               }                                       
+
                public bool AddConstant (Expression type, string name, Expression value, Location l)
                {
                        if (AddVariable (type, name, l) == null)
                                return false;
                        
                        if (constants == null)
-                               constants = new Hashtable ();
+                               constants = new HybridDictionary();
 
                        constants.Add (name, value);
 
@@ -1945,13 +1926,21 @@ namespace Mono.CSharp {
 
                public LocalInfo GetLocalInfo (string name)
                {
+                       LocalInfo ret;
                        for (Block b = this; b != null; b = b.Parent) {
                                if (b.variables != null) {
-                                       LocalInfo ret = b.variables [name] as LocalInfo;
+                                       ret = (LocalInfo) b.variables [name];
+                                       if (ret != null)
+                                               return ret;
+                               }
+
+                               if (b.range_variables != null) {
+                                       ret = (LocalInfo) b.range_variables [name];
                                        if (ret != null)
                                                return ret;
                                }
                        }
+
                        return null;
                }
 
@@ -1972,16 +1961,22 @@ namespace Mono.CSharp {
                        }
                        return null;
                }
-               
-               public void AddStatement (Statement s)
+
+               //
+               // It should be used by expressions which require to
+               // register a statement during resolve process.
+               //
+               public void AddScopeStatement (StatementExpression s)
                {
-                       statements.Add (s);
-                       flags |= Flags.BlockUsed;
+                       if (scope_initializers == null)
+                               scope_initializers = new ArrayList ();
+
+                       scope_initializers.Add (s);
                }
                
-               public void InsertStatementAfterCurrent (Statement statement)
+               public void AddStatement (Statement s)
                {
-                       statements.Insert (current_statement + 1, statement);
+                       statements.Add (s);
                        flags |= Flags.BlockUsed;
                }
 
@@ -2007,42 +2002,15 @@ namespace Mono.CSharp {
                        flags |= Flags.IsDestructor;
                }
 
-               VariableMap param_map;
-
-               public VariableMap ParameterMap {
-                       get {
-                               if ((flags & Flags.VariablesInitialized) == 0){
-                                       throw new Exception ("Variables have not been initialized yet");
-                               }
-
-                               return param_map;
-                       }
-               }
-
-               int assignable_slots;
                public int AssignableSlots {
                        get {
-                               if ((flags & Flags.VariablesInitialized) == 0){
-                                       throw new Exception ("Variables have not been initialized yet");
-                               }
+// TODO: Re-enable                     
+//                             if ((flags & Flags.VariablesInitialized) == 0)
+//                                     throw new Exception ("Variables have not been initialized yet");
                                return assignable_slots;
                        }
                }
 
-               protected ScopeInfo scope_info;
-
-               public ScopeInfo ScopeInfo {
-                       get { return scope_info; }
-               }
-
-               public ScopeInfo CreateScopeInfo ()
-               {
-                       if (scope_info == null)
-                               scope_info = ScopeInfo.CreateScope (this);
-
-                       return scope_info;
-               }
-
                public ArrayList AnonymousChildren {
                        get { return anonymous_children; }
                }
@@ -2068,8 +2036,12 @@ namespace Mono.CSharp {
                                LocalInfo vi = (LocalInfo) de.Value;
                                Type variable_type = vi.VariableType;
 
-                               if (variable_type == null)
+                               if (variable_type == null) {
+                                       if (vi.Type is VarExpr)
+                                               Report.Error (822, vi.Type.Location, "An implicitly typed local variable cannot be a constant");
+
                                        continue;
+                               }
 
                                Expression cv = (Expression) constants [name];
                                if (cv == null)
@@ -2101,10 +2073,10 @@ namespace Mono.CSharp {
 
                                e = ce.ConvertImplicitly (variable_type);
                                if (e == null) {
-                                       if (!variable_type.IsValueType && variable_type != TypeManager.string_type && !ce.IsDefaultValue)
+                                       if (TypeManager.IsReferenceType (variable_type))
                                                Const.Error_ConstantCanBeInitializedWithNullOnly (vi.Location, vi.Name);
                                        else
-                                               ce.Error_ValueCannotBeConverted (null, vi.Location, variable_type, false);
+                                               ce.Error_ValueCannotBeConverted (ec, vi.Location, variable_type, false);
                                        continue;
                                }
 
@@ -2113,33 +2085,31 @@ namespace Mono.CSharp {
                        }
                }
 
-               protected void ResolveMeta (ToplevelBlock toplevel, EmitContext ec, Parameters ip)
+               protected void ResolveMeta (EmitContext ec, int offset)
                {
-                       Report.Debug (64, "BLOCK RESOLVE META", this, Parent, toplevel);
+                       Report.Debug (64, "BLOCK RESOLVE META", this, Parent);
 
                        // If some parent block was unsafe, we remain unsafe even if this block
                        // isn't explicitly marked as such.
                        using (ec.With (EmitContext.Flags.InUnsafe, ec.InUnsafe | Unsafe)) {
-                               param_map = new VariableMap (ip);
                                flags |= Flags.VariablesInitialized;
 
-                               int offset = Parent == null ? 0 : Parent.AssignableSlots;
                                if (variables != null) {
                                        foreach (LocalInfo li in variables.Values) {
-                                               if (li.Resolve (ec)) {
-                                                       li.VariableInfo = new VariableInfo (li, offset);
-                                                       offset += li.VariableInfo.Length;
-                                               }
+                                               if (!li.Resolve (ec))
+                                                       continue;
+                                               li.VariableInfo = new VariableInfo (li, offset);
+                                               offset += li.VariableInfo.Length;
                                        }
                                }
                                assignable_slots = offset;
 
                                DoResolveConstants (ec);
 
-                               if (children != null) {
-                                       foreach (Block b in children)
-                                               b.ResolveMeta (toplevel, ec, ip);
-                               }
+                               if (children == null)
+                                       return;
+                               foreach (Block b in children)
+                                       b.ResolveMeta (ec, offset);
                        }
                }
 
@@ -2148,56 +2118,43 @@ namespace Mono.CSharp {
                //
                public virtual void EmitMeta (EmitContext ec)
                {
-                       Report.Debug (64, "BLOCK EMIT META", this, Parent, Toplevel, ScopeInfo, ec);
-                       if (ScopeInfo != null) {
-                               scope_init = ScopeInfo.GetScopeInitializer (ec);
-                               Report.Debug (64, "BLOCK EMIT META #1", this, Toplevel, ScopeInfo,
-                                             ec, scope_init);
-                       }
-
                        if (variables != null){
                                foreach (LocalInfo vi in variables.Values)
                                        vi.ResolveVariable (ec);
                        }
 
                        if (temporary_variables != null) {
-                               foreach (LocalInfo vi in temporary_variables)
-                                       vi.ResolveVariable (ec);
+                               for (int i = 0; i < temporary_variables.Count; i++)
+                                       ((LocalInfo)temporary_variables[i]).ResolveVariable(ec);
                        }
 
-                       if (children != null){
-                               foreach (Block b in children)
-                                       b.EmitMeta (ec);
+                       if (children != null) {
+                               for (int i = 0; i < children.Count; i++)
+                                       ((Block)children[i]).EmitMeta(ec);
                        }
                }
 
-               void UsageWarning (FlowBranching.UsageVector vector)
+               void UsageWarning ()
                {
-                       string name;
-
-                       if ((variables != null) && (RootContext.WarningLevel >= 3)) {
-                               foreach (DictionaryEntry de in variables){
-                                       LocalInfo vi = (LocalInfo) de.Value;
+                       if (variables == null || Report.WarningLevel < 3)
+                               return;
 
-                                       if (vi.Used)
-                                               continue;
+                       foreach (DictionaryEntry de in variables) {
+                               LocalInfo vi = (LocalInfo) de.Value;
 
-                                       name = (string) de.Key;
+                               if (!vi.Used) {
+                                       string name = (string) de.Key;
 
                                        // vi.VariableInfo can be null for 'catch' variables
-                                       if (vi.VariableInfo != null && vector.IsAssigned (vi.VariableInfo, true)){
+                                       if (vi.VariableInfo != null && vi.VariableInfo.IsEverAssigned)
                                                Report.Warning (219, 3, vi.Location, "The variable `{0}' is assigned but its value is never used", name);
-                                       } else {
+                                       else
                                                Report.Warning (168, 3, vi.Location, "The variable `{0}' is declared but never used", name);
-                                       }
                                }
                        }
                }
 
-               bool unreachable_shown;
-               bool unreachable;
-
-               private void CheckPossibleMistakenEmptyStatement (Statement s)
+               static void CheckPossibleMistakenEmptyStatement (Statement s)
                {
                        Statement body;
 
@@ -2216,10 +2173,12 @@ namespace Mono.CSharp {
                                body = ((Foreach) s).Statement;
                        else if (s is While)
                                body = ((While) s).Statement;
-                       else if (s is Using)
-                               body = ((Using) s).Statement;
                        else if (s is Fixed)
                                body = ((Fixed) s).Statement;
+                       else if (s is Using)
+                               body = ((Using) s).EmbeddedStatement;
+                       else if (s is UsingTemporary)
+                               body = ((UsingTemporary) s).Statement;
                        else
                                return;
 
@@ -2245,12 +2204,13 @@ namespace Mono.CSharp {
                        // from the beginning of the function.  The outer Resolve() that detected the unreachability is
                        // responsible for handling the situation.
                        //
-                       for (current_statement = 0; current_statement < statements.Count; current_statement++) {
-                               Statement s = (Statement) statements [current_statement];
+                       int statement_count = statements.Count;
+                       for (int ix = 0; ix < statement_count; ix++){
+                               Statement s = (Statement) statements [ix];
                                // Check possible empty statement (CS0642)
-                               if (RootContext.WarningLevel >= 3 &&
-                                       current_statement + 1 < statements.Count &&
-                                               statements [current_statement + 1] is Block)
+                               if (Report.WarningLevel >= 3 &&
+                                       ix + 1 < statement_count &&
+                                               statements [ix + 1] is Block)
                                        CheckPossibleMistakenEmptyStatement (s);
 
                                //
@@ -2260,13 +2220,14 @@ namespace Mono.CSharp {
                                        if (s is EmptyStatement)
                                                continue;
 
-                                       if (s is Block)
-                                               ((Block) s).unreachable = true;
-
                                        if (!unreachable_shown && !(s is LabeledStatement)) {
                                                Report.Warning (162, 2, s.loc, "Unreachable code detected");
                                                unreachable_shown = true;
                                        }
+
+                                       Block c_block = s as Block;
+                                       if (c_block != null)
+                                               c_block.unreachable = c_block.unreachable_shown = true;
                                }
 
                                //
@@ -2279,14 +2240,15 @@ namespace Mono.CSharp {
 
                                if (!s.Resolve (ec)) {
                                        ok = false;
-                                       statements [current_statement] = EmptyStatement.Value;
+                                       if (ec.IsInProbingMode)
+                                               break;
+
+                                       statements [ix] = EmptyStatement.Value;
                                        continue;
                                }
 
                                if (unreachable && !(s is LabeledStatement) && !(s is Block))
-                                       statements [current_statement] = EmptyStatement.Value;
-
-                               num_statements = current_statement + 1;
+                                       statements [ix] = EmptyStatement.Value;
 
                                unreachable = ec.CurrentBranching.CurrentUsageVector.IsUnreachable;
                                if (unreachable && s is LabeledStatement)
@@ -2294,41 +2256,31 @@ namespace Mono.CSharp {
                        }
 
                        Report.Debug (4, "RESOLVE BLOCK DONE", StartLocation,
-                                     ec.CurrentBranching, statements.Count, num_statements);
-
-                       if (!ok)
-                               return false;
+                                     ec.CurrentBranching, statement_count);
 
                        while (ec.CurrentBranching is FlowBranchingLabeled)
                                ec.EndFlowBranching ();
 
-                       FlowBranching.UsageVector vector = ec.DoEndFlowBranching ();
+                       bool flow_unreachable = ec.EndFlowBranching ();
 
                        ec.CurrentBlock = prev_block;
 
+                       if (flow_unreachable)
+                               flags |= Flags.HasRet;
+
                        // If we're a non-static `struct' constructor which doesn't have an
                        // initializer, then we must initialize all of the struct's fields.
-                       if ((flags & Flags.IsToplevel) != 0 && 
-                           !Toplevel.IsThisAssigned (ec) &&
-                           !vector.IsUnreachable)
+                       if (this == Toplevel && !Toplevel.IsThisAssigned (ec) && !flow_unreachable)
                                ok = false;
 
-                       if ((labels != null) && (RootContext.WarningLevel >= 2)) {
+                       if ((labels != null) && (Report.WarningLevel >= 2)) {
                                foreach (LabeledStatement label in labels.Values)
                                        if (!label.HasBeenReferenced)
-                                               Report.Warning (164, 2, label.loc,
-                                                               "This label has not been referenced");
+                                               Report.Warning (164, 2, label.loc, "This label has not been referenced");
                        }
 
-                       Report.Debug (4, "RESOLVE BLOCK DONE #2", StartLocation, vector);
-
-                       if (vector.IsUnreachable)
-                               flags |= Flags.HasRet;
-
-                       if (ok && (errors == Report.Errors)) {
-                               if (RootContext.WarningLevel >= 3)
-                                       UsageWarning (vector);
-                       }
+                       if (ok && errors == Report.Errors)
+                               UsageWarning ();
 
                        return ok;
                }
@@ -2350,17 +2302,8 @@ namespace Mono.CSharp {
                
                protected override void DoEmit (EmitContext ec)
                {
-                       for (int ix = 0; ix < num_statements; ix++){
+                       for (int ix = 0; ix < statements.Count; ix++){
                                Statement s = (Statement) statements [ix];
-
-                               // Check whether we are the last statement in a
-                               // top-level block.
-
-                               if (((Parent == null) || Implicit) && (ix+1 == num_statements) && !(s is Block))
-                                       ec.IsLastStatement = true;
-                               else
-                                       ec.IsLastStatement = false;
-
                                s.Emit (ec);
                        }
                }
@@ -2368,52 +2311,58 @@ namespace Mono.CSharp {
                public override void Emit (EmitContext ec)
                {
                        Block prev_block = ec.CurrentBlock;
-
                        ec.CurrentBlock = this;
 
-                       bool emit_debug_info = (CodeGen.SymbolWriter != null);
-                       bool is_lexical_block = !Implicit && (Parent != null);
+                       if (scope_initializers != null) {
+                               SymbolWriter.OpenCompilerGeneratedBlock (ec.ig);
+
+                               bool omit_debug_info = ec.OmitDebuggingInfo;
+                               ec.OmitDebuggingInfo = true;
+                               foreach (StatementExpression s in scope_initializers)
+                                       s.Emit (ec);
+                               ec.OmitDebuggingInfo = omit_debug_info;
 
-                       if (emit_debug_info) {
-                               if (is_lexical_block)
-                                       ec.BeginScope ();
+                               SymbolWriter.CloseCompilerGeneratedBlock (ec.ig);
                        }
-                       ec.Mark (StartLocation, true);
-                       if (scope_init != null)
-                               scope_init.EmitStatement (ec);
+
+                       ec.Mark (StartLocation);
                        DoEmit (ec);
-                       ec.Mark (EndLocation, true); 
 
-                       if (emit_debug_info) {
-                               if (is_lexical_block)
-                                       ec.EndScope ();
+                       if (SymbolWriter.HasSymbolWriter)
+                               EmitSymbolInfo (ec);
 
-                               if (variables != null) {
-                                       foreach (DictionaryEntry de in variables) {
-                                               string name = (string) de.Key;
-                                               LocalInfo vi = (LocalInfo) de.Value;
+                       ec.CurrentBlock = prev_block;
+               }
 
-                                               vi.EmitSymbolInfo (ec, name);
-                                       }
+               protected virtual void EmitSymbolInfo (EmitContext ec)
+               {
+                       if (variables != null) {
+                               foreach (LocalInfo vi in variables.Values) {
+                                       vi.EmitSymbolInfo (ec);
                                }
                        }
+               }
 
-                       ec.CurrentBlock = prev_block;
+               public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
+               {
+                       MutateVariables (storey);
+
+                       foreach (Statement s in statements)
+                               s.MutateHoistedGenericType (storey);
                }
 
-               //
-               // Returns true if we ar ea child of `b'.
-               //
-               public bool IsChildOf (Block b)
+               void MutateVariables (AnonymousMethodStorey storey)
                {
-                       Block current = this;
-                       
-                       do {
-                               if (current.Parent == b)
-                                       return true;
-                               current = current.Parent;
-                       } while (current != null);
-                       return false;
+                       if (variables != null) {
+                               foreach (LocalInfo vi in variables.Values) {
+                                       vi.VariableType = storey.MutateType (vi.VariableType);
+                               }
+                       }
+
+                       if (temporary_variables != null) {
+                               foreach (LocalInfo vi in temporary_variables)
+                                       vi.VariableType = storey.MutateType (vi.VariableType);
+                       }
                }
 
                public override string ToString ()
@@ -2425,22 +2374,12 @@ namespace Mono.CSharp {
                {
                        Block target = (Block) t;
 
+                       clonectx.AddBlockMap (this, target);
+
+                       //target.Toplevel = (ToplevelBlock) clonectx.LookupBlock (Toplevel);
+                       target.Explicit = (ExplicitBlock) clonectx.LookupBlock (Explicit);
                        if (Parent != null)
-                               target.Parent = clonectx.LookupBlock (Parent);
-                       
-                       target.statements = new ArrayList ();
-                       if (target.children != null){
-                               target.children = new ArrayList ();
-                               foreach (Block b in children){
-                                       Block newblock = (Block) b.Clone (clonectx);
-
-                                       target.children.Add (newblock);
-                               }
-                               
-                       }
-
-                       foreach (Statement s in statements)
-                               target.statements.Add (s.Clone (clonectx));
+                               target.Parent = clonectx.RemapBlockCopy (Parent);
 
                        if (variables != null){
                                target.variables = new Hashtable ();
@@ -2452,103 +2391,241 @@ namespace Mono.CSharp {
                                }
                        }
 
+                       target.statements = new ArrayList (statements.Count);
+                       foreach (Statement s in statements)
+                               target.statements.Add (s.Clone (clonectx));
+
+                       if (target.children != null){
+                               target.children = new ArrayList (children.Count);
+                               foreach (Block b in children){
+                                       target.children.Add (clonectx.LookupBlock (b));
+                               }
+                       }
+
                        //
                        // TODO: labels, switch_block, constants (?), anonymous_children
                        //
                }
        }
 
-       //
-       // A toplevel block contains extra information, the split is done
-       // only to separate information that would otherwise bloat the more
-       // lightweight Block.
-       //
-       // In particular, this was introduced when the support for Anonymous
-       // Methods was implemented. 
-       // 
-       public class ToplevelBlock : Block {
-               //
-               // Pointer to the host of this anonymous method, or null
-               // if we are the topmost block
-               //
-               Block container;
-               ToplevelBlock child;    
-               GenericMethod generic;
-               FlowBranchingToplevel top_level_branching;
-               AnonymousContainer anonymous_container;
-               RootScopeInfo root_scope;
+       public class ExplicitBlock : Block {
+               HybridDictionary known_variables;
+               protected AnonymousMethodStorey am_storey;
 
-               public bool HasVarargs {
-                       get { return (flags & Flags.HasVarargs) != 0; }
-                       set { flags |= Flags.HasVarargs; }
+               public ExplicitBlock (Block parent, Location start, Location end)
+                       : this (parent, (Flags) 0, start, end)
+               {
                }
 
-               public bool IsIterator {
-                       get { return (flags & Flags.IsIterator) != 0; }
+               public ExplicitBlock (Block parent, Flags flags, Location start, Location end)
+                       : base (parent, flags, start, end)
+               {
+                       this.Explicit = this;
+               }
+
+               // <summary>
+               //   Marks a variable with name @name as being used in this or a child block.
+               //   If a variable name has been used in a child block, it's illegal to
+               //   declare a variable with the same name in the current block.
+               // </summary>
+               internal void AddKnownVariable (string name, IKnownVariable info)
+               {
+                       if (known_variables == null)
+                               known_variables = new HybridDictionary();
+
+                       known_variables [name] = info;
+
+                       if (Parent != null)
+                               Parent.Explicit.AddKnownVariable (name, info);
+               }
+
+               public AnonymousMethodStorey AnonymousMethodStorey {
+                       get { return am_storey; }
                }
 
                //
-               // The parameters for the block.
+               // Creates anonymous method storey in current block
                //
-               Parameters parameters;
-               public Parameters Parameters {
-                       get { return parameters; }
+               public AnonymousMethodStorey CreateAnonymousMethodStorey (EmitContext ec)
+               {
+                       //
+                       // When referencing a variable in iterator storey from children anonymous method
+                       //
+                       if (Toplevel.am_storey is IteratorStorey) {
+                               ec.CurrentAnonymousMethod.AddStoreyReference (Toplevel.am_storey);
+                               return Toplevel.am_storey;
+                       }
+
+                       //
+                       // An iterator has only 1 storey block
+                       //
+                       if (ec.CurrentIterator != null)
+                           return ec.CurrentIterator.Storey;
+
+                       if (am_storey == null) {
+                               MemberBase mc = ec.ResolveContext as MemberBase;
+                               GenericMethod gm = mc == null ? null : mc.GenericMethod;
+
+                               //
+                               // Create anonymous method storey for this block
+                               //
+                               am_storey = new AnonymousMethodStorey (this, ec.TypeContainer, mc, gm, "AnonStorey");
+                       }
+
+                       //
+                       // Creates a link between this block and the anonymous method
+                       //
+                       // An anonymous method can reference variables from any outer block, but they are
+                       // hoisted in their own ExplicitBlock. When more than one block is referenced we
+                       // need to create another link between those variable storeys
+                       //
+                       ec.CurrentAnonymousMethod.AddStoreyReference (am_storey);
+                       return am_storey;
                }
 
-               public bool CompleteContexts (EmitContext ec)
+               public override void Emit (EmitContext ec)
                {
-                       Report.Debug (64, "TOPLEVEL COMPLETE CONTEXTS", this,
-                                     container, root_scope);
+                       if (am_storey != null)
+                               am_storey.EmitHoistedVariables (ec);
 
-                       if (root_scope != null)
-                               root_scope.LinkScopes ();
+                       bool emit_debug_info = SymbolWriter.HasSymbolWriter && Parent != null && !(am_storey is IteratorStorey);
+                       if (emit_debug_info)
+                               ec.BeginScope ();
 
-                       if ((container == null) && (root_scope != null)) {
-                               Report.Debug (64, "TOPLEVEL COMPLETE CONTEXTS #1", this,
-                                             root_scope);
+                       base.Emit (ec);
 
-                               if (root_scope.DefineType () == null)
-                                       return false;
-                               if (!root_scope.ResolveType ())
-                                       return false;
-                               if (!root_scope.ResolveMembers ())
-                                       return false;
-                               if (!root_scope.DefineMembers ())
-                                       return false;
+                       if (emit_debug_info)
+                               ec.EndScope ();
+               }
+
+               public override void EmitMeta (EmitContext ec)
+               {
+                       //
+                       // Creates anonymous method storey
+                       //
+                       if (am_storey != null) {
+                               if (ec.CurrentAnonymousMethod != null && ec.CurrentAnonymousMethod.Storey != null) {
+                                       am_storey.ChangeParentStorey (ec.CurrentAnonymousMethod.Storey);
+                               }
+
+                               am_storey.DefineType ();
+                               am_storey.ResolveType ();                               
+                               am_storey.DefineMembers ();
+                               am_storey.Parent.PartialContainer.AddCompilerGeneratedClass (am_storey);
                        }
 
-                       return true;
+                       base.EmitMeta (ec);
                }
 
-               public GenericMethod GenericMethod {
-                       get { return generic; }
+               internal IKnownVariable GetKnownVariable (string name)
+               {
+                       return known_variables == null ? null : (IKnownVariable) known_variables [name];
                }
 
-               public ToplevelBlock Container {
-                       get { return container != null ? container.Toplevel : null; }
+               public void PropagateStoreyReference (AnonymousMethodStorey s)
+               {
+                       if (Parent != null && am_storey != s) {
+                               if (am_storey != null)
+                                       am_storey.AddParentStoreyReference (s);
+
+                               Parent.Explicit.PropagateStoreyReference (s);
+                       }
+               }
+
+               public override bool Resolve (EmitContext ec)
+               {
+                       bool ok = base.Resolve (ec);
+
+                       //
+                       // Discard an anonymous method storey when this block has no hoisted variables
+                       //
+                       if (am_storey != null && !am_storey.HasHoistedVariables) {
+                               am_storey.Undo ();
+                               am_storey = null;
+                       }
+
+                       return ok;
+               }
+
+               protected override void CloneTo (CloneContext clonectx, Statement t)
+               {
+                       ExplicitBlock target = (ExplicitBlock) t;
+                       target.known_variables = null;
+                       base.CloneTo (clonectx, t);
+               }
+       }
+
+       public class ToplevelParameterInfo : IKnownVariable {
+               public readonly ToplevelBlock Block;
+               public readonly int Index;
+               public VariableInfo VariableInfo;
+
+               Block IKnownVariable.Block {
+                       get { return Block; }
+               }
+               public Parameter Parameter {
+                       get { return Block.Parameters [Index]; }
+               }
+
+               public Type ParameterType {
+                       get { return Block.Parameters.Types [Index]; }
                }
 
-               public Block ContainerBlock {
-                       get { return container; }
+               public Location Location {
+                       get { return Parameter.Location; }
                }
 
-               public AnonymousContainer AnonymousContainer {
-                       get { return anonymous_container; }
-                       set { anonymous_container = value; }
+               public ToplevelParameterInfo (ToplevelBlock block, int idx)
+               {
+                       this.Block = block;
+                       this.Index = idx;
                }
+       }
+
+       //
+       // A toplevel block contains extra information, the split is done
+       // only to separate information that would otherwise bloat the more
+       // lightweight Block.
+       //
+       // In particular, this was introduced when the support for Anonymous
+       // Methods was implemented. 
+       // 
+       public class ToplevelBlock : ExplicitBlock {
+               GenericMethod generic;
+               FlowBranchingToplevel top_level_branching;
+               Parameters parameters;
+               ToplevelParameterInfo[] parameter_info;
+               LocalInfo this_variable;
+
+               public HoistedVariable HoistedThisVariable;
 
                //
-               // Parent is only used by anonymous blocks to link back to their
-               // parents
+               // The parameters for the block.
                //
-               public ToplevelBlock (Block container, Parameters parameters, Location start) :
-                       this (container, (Flags) 0, parameters, start)
+               public Parameters Parameters {
+                       get { return parameters; }
+               }
+
+               public GenericMethod GenericMethod {
+                       get { return generic; }
+               }
+
+               public bool HasStoreyAccess {
+                       set { flags = value ? flags | Flags.HasStoreyAccess : flags & ~Flags.HasStoreyAccess; }
+                       get { return (flags & Flags.HasStoreyAccess) != 0;  }
+               }
+
+               public ToplevelBlock Container {
+                       get { return Parent == null ? null : Parent.Toplevel; }
+               }
+
+               public ToplevelBlock (Block parent, Parameters parameters, Location start) :
+                       this (parent, (Flags) 0, parameters, start)
                {
                }
 
-               public ToplevelBlock (Block container, Parameters parameters, GenericMethod generic,
-                                     Location start) :
-                       this (container, parameters, start)
+               public ToplevelBlock (Block parent, Parameters parameters, GenericMethod generic, Location start) :
+                       this (parent, parameters, start)
                {
                        this.generic = generic;
                }
@@ -2558,22 +2635,42 @@ namespace Mono.CSharp {
                {
                }
 
-               public ToplevelBlock (Flags flags, Parameters parameters, Location start) :
+               ToplevelBlock (Flags flags, Parameters parameters, Location start) :
                        this (null, flags, parameters, start)
                {
                }
 
-               public ToplevelBlock (Block container, Flags flags, Parameters parameters, Location start) :
-                       base (null, flags | Flags.IsToplevel, start, Location.Null)
+               // We use 'Parent' to hook up to the containing block, but don't want to register the current block as a child.
+               // So, we use a two-stage setup -- first pass a null parent to the base constructor, and then override 'Parent'.
+               public ToplevelBlock (Block parent, Flags flags, Parameters parameters, Location start) :
+                       base (null, flags, start, Location.Null)
                {
+                       this.Toplevel = this;
+
                        this.parameters = parameters == null ? Parameters.EmptyReadOnlyParameters : parameters;
-                       this.container = container;
+                       this.Parent = parent;
+                       if (parent != null)
+                               parent.AddAnonymousChild (this);
+
+                       if (!this.parameters.IsEmpty)
+                               ProcessParameters ();
                }
 
                public ToplevelBlock (Location loc) : this (null, (Flags) 0, null, loc)
                {
                }
 
+               protected override void CloneTo (CloneContext clonectx, Statement t)
+               {
+                       ToplevelBlock target = (ToplevelBlock) t;
+                       base.CloneTo (clonectx, t);
+
+                       if (parameters.Count != 0)
+                               target.parameter_info = new ToplevelParameterInfo [parameters.Count];
+                       for (int i = 0; i < parameters.Count; ++i)
+                               target.parameter_info [i] = new ToplevelParameterInfo (target, i);
+               }
+
                public bool CheckError158 (string name, Location loc)
                {
                        if (AnonymousChildren != null) {
@@ -2591,10 +2688,50 @@ namespace Mono.CSharp {
                        return true;
                }
 
+               public virtual Expression GetTransparentIdentifier (string name)
+               {
+                       return null;
+               }
+
+               void ProcessParameters ()
+               {
+                       int n = parameters.Count;
+                       parameter_info = new ToplevelParameterInfo [n];
+                       for (int i = 0; i < n; ++i) {
+                               parameter_info [i] = new ToplevelParameterInfo (this, i);
+
+                               Parameter p = parameters [i];
+                               if (p == null)
+                                       continue;
+
+                               string name = p.Name;
+                               LocalInfo vi = GetLocalInfo (name);
+                               if (vi != null) {
+                                       Report.SymbolRelatedToPreviousError (vi.Location, name);
+                                       Error_AlreadyDeclared (loc, name, "parent or current");
+                                       continue;
+                               }
+
+                               ToplevelParameterInfo pi = Parent == null ? null : Parent.Toplevel.GetParameterInfo (name);
+                               if (pi != null) {
+                                       Report.SymbolRelatedToPreviousError (pi.Location, name);
+                                       Error_AlreadyDeclared (loc, name, "parent or current");
+                                       continue;
+                               }
+
+                               AddKnownVariable (name, parameter_info [i]);
+                       }
+
+                       // mark this block as "used" so that we create local declarations in a sub-block
+                       // FIXME: This appears to uncover a lot of bugs
+                       //this.Use ();
+               }
+
                bool DoCheckError158 (string name, Location loc)
                {
                        LabeledStatement s = LookupLabel (name);
                        if (s != null) {
+                               Report.SymbolRelatedToPreviousError (s.loc, s.Name);
                                Error_158 (name, loc);
                                return false;
                        }
@@ -2602,105 +2739,64 @@ namespace Mono.CSharp {
                        return true;
                }
 
-               public RootScopeInfo CreateRootScope (TypeContainer host)
+               public override Expression CreateExpressionTree (EmitContext ec)
                {
-                       if (root_scope != null)
-                               return root_scope;
+                       if (statements.Count == 1)
+                               return ((Statement) statements [0]).CreateExpressionTree (ec);
 
-                       if (Container == null)
-                               root_scope = new RootScopeInfo (
-                                       this, host, generic, StartLocation);
-
-                       if (scope_info != null)
-                               throw new InternalErrorException ();
-
-                       scope_info = root_scope;
-                       return root_scope;
+                       return base.CreateExpressionTree (ec);
                }
 
-               public void CreateIteratorHost (RootScopeInfo root)
+               //
+               // Reformats this block to be top-level iterator block
+               //
+               public IteratorStorey ChangeToIterator (Iterator iterator, ToplevelBlock source)
                {
-                       Report.Debug (64, "CREATE ITERATOR HOST", this, root,
-                                     container, root_scope);
+                       // Create block with original statements
+                       ExplicitBlock iter_block = new ExplicitBlock (this, flags, StartLocation, EndLocation);
+                       IsIterator = true;
 
-                       if ((container != null) || (root_scope != null))
-                               throw new InternalErrorException ();
+                       // TODO: Change to iter_block.statements = statements;
+                       foreach (Statement stmt in source.statements)
+                               iter_block.AddStatement (stmt);
+                       labels = source.labels;
+                       
+                       AddStatement (new IteratorStatement (iterator, iter_block));
 
-                       scope_info = root_scope = root;
-               }
+                       source.statements = new ArrayList (1);
+                       source.AddStatement (new Return (iterator, iterator.Location));
+                       source.IsIterator = false;
 
-               public RootScopeInfo RootScope {
-                       get {
-                               if (root_scope != null)
-                                       return root_scope;
-                               else if (Container != null)
-                                       return Container.RootScope;
-                               else
-                                       return null;
-                       }
+                       IteratorStorey iterator_storey = new IteratorStorey (iterator);
+                       source.am_storey = iterator_storey;
+                       return iterator_storey;
                }
 
                public FlowBranchingToplevel TopLevelBranching {
                        get { return top_level_branching; }
                }
 
-               //
-               // This is used if anonymous methods are used inside an iterator
-               // (see 2test-22.cs for an example).
-               //
-               // The AnonymousMethod is created while parsing - at a time when we don't
-               // know yet that we're inside an iterator, so it's `Container' is initially
-               // null.  Later on, when resolving the iterator, we need to move the
-               // anonymous method into that iterator.
-               //
-               public void ReParent (ToplevelBlock new_parent)
-               {
-                       container = new_parent;
-                       Parent = new_parent;
-                       new_parent.child = this;
-               }
-
                //
                // Returns a `ParameterReference' for the given name, or null if there
                // is no such parameter
                //
                public ParameterReference GetParameterReference (string name, Location loc)
                {
-                       Parameter par;
-                       int idx;
-
-                       for (ToplevelBlock t = this; t != null; t = t.Container) {
-                               Parameters pars = t.Parameters;
-                               par = pars.GetParameterByName (name, out idx);
-                               if (par != null)
-                                       return new ParameterReference (par, this, idx, loc);
-                       }
-                       return null;
+                       ToplevelParameterInfo p = GetParameterInfo (name);
+                       return p == null ? null : new ParameterReference (this, p, loc);
                }
 
-               //
-               // Whether the parameter named `name' is local to this block, 
-               // or false, if the parameter belongs to an encompassing block.
-               //
-               public bool IsLocalParameter (string name)
-               {
-                       return Parameters.GetParameterByName (name) != null;
-               }
-               
-               //
-               // Whether the `name' is a parameter reference
-               //
-               public bool IsParameterReference (string name)
+               public ToplevelParameterInfo GetParameterInfo (string name)
                {
+                       int idx;
                        for (ToplevelBlock t = this; t != null; t = t.Container) {
-                               if (t.IsLocalParameter (name))
-                                       return true;
+                               Parameter par = t.Parameters.GetParameterByName (name, out idx);
+                               if (par != null)
+                                       return t.parameter_info [idx];
                        }
-                       return false;
+                       return null;
                }
 
-               LocalInfo this_variable = null;
-
                // <summary>
                //   Returns the "this" instance variable of this block.
                //   See AddThisVariable() for more information.
@@ -2709,7 +2805,6 @@ namespace Mono.CSharp {
                        get { return this_variable; }
                }
 
-
                // <summary>
                //   This is used by non-static `struct' constructors which do not have an
                //   initializer - in this case, the constructor must initialize all of the
@@ -2730,6 +2825,11 @@ namespace Mono.CSharp {
                        return this_variable;
                }
 
+               public bool IsIterator {
+                       get { return (flags & Flags.IsIterator) != 0; }
+                       set { flags = value ? flags | Flags.IsIterator : flags & ~Flags.IsIterator; }
+               }
+
                public bool IsThisAssigned (EmitContext ec)
                {
                        return this_variable == null || this_variable.IsThisAssigned (ec);
@@ -2738,6 +2838,7 @@ namespace Mono.CSharp {
                public bool ResolveMeta (EmitContext ec, Parameters ip)
                {
                        int errors = Report.Errors;
+                       int orig_count = parameters.Count;
 
                        if (top_level_branching != null)
                                return true;
@@ -2745,67 +2846,78 @@ namespace Mono.CSharp {
                        if (ip != null)
                                parameters = ip;
 
-                       if (!IsIterator && (container != null) && (parameters != null)) {
-                               foreach (Parameter p in parameters.FixedParameters) {
-                                       if (!CheckError136_InParents (p.Name, loc))
-                                               return false;
-                               }
-                       }
+                       // Assert: orig_count != parameter.Count => orig_count == 0
+                       if (orig_count != 0 && orig_count != parameters.Count)
+                               throw new InternalErrorException ("parameter information mismatch");
+
+                       int offset = Parent == null ? 0 : Parent.AssignableSlots;
 
-                       ResolveMeta (this, ec, ip);
+                       for (int i = 0; i < orig_count; ++i) {
+                               Parameter.Modifier mod = parameters.FixedParameters [i].ModFlags;
+
+                               if ((mod & Parameter.Modifier.OUT) != Parameter.Modifier.OUT)
+                                       continue;
+
+                               VariableInfo vi = new VariableInfo (ip, i, offset);
+                               parameter_info [i].VariableInfo = vi;
+                               offset += vi.Length;
+                       }
 
-                       if (child != null)
-                               child.ResolveMeta (this, ec, ip);
+                       ResolveMeta (ec, offset);
 
                        top_level_branching = ec.StartFlowBranching (this);
 
                        return Report.Errors == errors;
                }
 
-               public override void EmitMeta (EmitContext ec)
+               // <summary>
+               //   Check whether all `out' parameters have been assigned.
+               // </summary>
+               public void CheckOutParameters (FlowBranching.UsageVector vector, Location loc)
                {
-                       base.EmitMeta (ec);
-                       parameters.ResolveVariable (this);
-               }
+                       if (vector.IsUnreachable)
+                               return;
 
-               public void MakeIterator (Iterator iterator)
-               {
-                       flags |= Flags.IsIterator;
+                       int n = parameter_info == null ? 0 : parameter_info.Length;
 
-                       Block block = new Block (this);
-                       foreach (Statement stmt in statements)
-                               block.AddStatement (stmt);
-                       statements = new ArrayList ();
-                       statements.Add (new MoveNextStatement (iterator, block));
-               }
+                       for (int i = 0; i < n; i++) {
+                               VariableInfo var = parameter_info [i].VariableInfo;
 
-               protected class MoveNextStatement : Statement {
-                       Iterator iterator;
-                       Block block;
+                               if (var == null)
+                                       continue;
 
-                       public MoveNextStatement (Iterator iterator, Block block)
-                       {
-                               this.iterator = iterator;
-                               this.block = block;
-                               this.loc = iterator.Location;
-                       }
+                               if (vector.IsAssigned (var, false))
+                                       continue;
 
-                       public override bool Resolve (EmitContext ec)
-                       {
-                               return block.Resolve (ec);
+                               Report.Error (177, loc, "The out parameter `{0}' must be assigned to before control leaves the current method",
+                                       var.Name);
                        }
+               }
 
-                       protected override void DoEmit (EmitContext ec)
-                       {
-                               iterator.EmitMoveNext (ec, block);
-                       }
+               public override void EmitMeta (EmitContext ec)
+               {
+                       parameters.ResolveVariable ();
+
+                       // Avoid declaring an IL variable for this_variable since it is not accessed
+                       // from the generated IL
+                       if (this_variable != null)
+                               Variables.Remove ("this");
+                       base.EmitMeta (ec);
                }
 
-               public override string ToString ()
+               protected override void EmitSymbolInfo (EmitContext ec)
+               {
+                       AnonymousExpression ae = ec.CurrentAnonymousMethod;
+                       if ((ae != null) && (ae.Storey != null))
+                               SymbolWriter.DefineScopeVariable (ae.Storey.ID);
+
+                       base.EmitSymbolInfo (ec);
+               }
+
+               public override void Emit (EmitContext ec)
                {
-                       return String.Format ("{0} ({1}:{2}{3}:{4})", GetType (), ID, StartLocation,
-                                             root_scope, anonymous_container != null ?
-                                             anonymous_container.Scope : null);
+                       base.Emit (ec);
+                       ec.Mark (EndLocation);
                }
        }
        
@@ -2836,6 +2948,10 @@ namespace Mono.CSharp {
                        }
                }
 
+               public Location Location {
+                       get { return loc; }
+               }
+
                public object Converted {
                        get {
                                return converted;
@@ -2886,8 +3002,8 @@ namespace Mono.CSharp {
                                converted = NullStringCase;
                                return true;
                        }
-
-                       c = c.ImplicitConversionRequired (required_type, loc);
+                       
+                       c = c.ImplicitConversionRequired (ec, required_type, loc);
                        if (c == null)
                                return false;
 
@@ -2895,19 +3011,17 @@ namespace Mono.CSharp {
                        return true;
                }
 
-               public void Erorr_AlreadyOccurs (Type switchType, SwitchLabel collisionWith)
+               public void Error_AlreadyOccurs (Type switch_type, SwitchLabel collision_with)
                {
                        string label;
                        if (converted == null)
                                label = "default";
                        else if (converted == NullStringCase)
                                label = "null";
-                       else if (TypeManager.IsEnumType (switchType)) 
-                               label = TypeManager.CSharpEnumValue (switchType, converted);
                        else
                                label = converted.ToString ();
                        
-                       Report.SymbolRelatedToPreviousError (collisionWith.loc, null);
+                       Report.SymbolRelatedToPreviousError (collision_with.loc, null);
                        Report.Error (152, loc, "The label `case {0}:' already occurs in this switch statement", label);
                }
 
@@ -2960,9 +3074,14 @@ namespace Mono.CSharp {
                Label null_target;
                Expression new_expr;
                bool is_constant;
+               bool has_null_case;
                SwitchSection constant_section;
                SwitchSection default_section;
 
+               ExpressionStatement string_dictionary;
+               FieldExpr switch_cache_field;
+               static int unique_counter;
+
 #if GMCS_SOURCE
                //
                // Nullable Types support for GMCS.
@@ -3011,7 +3130,7 @@ namespace Mono.CSharp {
                //
                Expression SwitchGoverningType (EmitContext ec, Expression expr)
                {
-                       Type t = TypeManager.DropGenericTypeArguments (expr.Type);
+                       Type t = expr.Type;
 
                        if (t == TypeManager.byte_type ||
                            t == TypeManager.sbyte_type ||
@@ -3024,7 +3143,7 @@ namespace Mono.CSharp {
                            t == TypeManager.char_type ||
                            t == TypeManager.string_type ||
                            t == TypeManager.bool_type ||
-                           t.IsSubclassOf (TypeManager.enum_type))
+                           TypeManager.IsEnumType (t))
                                return expr;
 
                        if (allowed_types == null){
@@ -3038,8 +3157,7 @@ namespace Mono.CSharp {
                                        TypeManager.int64_type,
                                        TypeManager.uint64_type,
                                        TypeManager.char_type,
-                                       TypeManager.string_type,
-                                       TypeManager.bool_type
+                                       TypeManager.string_type
                                };
                        }
 
@@ -3065,10 +3183,7 @@ namespace Mono.CSharp {
                                        continue;
 
                                if (converted != null){
-                                       Report.ExtraInformation (
-                                               loc,
-                                               String.Format ("reason: more than one conversion to an integral type exist for type {0}",
-                                                              TypeManager.CSharpName (expr.Type)));
+                                       Report.ExtraInformation (loc, "(Ambiguous implicit user defined conversion in previous ");
                                        return null;
                                }
 
@@ -3095,7 +3210,7 @@ namespace Mono.CSharp {
                                foreach (SwitchLabel sl in ss.Labels){
                                        if (sl.Label == null){
                                                if (default_section != null){
-                                                       sl.Erorr_AlreadyOccurs (SwitchType, (SwitchLabel)default_section.Labels [0]);
+                                                       sl.Error_AlreadyOccurs (SwitchType, (SwitchLabel)default_section.Labels [0]);
                                                        error = true;
                                                }
                                                default_section = ss;
@@ -3108,10 +3223,13 @@ namespace Mono.CSharp {
                                        }
                                        
                                        object key = sl.Converted;
+                                       if (key == SwitchLabel.NullStringCase)
+                                               has_null_case = true;
+
                                        try {
                                                Elements.Add (key, sl);
                                        } catch (ArgumentException) {
-                                               sl.Erorr_AlreadyOccurs (SwitchType, (SwitchLabel)Elements [key]);
+                                               sl.Error_AlreadyOccurs (SwitchType, (SwitchLabel)Elements [key]);
                                                error = true;
                                        }
                                }
@@ -3170,22 +3288,22 @@ namespace Mono.CSharp {
                // structure used to hold blocks of keys while calculating table switch
                class KeyBlock : IComparable
                {
-                       public KeyBlock (long _nFirst)
+                       public KeyBlock (long _first)
                        {
-                               nFirst = nLast = _nFirst;
+                               first = last = _first;
                        }
-                       public long nFirst;
-                       public long nLast;
-                       public ArrayList rgKeys = null;
+                       public long first;
+                       public long last;
+                       public ArrayList element_keys = null;
                        // how many items are in the bucket
                        public int Size = 1;
                        public int Length
                        {
-                               get { return (int) (nLast - nFirst + 1); }
+                               get { return (int) (last - first + 1); }
                        }
-                       public static long TotalLength (KeyBlock kbFirst, KeyBlock kbLast)
+                       public static long TotalLength (KeyBlock kb_first, KeyBlock kb_last)
                        {
-                               return kbLast.nLast - kbFirst.nFirst + 1;
+                               return kb_last.last - kb_first.first + 1;
                        }
                        public int CompareTo (object obj)
                        {
@@ -3193,7 +3311,7 @@ namespace Mono.CSharp {
                                int nLength = Length;
                                int nLengthOther = kb.Length;
                                if (nLengthOther == nLength)
-                                       return (int) (kb.nFirst - nFirst);
+                                       return (int) (kb.first - first);
                                return nLength - nLengthOther;
                        }
                }
@@ -3208,96 +3326,99 @@ namespace Mono.CSharp {
                /// <param name="ec"></param>
                /// <param name="val"></param>
                /// <returns></returns>
-               void TableSwitchEmit (EmitContext ec, LocalBuilder val)
+               void TableSwitchEmit (EmitContext ec, Expression val)
                {
-                       int cElements = Elements.Count;
-                       object [] rgKeys = new object [cElements];
-                       Elements.Keys.CopyTo (rgKeys, 0);
-                       Array.Sort (rgKeys);
+                       int element_count = Elements.Count;
+                       object [] element_keys = new object [element_count];
+                       Elements.Keys.CopyTo (element_keys, 0);
+                       Array.Sort (element_keys);
 
                        // initialize the block list with one element per key
-                       ArrayList rgKeyBlocks = new ArrayList ();
-                       foreach (object key in rgKeys)
-                               rgKeyBlocks.Add (new KeyBlock (System.Convert.ToInt64 (key)));
+                       ArrayList key_blocks = new ArrayList (element_count);
+                       foreach (object key in element_keys)
+                               key_blocks.Add (new KeyBlock (System.Convert.ToInt64 (key)));
 
-                       KeyBlock kbCurr;
+                       KeyBlock current_kb;
                        // iteratively merge the blocks while they are at least half full
                        // there's probably a really cool way to do this with a tree...
-                       while (rgKeyBlocks.Count > 1)
+                       while (key_blocks.Count > 1)
                        {
-                               ArrayList rgKeyBlocksNew = new ArrayList ();
-                               kbCurr = (KeyBlock) rgKeyBlocks [0];
-                               for (int ikb = 1; ikb < rgKeyBlocks.Count; ikb++)
+                               ArrayList key_blocks_new = new ArrayList ();
+                               current_kb = (KeyBlock) key_blocks [0];
+                               for (int ikb = 1; ikb < key_blocks.Count; ikb++)
                                {
-                                       KeyBlock kb = (KeyBlock) rgKeyBlocks [ikb];
-                                       if ((kbCurr.Size + kb.Size) * 2 >=  KeyBlock.TotalLength (kbCurr, kb))
+                                       KeyBlock kb = (KeyBlock) key_blocks [ikb];
+                                       if ((current_kb.Size + kb.Size) * 2 >=  KeyBlock.TotalLength (current_kb, kb))
                                        {
                                                // merge blocks
-                                               kbCurr.nLast = kb.nLast;
-                                               kbCurr.Size += kb.Size;
+                                               current_kb.last = kb.last;
+                                               current_kb.Size += kb.Size;
                                        }
                                        else
                                        {
                                                // start a new block
-                                               rgKeyBlocksNew.Add (kbCurr);
-                                               kbCurr = kb;
+                                               key_blocks_new.Add (current_kb);
+                                               current_kb = kb;
                                        }
                                }
-                               rgKeyBlocksNew.Add (kbCurr);
-                               if (rgKeyBlocks.Count == rgKeyBlocksNew.Count)
+                               key_blocks_new.Add (current_kb);
+                               if (key_blocks.Count == key_blocks_new.Count)
                                        break;
-                               rgKeyBlocks = rgKeyBlocksNew;
+                               key_blocks = key_blocks_new;
                        }
 
                        // initialize the key lists
-                       foreach (KeyBlock kb in rgKeyBlocks)
-                               kb.rgKeys = new ArrayList ();
+                       foreach (KeyBlock kb in key_blocks)
+                               kb.element_keys = new ArrayList ();
 
                        // fill the key lists
                        int iBlockCurr = 0;
-                       if (rgKeyBlocks.Count > 0) {
-                               kbCurr = (KeyBlock) rgKeyBlocks [0];
-                               foreach (object key in rgKeys)
+                       if (key_blocks.Count > 0) {
+                               current_kb = (KeyBlock) key_blocks [0];
+                               foreach (object key in element_keys)
                                {
-                                       bool fNextBlock = (key is UInt64) ? (ulong) key > (ulong) kbCurr.nLast :
-                                               System.Convert.ToInt64 (key) > kbCurr.nLast;
-                                       if (fNextBlock)
-                                               kbCurr = (KeyBlock) rgKeyBlocks [++iBlockCurr];
-                                       kbCurr.rgKeys.Add (key);
+                                       bool next_block = (key is UInt64) ? (ulong) key > (ulong) current_kb.last :
+                                               System.Convert.ToInt64 (key) > current_kb.last;
+                                       if (next_block)
+                                               current_kb = (KeyBlock) key_blocks [++iBlockCurr];
+                                       current_kb.element_keys.Add (key);
                                }
                        }
 
                        // sort the blocks so we can tackle the largest ones first
-                       rgKeyBlocks.Sort ();
+                       key_blocks.Sort ();
 
                        // okay now we can start...
                        ILGenerator ig = ec.ig;
-                       Label lblEnd = ig.DefineLabel ();       // at the end ;-)
-                       Label lblDefault = ig.DefineLabel ();
+                       Label lbl_end = ig.DefineLabel ();      // at the end ;-)
+                       Label lbl_default = default_target;
 
-                       Type typeKeys = null;
-                       if (rgKeys.Length > 0)
-                               typeKeys = rgKeys [0].GetType ();       // used for conversions
+                       Type type_keys = null;
+                       if (element_keys.Length > 0)
+                               type_keys = element_keys [0].GetType ();        // used for conversions
 
                        Type compare_type;
                        
                        if (TypeManager.IsEnumType (SwitchType))
-                               compare_type = TypeManager.EnumToUnderlying (SwitchType);
+                               compare_type = TypeManager.GetEnumUnderlyingType (SwitchType);
                        else
                                compare_type = SwitchType;
                        
-                       for (int iBlock = rgKeyBlocks.Count - 1; iBlock >= 0; --iBlock)
+                       for (int iBlock = key_blocks.Count - 1; iBlock >= 0; --iBlock)
                        {
-                               KeyBlock kb = ((KeyBlock) rgKeyBlocks [iBlock]);
-                               lblDefault = (iBlock == 0) ? DefaultTarget : ig.DefineLabel ();
+                               KeyBlock kb = ((KeyBlock) key_blocks [iBlock]);
+                               lbl_default = (iBlock == 0) ? default_target : ig.DefineLabel ();
                                if (kb.Length <= 2)
                                {
-                                       foreach (object key in kb.rgKeys)
-                                       {
-                                               ig.Emit (OpCodes.Ldloc, val);
-                                               EmitObjectInteger (ig, key);
+                                       foreach (object key in kb.element_keys) {
                                                SwitchLabel sl = (SwitchLabel) Elements [key];
-                                               ig.Emit (OpCodes.Beq, sl.GetILLabel (ec));
+                                               if (key is int && (int) key == 0) {
+                                                       val.EmitBranchable (ec, sl.GetILLabel (ec), false);
+                                               } else {
+                                                       val.Emit (ec);
+                                                       EmitObjectInteger (ig, key);
+                                                       ig.Emit (OpCodes.Beq, sl.GetILLabel (ec));
+                                               }
                                        }
                                }
                                else
@@ -3310,18 +3431,18 @@ namespace Mono.CSharp {
                                                // TODO: optimize constant/I4 cases
 
                                                // check block range (could be > 2^31)
-                                               ig.Emit (OpCodes.Ldloc, val);
-                                               EmitObjectInteger (ig, System.Convert.ChangeType (kb.nFirst, typeKeys));
-                                               ig.Emit (OpCodes.Blt, lblDefault);
-                                               ig.Emit (OpCodes.Ldloc, val);
-                                               EmitObjectInteger (ig, System.Convert.ChangeType (kb.nLast, typeKeys));
-                                               ig.Emit (OpCodes.Bgt, lblDefault);
+                                               val.Emit (ec);
+                                               EmitObjectInteger (ig, System.Convert.ChangeType (kb.first, type_keys));
+                                               ig.Emit (OpCodes.Blt, lbl_default);
+                                               val.Emit (ec);
+                                               EmitObjectInteger (ig, System.Convert.ChangeType (kb.last, type_keys));
+                                               ig.Emit (OpCodes.Bgt, lbl_default);
 
                                                // normalize range
-                                               ig.Emit (OpCodes.Ldloc, val);
-                                               if (kb.nFirst != 0)
+                                               val.Emit (ec);
+                                               if (kb.first != 0)
                                                {
-                                                       EmitObjectInteger (ig, System.Convert.ChangeType (kb.nFirst, typeKeys));
+                                                       EmitObjectInteger (ig, System.Convert.ChangeType (kb.first, type_keys));
                                                        ig.Emit (OpCodes.Sub);
                                                }
                                                ig.Emit (OpCodes.Conv_I4);      // assumes < 2^31 labels!
@@ -3329,16 +3450,16 @@ namespace Mono.CSharp {
                                        else
                                        {
                                                // normalize range
-                                               ig.Emit (OpCodes.Ldloc, val);
-                                               int nFirst = (int) kb.nFirst;
-                                               if (nFirst > 0)
+                                               val.Emit (ec);
+                                               int first = (int) kb.first;
+                                               if (first > 0)
                                                {
-                                                       IntConstant.EmitInt (ig, nFirst);
+                                                       IntConstant.EmitInt (ig, first);
                                                        ig.Emit (OpCodes.Sub);
                                                }
-                                               else if (nFirst < 0)
+                                               else if (first < 0)
                                                {
-                                                       IntConstant.EmitInt (ig, -nFirst);
+                                                       IntConstant.EmitInt (ig, -first);
                                                        ig.Emit (OpCodes.Add);
                                                }
                                        }
@@ -3346,26 +3467,26 @@ namespace Mono.CSharp {
                                        // first, build the list of labels for the switch
                                        int iKey = 0;
                                        int cJumps = kb.Length;
-                                       Label [] rgLabels = new Label [cJumps];
+                                       Label [] switch_labels = new Label [cJumps];
                                        for (int iJump = 0; iJump < cJumps; iJump++)
                                        {
-                                               object key = kb.rgKeys [iKey];
-                                               if (System.Convert.ToInt64 (key) == kb.nFirst + iJump)
+                                               object key = kb.element_keys [iKey];
+                                               if (System.Convert.ToInt64 (key) == kb.first + iJump)
                                                {
                                                        SwitchLabel sl = (SwitchLabel) Elements [key];
-                                                       rgLabels [iJump] = sl.GetILLabel (ec);
+                                                       switch_labels [iJump] = sl.GetILLabel (ec);
                                                        iKey++;
                                                }
                                                else
-                                                       rgLabels [iJump] = lblDefault;
+                                                       switch_labels [iJump] = lbl_default;
                                        }
                                        // emit the switch opcode
-                                       ig.Emit (OpCodes.Switch, rgLabels);
+                                       ig.Emit (OpCodes.Switch, switch_labels);
                                }
 
                                // mark the default for this block
                                if (iBlock != 0)
-                                       ig.MarkLabel (lblDefault);
+                                       ig.MarkLabel (lbl_default);
                        }
 
                        // TODO: find the default case and emit it here,
@@ -3373,140 +3494,36 @@ namespace Mono.CSharp {
                        //       make sure to mark other labels in the default section
 
                        // the last default just goes to the end
-                       ig.Emit (OpCodes.Br, lblDefault);
+                       if (element_keys.Length > 0)
+                               ig.Emit (OpCodes.Br, lbl_default);
 
                        // now emit the code for the sections
-                       bool fFoundDefault = false;
-                       bool fFoundNull = false;
-                       foreach (SwitchSection ss in Sections)
-                       {
-                               foreach (SwitchLabel sl in ss.Labels)
-                                       if (sl.Converted == SwitchLabel.NullStringCase)
-                                               fFoundNull = true;
-                       }
+                       bool found_default = false;
 
-                       foreach (SwitchSection ss in Sections)
-                       {
-                               foreach (SwitchLabel sl in ss.Labels)
-                               {
-                                       ig.MarkLabel (sl.GetILLabel (ec));
-                                       ig.MarkLabel (sl.GetILLabelCode (ec));
-                                       if (sl.Converted == SwitchLabel.NullStringCase)
+                       foreach (SwitchSection ss in Sections) {
+                               foreach (SwitchLabel sl in ss.Labels) {
+                                       if (sl.Converted == SwitchLabel.NullStringCase) {
                                                ig.MarkLabel (null_target);
-                                       else if (sl.Label == null) {
-                                               ig.MarkLabel (lblDefault);
-                                               fFoundDefault = true;
-                                               if (!fFoundNull)
+                                       else if (sl.Label == null) {
+                                               ig.MarkLabel (lbl_default);
+                                               found_default = true;
+                                               if (!has_null_case)
                                                        ig.MarkLabel (null_target);
                                        }
+                                       ig.MarkLabel (sl.GetILLabel (ec));
+                                       ig.MarkLabel (sl.GetILLabelCode (ec));
                                }
                                ss.Block.Emit (ec);
                        }
                        
-                       if (!fFoundDefault) {
-                               ig.MarkLabel (lblDefault);
-                       }
-                       ig.MarkLabel (lblEnd);
-               }
-               //
-               // This simple emit switch works, but does not take advantage of the
-               // `switch' opcode. 
-               // TODO: remove non-string logic from here
-               // TODO: binary search strings?
-               //
-               void SimpleSwitchEmit (EmitContext ec, LocalBuilder val)
-               {
-                       ILGenerator ig = ec.ig;
-                       Label end_of_switch = ig.DefineLabel ();
-                       Label next_test = ig.DefineLabel ();
-                       bool first_test = true;
-                       bool pending_goto_end = false;
-                       bool null_marked = false;
-                       bool null_found;
-                       int section_count = Sections.Count;
-
-                       // TODO: implement switch optimization for string by using Hashtable
-                       //if (SwitchType == TypeManager.string_type && section_count > 7)
-                       //      Console.WriteLine ("Switch optimization possible " + loc);
-
-                       ig.Emit (OpCodes.Ldloc, val);
-                       
-                       if (Elements.Contains (SwitchLabel.NullStringCase)){
-                               ig.Emit (OpCodes.Brfalse, null_target);
-                       } else
-                               ig.Emit (OpCodes.Brfalse, default_target);
-                       
-                       ig.Emit (OpCodes.Ldloc, val);
-                       ig.Emit (OpCodes.Call, TypeManager.string_isinterned_string);
-                       ig.Emit (OpCodes.Stloc, val);
-
-                       for (int section = 0; section < section_count; section++){
-                               SwitchSection ss = (SwitchSection) Sections [section];
-
-                               if (ss == default_section)
-                                       continue;
-
-                               Label sec_begin = ig.DefineLabel ();
-
-                               ig.Emit (OpCodes.Nop);
-
-                               if (pending_goto_end)
-                                       ig.Emit (OpCodes.Br, end_of_switch);
-
-                               int label_count = ss.Labels.Count;
-                               null_found = false;
-                               for (int label = 0; label < label_count; label++){
-                                       SwitchLabel sl = (SwitchLabel) ss.Labels [label];
-                                       ig.MarkLabel (sl.GetILLabel (ec));
-                                       
-                                       if (!first_test){
-                                               ig.MarkLabel (next_test);
-                                               next_test = ig.DefineLabel ();
-                                       }
-                                       //
-                                       // If we are the default target
-                                       //
-                                       if (sl.Label != null){
-                                               object lit = sl.Converted;
-
-                                               if (lit == SwitchLabel.NullStringCase){
-                                                       null_found = true;
-                                                       if (label + 1 == label_count)
-                                                               ig.Emit (OpCodes.Br, next_test);
-                                                       continue;
-                                               }
-                                               
-                                               ig.Emit (OpCodes.Ldloc, val);
-                                               ig.Emit (OpCodes.Ldstr, (string)lit);
-                                               if (label_count == 1)
-                                                       ig.Emit (OpCodes.Bne_Un, next_test);
-                                               else {
-                                                       if (label+1 == label_count)
-                                                               ig.Emit (OpCodes.Bne_Un, next_test);
-                                                       else
-                                                               ig.Emit (OpCodes.Beq, sec_begin);
-                                               }
-                                       }
-                               }
-                               if (null_found) {
+                       if (!found_default) {
+                               ig.MarkLabel (lbl_default);
+                               if (!has_null_case) {
                                        ig.MarkLabel (null_target);
-                                       null_marked = true;
                                }
-                               ig.MarkLabel (sec_begin);
-                               foreach (SwitchLabel sl in ss.Labels)
-                                       ig.MarkLabel (sl.GetILLabelCode (ec));
-
-                               ss.Block.Emit (ec);
-                               pending_goto_end = !ss.Block.HasRet;
-                               first_test = false;
                        }
-                       ig.MarkLabel (next_test);
-                       ig.MarkLabel (default_target);
-                       if (!null_marked)
-                               ig.MarkLabel (null_target);
-                       if (default_section != null)
-                               default_section.Block.Emit (ec);
-                       ig.MarkLabel (end_of_switch);
+                       
+                       ig.MarkLabel (lbl_end);
                }
 
                SwitchSection FindSection (SwitchLabel label)
@@ -3521,6 +3538,17 @@ namespace Mono.CSharp {
                        return null;
                }
 
+               public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
+               {
+                       foreach (SwitchSection ss in Sections)
+                               ss.Block.MutateHoistedGenericType (storey);
+               }
+
+               public static void Reset ()
+               {
+                       unique_counter = 0;
+               }
+
                public override bool Resolve (EmitContext ec)
                {
                        Expr = Expr.Resolve (ec);
@@ -3548,7 +3576,7 @@ namespace Mono.CSharp {
                        SwitchType = new_expr.Type;
 
                        if (RootContext.Version == LanguageVersion.ISO_1 && SwitchType == TypeManager.bool_type) {
-                               Report.FeatureIsNotISO1 (loc, "switch expression of boolean type");
+                               Report.FeatureIsNotAvailable (loc, "switch expression of boolean type");
                                return false;
                        }
 
@@ -3576,6 +3604,7 @@ namespace Mono.CSharp {
                        }
 
                        bool first = true;
+                       bool ok = true;
                        foreach (SwitchSection ss in Sections){
                                if (!first)
                                        ec.CurrentBranching.CreateSibling (
@@ -3588,11 +3617,12 @@ namespace Mono.CSharp {
                                        // one single section - mark all the others as
                                        // unreachable.
                                        ec.CurrentBranching.CurrentUsageVector.Goto ();
-                                       if (!ss.Block.ResolveUnreachable (ec, true))
-                                               return false;
+                                       if (!ss.Block.ResolveUnreachable (ec, true)) {
+                                               ok = false;
+                                       }
                                } else {
                                        if (!ss.Block.Resolve (ec))
-                                               return false;
+                                               ok = false;
                                }
                        }
 
@@ -3605,8 +3635,127 @@ namespace Mono.CSharp {
 
                        Report.Debug (1, "END OF SWITCH BLOCK", loc, ec.CurrentBranching);
 
+                       if (!ok)
+                               return false;
+
+                       if (SwitchType == TypeManager.string_type && !is_constant) {
+                               // TODO: Optimize single case, and single+default case
+                               ResolveStringSwitchMap (ec);
+                       }
+
                        return true;
                }
+
+               void ResolveStringSwitchMap (EmitContext ec)
+               {
+                       FullNamedExpression string_dictionary_type;
+#if GMCS_SOURCE
+                       MemberAccess system_collections_generic = new MemberAccess (new MemberAccess (
+                               new QualifiedAliasMember (QualifiedAliasMember.GlobalAlias, "System", loc), "Collections", loc), "Generic", loc);
+
+                       string_dictionary_type = new MemberAccess (system_collections_generic, "Dictionary",
+                               new TypeArguments (loc,
+                                       new TypeExpression (TypeManager.string_type, loc),
+                                       new TypeExpression (TypeManager.int32_type, loc)), loc);
+#else
+                       MemberAccess system_collections_generic = new MemberAccess (
+                               new QualifiedAliasMember (QualifiedAliasMember.GlobalAlias, "System", loc), "Collections", loc);
+
+                       string_dictionary_type = new MemberAccess (system_collections_generic, "Hashtable", loc);
+#endif
+                       Field field = new Field (ec.TypeContainer, string_dictionary_type,
+                               Modifiers.STATIC | Modifiers.PRIVATE | Modifiers.COMPILER_GENERATED,
+                               CompilerGeneratedClass.MakeName (null, "f", "switch$map", unique_counter++), null, loc);
+                       if (!field.Define ())
+                               return;
+                       ec.TypeContainer.PartialContainer.AddField (field);
+
+                       ArrayList init = new ArrayList ();
+                       int counter = 0;
+                       Elements.Clear ();
+                       string value = null;
+                       foreach (SwitchSection section in Sections) {
+                               foreach (SwitchLabel sl in section.Labels) {
+                                       if (sl.Label == null || sl.Converted == SwitchLabel.NullStringCase) {
+                                               value = null;
+                                               continue;
+                                       }
+
+                                       value = (string) sl.Converted;
+                                       ArrayList init_args = new ArrayList (2);
+                                       init_args.Add (new StringLiteral (value, sl.Location));
+                                       init_args.Add (new IntConstant (counter, loc));
+                                       init.Add (new CollectionElementInitializer (init_args, loc));
+                               }
+
+                               if (value == null)
+                                       continue;
+
+                               Elements.Add (counter, section.Labels [0]);
+                               ++counter;
+                       }
+
+                       ArrayList args = new ArrayList (1);
+                       args.Add (new Argument (new IntConstant (Sections.Count, loc)));
+                       Expression initializer = new NewInitialize (string_dictionary_type, args,
+                               new CollectionOrObjectInitializers (init, loc), loc);
+
+                       switch_cache_field = new FieldExpr (field.FieldBuilder, loc);
+                       string_dictionary = new SimpleAssign (switch_cache_field, initializer.Resolve (ec));
+               }
+
+               void DoEmitStringSwitch (LocalTemporary value, EmitContext ec)
+               {
+                       ILGenerator ig = ec.ig;
+                       Label l_initialized = ig.DefineLabel ();
+
+                       //
+                       // Skip initialization when value is null
+                       //
+                       value.EmitBranchable (ec, null_target, false);
+
+                       //
+                       // Check if string dictionary is initialized and initialize
+                       //
+                       switch_cache_field.EmitBranchable (ec, l_initialized, true);
+                       string_dictionary.EmitStatement (ec);
+                       ig.MarkLabel (l_initialized);
+
+                       LocalTemporary string_switch_variable = new LocalTemporary (TypeManager.int32_type);
+
+#if GMCS_SOURCE
+                       ArrayList get_value_args = new ArrayList (2);
+                       get_value_args.Add (new Argument (value));
+                       get_value_args.Add (new Argument (string_switch_variable, Argument.AType.Out));
+                       Expression get_item = new Invocation (new MemberAccess (switch_cache_field, "TryGetValue", loc), get_value_args).Resolve (ec);
+                       if (get_item == null)
+                               return;
+
+                       //
+                       // A value was not found, go to default case
+                       //
+                       get_item.EmitBranchable (ec, default_target, false);
+#else
+                       ArrayList get_value_args = new ArrayList (1);
+                       get_value_args.Add (value);
+
+                       Expression get_item = new IndexerAccess (new ElementAccess (switch_cache_field, get_value_args), loc).Resolve (ec);
+                       if (get_item == null)
+                               return;
+
+                       LocalTemporary get_item_object = new LocalTemporary (TypeManager.object_type);
+                       get_item_object.EmitAssign (ec, get_item, true, false);
+                       ec.ig.Emit (OpCodes.Brfalse, default_target);
+
+                       ExpressionStatement get_item_int = (ExpressionStatement) new SimpleAssign (string_switch_variable,
+                               new Cast (new TypeExpression (TypeManager.int32_type, loc), get_item_object, loc)).Resolve (ec);
+
+                       get_item_int.EmitStatement (ec);
+                       get_item_object.Release (ec);
+#endif
+                       TableSwitchEmit (ec, string_switch_variable);
+                       string_switch_variable.Release (ec);
+               }
                
                protected override void DoEmit (EmitContext ec)
                {
@@ -3616,19 +3765,20 @@ namespace Mono.CSharp {
                        null_target = ig.DefineLabel ();
 
                        // Store variable for comparission purposes
-                       LocalBuilder value;
+                       // TODO: Don't duplicate non-captured VariableReference
+                       LocalTemporary value;
                        if (HaveUnwrap) {
-                               value = ig.DeclareLocal (SwitchType);
+                               value = new LocalTemporary (SwitchType);
 #if GMCS_SOURCE
                                unwrap.EmitCheck (ec);
                                ig.Emit (OpCodes.Brfalse, null_target);
                                new_expr.Emit (ec);
-                               ig.Emit (OpCodes.Stloc, value);
+                               value.Store (ec);
 #endif
                        } else if (!is_constant) {
-                               value = ig.DeclareLocal (SwitchType);
+                               value = new LocalTemporary (SwitchType);
                                new_expr.Emit (ec);
-                               ig.Emit (OpCodes.Stloc, value);
+                               value.Store (ec);
                        } else
                                value = null;
 
@@ -3645,10 +3795,14 @@ namespace Mono.CSharp {
                        if (is_constant) {
                                if (constant_section != null)
                                        constant_section.Block.Emit (ec);
-                       } else if (SwitchType == TypeManager.string_type)
-                               SimpleSwitchEmit (ec, value);
-                       else
+                       } else if (string_dictionary != null) {
+                               DoEmitStringSwitch (value, ec);
+                       } else {
                                TableSwitchEmit (ec, value);
+                       }
+
+                       if (value != null)
+                               value.Release (ec);
 
                        // Restore context state. 
                        ig.MarkLabel (ec.LoopEnd);
@@ -3672,27 +3826,184 @@ namespace Mono.CSharp {
                }
        }
 
-       public abstract class ExceptionStatement : Statement
+       // A place where execution can restart in an iterator
+       public abstract class ResumableStatement : Statement
        {
-               public abstract void EmitFinally (EmitContext ec);
+               bool prepared;
+               protected Label resume_point;
 
-               protected bool emit_finally = true;
-               ArrayList parent_vectors;
+               public Label PrepareForEmit (EmitContext ec)
+               {
+                       if (!prepared) {
+                               prepared = true;
+                               resume_point = ec.ig.DefineLabel ();
+                       }
+                       return resume_point;
+               }
 
-               protected void DoEmitFinally (EmitContext ec)
+               public virtual Label PrepareForDispose (EmitContext ec, Label end)
                {
-                       if (emit_finally)
-                               ec.ig.BeginFinallyBlock ();
-                       else if (ec.InIterator)
-                               ec.CurrentIterator.MarkFinally (ec, parent_vectors);
-                       EmitFinally (ec);
+                       return end;
                }
+               public virtual void EmitForDispose (EmitContext ec, Iterator iterator, Label end, bool have_dispatcher)
+               {
+               }
+       }
+
+       // Base class for statements that are implemented in terms of try...finally
+       public abstract class ExceptionStatement : ResumableStatement
+       {
+               bool code_follows;
+
+               protected abstract void EmitPreTryBody (EmitContext ec);
+               protected abstract void EmitTryBody (EmitContext ec);
+               protected abstract void EmitFinallyBody (EmitContext ec);
 
-               protected void ResolveFinally (FlowBranchingException branching)
+               protected sealed override void DoEmit (EmitContext ec)
                {
-                       emit_finally = branching.EmitFinally;
-                       if (!emit_finally)
-                               branching.Parent.StealFinallyClauses (ref parent_vectors);
+                       ILGenerator ig = ec.ig;
+
+                       EmitPreTryBody (ec);
+
+                       if (resume_points != null) {
+                               IntConstant.EmitInt (ig, (int) Iterator.State.Running);
+                               ig.Emit (OpCodes.Stloc, ec.CurrentIterator.CurrentPC);
+                       }
+
+                       ig.BeginExceptionBlock ();
+
+                       if (resume_points != null) {
+                               ig.MarkLabel (resume_point);
+
+                               // For normal control flow, we want to fall-through the Switch
+                               // So, we use CurrentPC rather than the $PC field, and initialize it to an outside value above
+                               ig.Emit (OpCodes.Ldloc, ec.CurrentIterator.CurrentPC);
+                               IntConstant.EmitInt (ig, first_resume_pc);
+                               ig.Emit (OpCodes.Sub);
+
+                               Label [] labels = new Label [resume_points.Count];
+                               for (int i = 0; i < resume_points.Count; ++i)
+                                       labels [i] = ((ResumableStatement) resume_points [i]).PrepareForEmit (ec);
+                               ig.Emit (OpCodes.Switch, labels);
+                       }
+
+                       EmitTryBody (ec);
+
+                       ig.BeginFinallyBlock ();
+
+                       Label start_finally = ec.ig.DefineLabel ();
+                       if (resume_points != null) {
+                               ig.Emit (OpCodes.Ldloc, ec.CurrentIterator.SkipFinally);
+                               ig.Emit (OpCodes.Brfalse_S, start_finally);
+                               ig.Emit (OpCodes.Endfinally);
+                       }
+
+                       ig.MarkLabel (start_finally);
+                       EmitFinallyBody (ec);
+
+                       ig.EndExceptionBlock ();
+               }
+
+               public void SomeCodeFollows ()
+               {
+                       code_follows = true;
+               }
+
+               protected void ResolveReachability (EmitContext ec)
+               {
+                       // System.Reflection.Emit automatically emits a 'leave' at the end of a try clause
+                       // So, ensure there's some IL code after this statement.
+                       if (!code_follows && resume_points == null && ec.CurrentBranching.CurrentUsageVector.IsUnreachable)
+                               ec.NeedReturnLabel ();
+
+               }
+
+               ArrayList resume_points;
+               int first_resume_pc;
+               public void AddResumePoint (ResumableStatement stmt, int pc)
+               {
+                       if (resume_points == null) {
+                               resume_points = new ArrayList ();
+                               first_resume_pc = pc;
+                       }
+
+                       if (pc != first_resume_pc + resume_points.Count)
+                               throw new InternalErrorException ("missed an intervening AddResumePoint?");
+
+                       resume_points.Add (stmt);
+               }
+
+               Label dispose_try_block;
+               bool prepared_for_dispose, emitted_dispose;
+               public override Label PrepareForDispose (EmitContext ec, Label end)
+               {
+                       if (!prepared_for_dispose) {
+                               prepared_for_dispose = true;
+                               dispose_try_block = ec.ig.DefineLabel ();
+                       }
+                       return dispose_try_block;
+               }
+
+               public override void EmitForDispose (EmitContext ec, Iterator iterator, Label end, bool have_dispatcher)
+               {
+                       if (emitted_dispose)
+                               return;
+
+                       emitted_dispose = true;
+
+                       ILGenerator ig = ec.ig;
+
+                       Label end_of_try = ig.DefineLabel ();
+
+                       // Ensure that the only way we can get into this code is through a dispatcher
+                       if (have_dispatcher)
+                               ig.Emit (OpCodes.Br, end);
+
+                       ig.BeginExceptionBlock ();
+
+                       ig.MarkLabel (dispose_try_block);
+
+                       Label [] labels = null;
+                       for (int i = 0; i < resume_points.Count; ++i) {
+                               ResumableStatement s = (ResumableStatement) resume_points [i];
+                               Label ret = s.PrepareForDispose (ec, end_of_try);
+                               if (ret.Equals (end_of_try) && labels == null)
+                                       continue;
+                               if (labels == null) {
+                                       labels = new Label [resume_points.Count];
+                                       for (int j = 0; j < i; ++j)
+                                               labels [j] = end_of_try;
+                               }
+                               labels [i] = ret;
+                       }
+
+                       if (labels != null) {
+                               int j;
+                               for (j = 1; j < labels.Length; ++j)
+                                       if (!labels [0].Equals (labels [j]))
+                                               break;
+                               bool emit_dispatcher = j < labels.Length;
+
+                               if (emit_dispatcher) {
+                                       //SymbolWriter.StartIteratorDispatcher (ec.ig);
+                                       ig.Emit (OpCodes.Ldloc, iterator.CurrentPC);
+                                       IntConstant.EmitInt (ig, first_resume_pc);
+                                       ig.Emit (OpCodes.Sub);
+                                       ig.Emit (OpCodes.Switch, labels);
+                                       //SymbolWriter.EndIteratorDispatcher (ec.ig);
+                               }
+
+                               foreach (ResumableStatement s in resume_points)
+                                       s.EmitForDispose (ec, iterator, end_of_try, emit_dispatcher);
+                       }
+
+                       ig.MarkLabel (end_of_try);
+
+                       ig.BeginFinallyBlock ();
+
+                       EmitFinallyBody (ec);
+
+                       ig.EndExceptionBlock ();
                }
        }
 
@@ -3721,16 +4032,11 @@ namespace Mono.CSharp {
                                return false;
                        }
 
-                       FlowBranchingException branching = ec.StartFlowBranching (this);
+                       ec.StartFlowBranching (this);
                        bool ok = Statement.Resolve (ec);
-
-                       ResolveFinally (branching);
-
                        ec.EndFlowBranching ();
 
-                       // System.Reflection.Emit automatically emits a 'leave' to the end of the finally block.
-                       // So, ensure there's some IL code after the finally block.
-                       ec.NeedReturnLabel ();
+                       ResolveReachability (ec);
 
                        // Avoid creating libraries that reference the internal
                        // mcs NullType:
@@ -3740,34 +4046,44 @@ namespace Mono.CSharp {
                        
                        temp = new TemporaryVariable (t, loc);
                        temp.Resolve (ec);
+
+                       if (TypeManager.void_monitor_enter_object == null || TypeManager.void_monitor_exit_object == null) {
+                               Type monitor_type = TypeManager.CoreLookupType ("System.Threading", "Monitor", Kind.Class, true);
+                               TypeManager.void_monitor_enter_object = TypeManager.GetPredefinedMethod (
+                                       monitor_type, "Enter", loc, TypeManager.object_type);
+                               TypeManager.void_monitor_exit_object = TypeManager.GetPredefinedMethod (
+                                       monitor_type, "Exit", loc, TypeManager.object_type);
+                       }
                        
                        return ok;
                }
                
-               protected override void DoEmit (EmitContext ec)
+               protected override void EmitPreTryBody (EmitContext ec)
                {
                        ILGenerator ig = ec.ig;
 
-                       temp.Store (ec, expr);
+                       temp.EmitAssign (ec, expr);
                        temp.Emit (ec);
                        ig.Emit (OpCodes.Call, TypeManager.void_monitor_enter_object);
+               }
 
-                       // try
-                       if (emit_finally)
-                               ig.BeginExceptionBlock ();
+               protected override void EmitTryBody (EmitContext ec)
+               {
                        Statement.Emit (ec);
-                       
-                       // finally
-                       DoEmitFinally (ec);
-                       if (emit_finally)
-                               ig.EndExceptionBlock ();
                }
 
-               public override void EmitFinally (EmitContext ec)
+               protected override void EmitFinallyBody (EmitContext ec)
                {
                        temp.Emit (ec);
                        ec.ig.Emit (OpCodes.Call, TypeManager.void_monitor_exit_object);
                }
+
+               public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
+               {
+                       expr.MutateHoistedGenericType (storey);
+                       temp.MutateHoistedGenericType (storey);
+                       Statement.MutateHoistedGenericType (storey);
+               }
                
                protected override void CloneTo (CloneContext clonectx, Statement t)
                {
@@ -3799,6 +4115,11 @@ namespace Mono.CSharp {
                                Block.Emit (ec);
                }
 
+               public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
+               {
+                       Block.MutateHoistedGenericType (storey);
+               }
+
                protected override void CloneTo (CloneContext clonectx, Statement t)
                {
                        Unchecked target = (Unchecked) t;
@@ -3828,6 +4149,11 @@ namespace Mono.CSharp {
                                Block.Emit (ec);
                }
 
+               public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
+               {
+                       Block.MutateHoistedGenericType (storey);
+               }
+
                protected override void CloneTo (CloneContext clonectx, Statement t)
                {
                        Checked target = (Checked) t;
@@ -3856,6 +4182,12 @@ namespace Mono.CSharp {
                        using (ec.With (EmitContext.Flags.InUnsafe, true))
                                Block.Emit (ec);
                }
+
+               public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
+               {
+                       Block.MutateHoistedGenericType (storey);
+               }
+
                protected override void CloneTo (CloneContext clonectx, Statement t)
                {
                        Unsafe target = (Unsafe) t;
@@ -3901,18 +4233,60 @@ namespace Mono.CSharp {
                                // Store pointer in pinned location
                                //
                                converted.Emit (ec);
-                               vi.Variable.EmitAssign (ec);
+                               vi.EmitAssign (ec);
                        }
 
                        public override void EmitExit (EmitContext ec)
                        {
                                ec.ig.Emit (OpCodes.Ldc_I4_0);
                                ec.ig.Emit (OpCodes.Conv_U);
-                               vi.Variable.EmitAssign (ec);
+                               vi.EmitAssign (ec);
                        }
                }
 
                class StringEmitter : Emitter {
+                       class StringPtr : Expression
+                       {
+                               LocalBuilder b;
+
+                               public StringPtr (LocalBuilder b, Location l)
+                               {
+                                       this.b = b;
+                                       eclass = ExprClass.Value;
+                                       type = TypeManager.char_ptr_type;
+                                       loc = l;
+                               }
+
+                               public override Expression CreateExpressionTree (EmitContext ec)
+                               {
+                                       throw new NotSupportedException ("ET");
+                               }
+
+                               public override Expression DoResolve (EmitContext ec)
+                               {
+                                       // This should never be invoked, we are born in fully
+                                       // initialized state.
+
+                                       return this;
+                               }
+
+                               public override void Emit (EmitContext ec)
+                               {
+                                       if (TypeManager.int_get_offset_to_string_data == null) {
+                                               // TODO: Move to resolve !!
+                                               TypeManager.int_get_offset_to_string_data = TypeManager.GetPredefinedMethod (
+                                                       TypeManager.runtime_helpers_type, "get_OffsetToStringData", loc, Type.EmptyTypes);
+                                       }
+
+                                       ILGenerator ig = ec.ig;
+
+                                       ig.Emit (OpCodes.Ldloc, b);
+                                       ig.Emit (OpCodes.Conv_I);
+                                       ig.Emit (OpCodes.Call, TypeManager.int_get_offset_to_string_data);
+                                       ig.Emit (OpCodes.Add);
+                               }
+                       }
+
                        LocalBuilder pinned_string;
                        Location loc;
 
@@ -3938,7 +4312,7 @@ namespace Mono.CSharp {
                                        return;
 
                                converted.Emit (ec);
-                               vi.Variable.EmitAssign (ec);
+                               vi.EmitAssign (ec);
                        }
 
                        public override void EmitExit (EmitContext ec)
@@ -3967,24 +4341,13 @@ namespace Mono.CSharp {
                                return false;
                        }
                        
-                       TypeExpr texpr = null;
-                       if (type is VarExpr) {
-                               Unary u = ((Pair) declarators[0]).Second as Unary;
-                               if (u == null)
-                                       return false;
-                               
-                               Expression e = u.Expr.Resolve (ec);
-                               if (e == null || e.Type == null)
-                                       return false;
-                               
-                               Type t = TypeManager.GetPointerType (e.Type);
-                               texpr = new TypeExpression (t, loc);
-                       }
-                       else
-                               texpr = type.ResolveAsTypeTerminal (ec, false);
+                       TypeExpr texpr = type.ResolveAsContextualType (ec, false);
+                       if (texpr == null) {
+                               if (type is VarExpr)
+                                       Report.Error (821, type.Location, "A fixed statement cannot use an implicitly typed local variable");
 
-                       if (texpr == null)
                                return false;
+                       }
 
                        expr_type = texpr.Type;
 
@@ -4000,9 +4363,6 @@ namespace Mono.CSharp {
                                LocalInfo vi = (LocalInfo) p.First;
                                Expression e = (Expression) p.Second;
                                
-                               if (type is VarExpr)
-                                       vi.VariableType = expr_type;
-
                                vi.VariableInfo.SetAssigned (ec);
                                vi.SetReadOnlyContext (LocalInfo.ReadOnlyContext.Fixed);
 
@@ -4021,43 +4381,6 @@ namespace Mono.CSharp {
                                        Report.Error (254, loc, "The right hand side of a fixed statement assignment may not be a cast expression");
                                        return false;
                                }
-                               
-                               //
-                               // Case 1: & object.
-                               //
-                               if (e is Unary && ((Unary) e).Oper == Unary.Operator.AddressOf){
-                                       Expression child = ((Unary) e).Expr;
-
-                                       if (child is ParameterReference || child is LocalVariableReference){
-                                               Report.Error (
-                                                       213, loc, 
-                                                       "No need to use fixed statement for parameters or " +
-                                                       "local variable declarations (address is already " +
-                                                       "fixed)");
-                                               return false;
-                                       }
-
-                                       ec.InFixedInitializer = true;
-                                       e = e.Resolve (ec);
-                                       ec.InFixedInitializer = false;
-                                       if (e == null)
-                                               return false;
-
-                                       child = ((Unary) e).Expr;
-                                       
-                                       if (!TypeManager.VerifyUnManaged (child.Type, loc))
-                                               return false;
-
-                                       if (!Convert.ImplicitConversionExists (ec, e, expr_type)) {
-                                               e.Error_ValueCannotBeConverted (ec, e.Location, expr_type, false);
-                                               return false;
-                                       }
-
-                                       data [i] = new ExpressionEmitter (e, vi);
-                                       i++;
-
-                                       continue;
-                               }
 
                                ec.InFixedInitializer = true;
                                e = e.Resolve (ec);
@@ -4087,6 +4410,17 @@ namespace Mono.CSharp {
                                                ec, array_ptr, vi.VariableType, loc);
                                        if (converted == null)
                                                return false;
+                                       
+                                       //
+                                       // fixed (T* e_ptr = (e == null || e.Length == 0) ? null : converted [0])
+                                       //
+                                       converted = new Conditional (new Binary (Binary.Operator.LogicalOr,
+                                               new Binary (Binary.Operator.Equality, e, new NullLiteral (loc)),
+                                               new Binary (Binary.Operator.Equality, new MemberAccess (e, "Length"), new IntConstant (0, loc))),
+                                                       new NullPointer (loc),
+                                                       converted);
+
+                                       converted = converted.Resolve (ec);                                     
 
                                        data [i] = new ExpressionEmitter (converted, vi);
                                        i++;
@@ -4104,36 +4438,26 @@ namespace Mono.CSharp {
                                }
 
                                // Case 4: fixed buffer
-                               FieldExpr fe = e as FieldExpr;
-                               if (fe != null) {
-                                       IFixedBuffer ff = AttributeTester.GetFixedBuffer (fe.FieldInfo);
-                                       if (ff != null) {
-                                               Expression fixed_buffer_ptr = new FixedBufferPtr (fe, ff.ElementType, loc);
-                                       
-                                               Expression converted = Convert.ImplicitConversionRequired (
-                                                       ec, fixed_buffer_ptr, vi.VariableType, loc);
-                                               if (converted == null)
-                                                       return false;
-
-                                               data [i] = new ExpressionEmitter (converted, vi);
-                                               i++;
-
-                                               continue;
-                                       }
+                               if (e is FixedBufferPtr) {
+                                       data [i++] = new ExpressionEmitter (e, vi);
+                                       continue;
                                }
 
                                //
-                               // For other cases, flag a `this is already fixed expression'
+                               // Case 1: & object.
                                //
-                               if (e is LocalVariableReference || e is ParameterReference ||
-                                   Convert.ImplicitConversionExists (ec, e, vi.VariableType)){
-                                   
-                                       Report.Error (245, loc, "right hand expression is already fixed, no need to use fixed statement ");
-                                       return false;
+                               Unary u = e as Unary;
+                               if (u != null && u.Oper == Unary.Operator.AddressOf) {
+                                       IVariableReference vr = u.Expr as IVariableReference;
+                                       if (vr == null || !vr.IsFixedVariable) {
+                                               data [i] = new ExpressionEmitter (e, vi);
+                                       }
                                }
 
-                               Report.Error (245, loc, "Fixed statement only allowed on strings, arrays or address-of expressions");
-                               return false;
+                               if (data [i++] == null)
+                                       Report.Error (213, vi.Location, "You cannot use the fixed statement to take the address of an already fixed expression");
+
+                               e = Convert.ImplicitConversionRequired (ec, e, expr_type, loc);
                        }
 
                        ec.StartFlowBranching (FlowBranching.BranchingType.Conditional, loc);
@@ -4163,14 +4487,26 @@ namespace Mono.CSharp {
                        }
                }
 
+               public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
+               {
+                       // Fixed statement cannot be used inside anonymous methods or lambdas
+                       throw new NotSupportedException ();
+               }
+
                protected override void CloneTo (CloneContext clonectx, Statement t)
                {
                        Fixed target = (Fixed) t;
 
                        target.type = type.Clone (clonectx);
-                       target.declarators = new ArrayList ();
-                       foreach (LocalInfo var in declarators)
-                               target.declarators.Add (clonectx.LookupVariable (var));
+                       target.declarators = new ArrayList (declarators.Count);
+                       foreach (Pair p in declarators) {
+                               LocalInfo vi = (LocalInfo) p.First;
+                               Expression e = (Expression) p.Second;
+
+                               target.declarators.Add (
+                                       new Pair (clonectx.LookupVariable (vi), e.Clone (clonectx)));                           
+                       }
+                       
                        target.statement = statement.Clone (clonectx);
                }
        }
@@ -4204,7 +4540,7 @@ namespace Mono.CSharp {
                        }
                }
 
-               protected override void DoEmit(EmitContext ec)
+               protected override void DoEmit (EmitContext ec)
                {
                        ILGenerator ig = ec.ig;
 
@@ -4217,19 +4553,21 @@ namespace Mono.CSharp {
                                VarBlock.Emit (ec);
 
                        if (Name != null) {
-                               LocalInfo vi = Block.GetLocalInfo (Name);
-                               if (vi == null)
-                                       throw new Exception ("Variable does not exist in this block");
-
-                               if (vi.Variable.NeedsTemporary) {
-                                       LocalBuilder e = ig.DeclareLocal (vi.VariableType);
-                                       ig.Emit (OpCodes.Stloc, e);
+                               // TODO: Move to resolve
+                               LocalVariableReference lvr = new LocalVariableReference (Block, Name, loc);
+                               lvr.Resolve (ec);
+
+                               Expression source;
+                               if (lvr.IsHoisted) {
+                                       LocalTemporary lt = new LocalTemporary (lvr.Type);
+                                       lt.Store (ec);
+                                       source = lt;
+                               } else {
+                                       // Variable is at the top of the stack
+                                       source = EmptyExpression.Null;
+                               }
 
-                                       vi.Variable.EmitInstance (ec);
-                                       ig.Emit (OpCodes.Ldloc, e);
-                                       vi.Variable.EmitAssign (ec);
-                               } else
-                                       vi.Variable.EmitAssign (ec);
+                               lvr.EmitAssign (ec, source, false, false);
                        } else
                                ig.Emit (OpCodes.Pop);
 
@@ -4246,7 +4584,7 @@ namespace Mono.CSharp {
 
                                        type = te.Type;
 
-                                       if (type != TypeManager.exception_type && !type.IsSubclassOf (TypeManager.exception_type)){
+                                       if (type != TypeManager.exception_type && !TypeManager.IsSubclassOf (type, TypeManager.exception_type)){
                                                Error (155, "The type caught or thrown must be derived from System.Exception");
                                                return false;
                                        }
@@ -4265,61 +4603,131 @@ namespace Mono.CSharp {
                        }
                }
 
+               public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
+               {
+                       if (type != null)
+                               type = storey.MutateType (type);
+                       if (VarBlock != null)
+                               VarBlock.MutateHoistedGenericType (storey);
+                       Block.MutateHoistedGenericType (storey);
+               }
+
                protected override void CloneTo (CloneContext clonectx, Statement t)
                {
                        Catch target = (Catch) t;
 
-                       target.type_expr = type_expr.Clone (clonectx);
+                       if (type_expr != null)
+                               target.type_expr = type_expr.Clone (clonectx);
+                       if (VarBlock != null)
+                               target.VarBlock = clonectx.LookupBlock (VarBlock);                      
                        target.Block = clonectx.LookupBlock (Block);
-                       target.VarBlock = clonectx.LookupBlock (VarBlock);
                }
        }
 
-       public class Try : ExceptionStatement {
-               public Block Fini, Block;
+       public class TryFinally : ExceptionStatement {
+               Statement stmt;
+               Block fini;
+
+               public TryFinally (Statement stmt, Block fini, Location l)
+               {
+                       this.stmt = stmt;
+                       this.fini = fini;
+                       loc = l;
+               }
+
+               public override bool Resolve (EmitContext ec)
+               {
+                       bool ok = true;
+
+                       ec.StartFlowBranching (this);
+
+                       if (!stmt.Resolve (ec))
+                               ok = false;
+
+                       if (ok)
+                               ec.CurrentBranching.CreateSibling (fini, FlowBranching.SiblingType.Finally);
+                       using (ec.With (EmitContext.Flags.InFinally, true)) {
+                               if (!fini.Resolve (ec))
+                                       ok = false;
+                       }
+
+                       ec.EndFlowBranching ();
+
+                       ResolveReachability (ec);
+
+                       return ok;
+               }
+
+               protected override void EmitPreTryBody (EmitContext ec)
+               {
+               }
+
+               protected override void EmitTryBody (EmitContext ec)
+               {
+                       stmt.Emit (ec);
+               }
+
+               protected override void EmitFinallyBody (EmitContext ec)
+               {
+                       fini.Emit (ec);
+               }
+
+               public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
+               {
+                       stmt.MutateHoistedGenericType (storey);
+                       fini.MutateHoistedGenericType (storey);
+               }
+
+               protected override void CloneTo (CloneContext clonectx, Statement t)
+               {
+                       TryFinally target = (TryFinally) t;
+
+                       target.stmt = (Statement) stmt.Clone (clonectx);
+                       if (fini != null)
+                               target.fini = clonectx.LookupBlock (fini);
+               }
+       }
+
+       public class TryCatch : Statement {
+               public Block Block;
                public ArrayList Specific;
                public Catch General;
+               bool inside_try_finally, code_follows;
 
-               bool need_exc_block;
-               
-               //
-               // specific, general and fini might all be null.
-               //
-               public Try (Block block, ArrayList specific, Catch general, Block fini, Location l)
+               public TryCatch (Block block, ArrayList catch_clauses, Location l, bool inside_try_finally)
                {
-                       if (specific == null && general == null){
-                               Console.WriteLine ("CIR.Try: Either specific or general have to be non-null");
-                       }
-                       
                        this.Block = block;
-                       this.Specific = specific;
-                       this.General = general;
-                       this.Fini = fini;
+                       this.Specific = catch_clauses;
+                       this.General = null;
+                       this.inside_try_finally = inside_try_finally;
+
+                       for (int i = 0; i < catch_clauses.Count; ++i) {
+                               Catch c = (Catch) catch_clauses [i];
+                               if (c.IsGeneral) {
+                                       if (i != catch_clauses.Count - 1)
+                                               Report.Error (1017, c.loc, "Try statement already has an empty catch block");
+                                       this.General = c;
+                                       catch_clauses.RemoveAt (i);
+                                       i--;
+                               }
+                       }
+
                        loc = l;
                }
 
                public override bool Resolve (EmitContext ec)
                {
                        bool ok = true;
-                       
-                       FlowBranchingException branching = ec.StartFlowBranching (this);
 
-                       Report.Debug (1, "START OF TRY BLOCK", Block.StartLocation);
+                       ec.StartFlowBranching (this);
 
                        if (!Block.Resolve (ec))
                                ok = false;
 
-                       FlowBranching.UsageVector vector = ec.CurrentBranching.CurrentUsageVector;
-
-                       Report.Debug (1, "START OF CATCH BLOCKS", vector);
-
-                       Type[] prevCatches = new Type [Specific.Count];
+                       Type[] prev_catches = new Type [Specific.Count];
                        int last_index = 0;
                        foreach (Catch c in Specific){
-                               ec.CurrentBranching.CreateSibling (
-                                       c.Block, FlowBranching.SiblingType.Catch);
-
-                               Report.Debug (1, "STARTED SIBLING FOR CATCH", ec.CurrentBranching);
+                               ec.CurrentBranching.CreateSibling (c.Block, FlowBranching.SiblingType.Catch);
 
                                if (c.Name != null) {
                                        LocalInfo vi = c.Block.GetLocalInfo (c.Name);
@@ -4330,23 +4738,20 @@ namespace Mono.CSharp {
                                }
 
                                if (!c.Resolve (ec))
-                                       return false;
+                                       ok = false;
 
-                               Type resolvedType = c.CatchType;
+                               Type resolved_type = c.CatchType;
                                for (int ii = 0; ii < last_index; ++ii) {
-                                       if (resolvedType == prevCatches [ii] || resolvedType.IsSubclassOf (prevCatches [ii])) {
-                                               Report.Error (160, c.loc, "A previous catch clause already catches all exceptions of this or a super type `{0}'", prevCatches [ii].FullName);
-                                               return false;
+                                       if (resolved_type == prev_catches [ii] || TypeManager.IsSubclassOf (resolved_type, prev_catches [ii])) {
+                                               Report.Error (160, c.loc, "A previous catch clause already catches all exceptions of this or a super type `{0}'", prev_catches [ii].FullName);
+                                               ok = false;
                                        }
                                }
 
-                               prevCatches [last_index++] = resolvedType;
-                               need_exc_block = true;
+                               prev_catches [last_index++] = resolved_type;
                        }
 
-                       Report.Debug (1, "END OF CATCH BLOCKS", ec.CurrentBranching);
-
-                       if (General != null){
+                       if (General != null) {
                                if (CodeGen.Assembly.WrapNonExceptionThrows) {
                                        foreach (Catch c in Specific){
                                                if (c.CatchType == TypeManager.exception_type) {
@@ -4355,58 +4760,34 @@ namespace Mono.CSharp {
                                        }
                                }
 
-                               ec.CurrentBranching.CreateSibling (
-                                       General.Block, FlowBranching.SiblingType.Catch);
-
-                               Report.Debug (1, "STARTED SIBLING FOR GENERAL", ec.CurrentBranching);
+                               ec.CurrentBranching.CreateSibling (General.Block, FlowBranching.SiblingType.Catch);
 
                                if (!General.Resolve (ec))
                                        ok = false;
-
-                               need_exc_block = true;
                        }
 
-                       Report.Debug (1, "END OF GENERAL CATCH BLOCKS", ec.CurrentBranching);
-
-                       if (Fini != null) {
-                               if (ok)
-                                       ec.CurrentBranching.CreateSibling (Fini, FlowBranching.SiblingType.Finally);
-
-                               Report.Debug (1, "STARTED SIBLING FOR FINALLY", ec.CurrentBranching, vector);
-                               using (ec.With (EmitContext.Flags.InFinally, true)) {
-                                       if (!Fini.Resolve (ec))
-                                               ok = false;
-                               }
-
-                               if (!ec.InIterator)
-                                       need_exc_block = true;
-                       }
-
-                       if (ec.InIterator) {
-                               ResolveFinally (branching);
-                               need_exc_block |= emit_finally;
-                       } else
-                               emit_finally = Fini != null;
-
                        ec.EndFlowBranching ();
 
-                       // System.Reflection.Emit automatically emits a 'leave' to the end of the finally block.
-                       // So, ensure there's some IL code after the finally block.
-                       ec.NeedReturnLabel ();
-
-                       FlowBranching.UsageVector f_vector = ec.CurrentBranching.CurrentUsageVector;
-
-                       Report.Debug (1, "END OF TRY", ec.CurrentBranching, vector, f_vector);
+                       // System.Reflection.Emit automatically emits a 'leave' at the end of a try/catch clause
+                       // So, ensure there's some IL code after this statement
+                       if (!inside_try_finally && !code_follows && ec.CurrentBranching.CurrentUsageVector.IsUnreachable)
+                               ec.NeedReturnLabel ();
 
                        return ok;
                }
+
+               public void SomeCodeFollows ()
+               {
+                       code_follows = true;
+               }
                
                protected override void DoEmit (EmitContext ec)
                {
                        ILGenerator ig = ec.ig;
 
-                       if (need_exc_block)
+                       if (!inside_try_finally)
                                ig.BeginExceptionBlock ();
+
                        Block.Emit (ec);
 
                        foreach (Catch c in Specific)
@@ -4415,31 +4796,27 @@ namespace Mono.CSharp {
                        if (General != null)
                                General.Emit (ec);
 
-                       DoEmitFinally (ec);
-                       if (need_exc_block)
+                       if (!inside_try_finally)
                                ig.EndExceptionBlock ();
                }
 
-               public override void EmitFinally (EmitContext ec)
+               public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
                {
-                       if (Fini != null)
-                               Fini.Emit (ec);
-               }
+                       Block.MutateHoistedGenericType (storey);
 
-               public bool HasCatch
-               {
-                       get {
-                               return General != null || Specific.Count > 0;
+                       if (General != null)
+                               General.MutateHoistedGenericType (storey);
+                       if (Specific != null) {
+                               foreach (Catch c in Specific)
+                                       c.MutateHoistedGenericType (storey);
                        }
                }
 
                protected override void CloneTo (CloneContext clonectx, Statement t)
                {
-                       Try target = (Try) t;
+                       TryCatch target = (TryCatch) t;
 
                        target.Block = clonectx.LookupBlock (Block);
-                       if (Fini != null)
-                               target.Fini = clonectx.LookupBlock (Fini);
                        if (General != null)
                                target.General = (Catch) General.Clone (clonectx);
                        if (Specific != null){
@@ -4450,244 +4827,200 @@ namespace Mono.CSharp {
                }
        }
 
-       public class Using : ExceptionStatement {
-               object expression_or_block;
+       public class UsingTemporary : ExceptionStatement {
+               TemporaryVariable local_copy;
                public Statement Statement;
-               ArrayList var_list;
                Expression expr;
                Type expr_type;
-               Expression [] resolved_vars;
-               Expression [] converted_vars;
-               ExpressionStatement [] assign;
-               TemporaryVariable local_copy;
-               
-               public Using (object expression_or_block, Statement stmt, Location l)
+
+               public UsingTemporary (Expression expr, Statement stmt, Location l)
                {
-                       this.expression_or_block = expression_or_block;
+                       this.expr = expr;
                        Statement = stmt;
                        loc = l;
                }
 
-               //
-               // Resolves for the case of using using a local variable declaration.
-               //
-               bool ResolveLocalVariableDecls (EmitContext ec)
+               public override bool Resolve (EmitContext ec)
                {
-                       int i = 0;
+                       expr = expr.Resolve (ec);
+                       if (expr == null)
+                               return false;
 
-                       TypeExpr texpr = null;
-                       
-                       if (expr is VarExpr) {
-                               Expression e = ((Expression)((DictionaryEntry)var_list[0]).Value).Resolve (ec);
-                               if (e == null || e.Type == null)
+                       expr_type = expr.Type;
+
+                       if (!TypeManager.ImplementsInterface (expr_type, TypeManager.idisposable_type)) {
+                               if (Convert.ImplicitConversion (ec, expr, TypeManager.idisposable_type, loc) == null) {
+                                       Using.Error_IsNotConvertibleToIDisposable (expr);
                                        return false;
-                               texpr = new TypeExpression (e.Type, loc);
+                               }
                        }
-                       else
-                               texpr = expr.ResolveAsTypeTerminal (ec, false);
 
-                       if (texpr == null)
-                               return false;
+                       local_copy = new TemporaryVariable (expr_type, loc);
+                       local_copy.Resolve (ec);
 
-                       expr_type = texpr.Type;
+                       ec.StartFlowBranching (this);
 
-                       //
-                       // The type must be an IDisposable or an implicit conversion
-                       // must exist.
-                       //
-                       converted_vars = new Expression [var_list.Count];
-                       resolved_vars = new Expression [var_list.Count];
-                       assign = new ExpressionStatement [var_list.Count];
+                       bool ok = Statement.Resolve (ec);
 
-                       bool need_conv = !TypeManager.ImplementsInterface (
-                               expr_type, TypeManager.idisposable_type);
+                       ec.EndFlowBranching ();
 
-                       foreach (DictionaryEntry e in var_list){
-                               Expression var = (Expression) e.Key;
-                               
-                               if (expr is VarExpr) {
-                                       LocalVariableReference l = var as LocalVariableReference;
-                                       ((LocalInfo)l.Block.Variables[l.Name]).VariableType = expr_type;
-                                       ((VarExpr)expr).Handled = true;
-                               }
+                       ResolveReachability (ec);
 
-                               var = var.ResolveLValue (ec, new EmptyExpression (), loc);
-                               if (var == null)
-                                       return false;
+                       if (TypeManager.void_dispose_void == null) {
+                               TypeManager.void_dispose_void = TypeManager.GetPredefinedMethod (
+                                       TypeManager.idisposable_type, "Dispose", loc, Type.EmptyTypes);
+                       }
 
-                               resolved_vars [i] = var;
+                       return ok;
+               }
 
-                               if (!need_conv) {
-                                       i++;
-                                       continue;
-                               }
+               protected override void EmitPreTryBody (EmitContext ec)
+               {
+                       local_copy.EmitAssign (ec, expr);
+               }
+
+               protected override void EmitTryBody (EmitContext ec)
+               {
+                       Statement.Emit (ec);
+               }
 
-                               converted_vars [i] = Convert.ImplicitConversion (
-                                       ec, var, TypeManager.idisposable_type, loc);
+               protected override void EmitFinallyBody (EmitContext ec)
+               {
+                       ILGenerator ig = ec.ig;
+                       if (!expr_type.IsValueType) {
+                               Label skip = ig.DefineLabel ();
+                               local_copy.Emit (ec);
+                               ig.Emit (OpCodes.Brfalse, skip);
+                               local_copy.Emit (ec);
+                               ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
+                               ig.MarkLabel (skip);
+                               return;
+                       }
 
-                               if (converted_vars [i] == null) {
-                                       Error_IsNotConvertibleToIDisposable ();
-                                       return false;
-                               }
+                       Expression ml = Expression.MemberLookup (
+                               ec.ContainerType, TypeManager.idisposable_type, expr_type,
+                               "Dispose", Location.Null);
 
-                               i++;
+                       if (!(ml is MethodGroupExpr)) {
+                               local_copy.Emit (ec);
+                               ig.Emit (OpCodes.Box, expr_type);
+                               ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
+                               return;
                        }
 
-                       i = 0;
-                       foreach (DictionaryEntry e in var_list){
-                               Expression var = resolved_vars [i];
-                               Expression new_expr = (Expression) e.Value;
-                               Expression a;
+                       MethodInfo mi = null;
 
-                               a = new Assign (var, new_expr, loc);
-                               a = a.Resolve (ec);
-                               if (a == null)
-                                       return false;
+                       foreach (MethodInfo mk in ((MethodGroupExpr) ml).Methods) {
+                               if (TypeManager.GetParameterData (mk).Count == 0) {
+                                       mi = mk;
+                                       break;
+                               }
+                       }
 
-                               if (!need_conv)
-                                       converted_vars [i] = var;
-                               assign [i] = (ExpressionStatement) a;
-                               i++;
+                       if (mi == null) {
+                               Report.Error(-100, Mono.CSharp.Location.Null, "Internal error: No Dispose method which takes 0 parameters.");
+                               return;
                        }
 
-                       return true;
+                       local_copy.AddressOf (ec, AddressOp.Load);
+                       ig.Emit (OpCodes.Call, mi);
                }
 
-               void Error_IsNotConvertibleToIDisposable ()
+               public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
                {
-                       Report.Error (1674, loc, "`{0}': type used in a using statement must be implicitly convertible to `System.IDisposable'",
-                               TypeManager.CSharpName (expr_type));
+                       expr_type = storey.MutateType (expr_type);
+                       local_copy.MutateHoistedGenericType (storey);
+                       Statement.MutateHoistedGenericType (storey);
                }
 
-               bool ResolveExpression (EmitContext ec)
+               protected override void CloneTo (CloneContext clonectx, Statement t)
                {
-                       if (!TypeManager.ImplementsInterface (expr_type, TypeManager.idisposable_type)){
-                               if (Convert.ImplicitConversion (ec, expr, TypeManager.idisposable_type, loc) == null) {
-                                       Error_IsNotConvertibleToIDisposable ();
-                                       return false;
-                               }
-                       }
-
-                       local_copy = new TemporaryVariable (expr_type, loc);
-                       local_copy.Resolve (ec);
+                       UsingTemporary target = (UsingTemporary) t;
 
-                       return true;
+                       target.expr = expr.Clone (clonectx);
+                       target.Statement = Statement.Clone (clonectx);
                }
-               
-               //
-               // Emits the code for the case of using using a local variable declaration.
-               //
-               void EmitLocalVariableDecls (EmitContext ec)
-               {
-                       ILGenerator ig = ec.ig;
-                       int i = 0;
+       }
 
-                       for (i = 0; i < assign.Length; i++) {
-                               assign [i].EmitStatement (ec);
+       public class Using : ExceptionStatement {
+               Statement stmt;
+               public Statement EmbeddedStatement {
+                       get { return stmt is Using ? ((Using) stmt).EmbeddedStatement : stmt; }
+               }
 
-                               if (emit_finally)
-                                       ig.BeginExceptionBlock ();
-                       }
-                       Statement.Emit (ec);
+               Expression var;
+               Expression init;
 
-                       var_list.Reverse ();
+               Expression converted_var;
+               ExpressionStatement assign;
 
-                       DoEmitFinally (ec);
+               public Using (Expression var, Expression init, Statement stmt, Location l)
+               {
+                       this.var = var;
+                       this.init = init;
+                       this.stmt = stmt;
+                       loc = l;
                }
 
-               void EmitLocalVariableDeclFinally (EmitContext ec)
+               bool ResolveVariable (EmitContext ec)
                {
-                       ILGenerator ig = ec.ig;
-
-                       int i = assign.Length;
-                       for (int ii = 0; ii < var_list.Count; ++ii){
-                               Expression var = resolved_vars [--i];
-                               Label skip = ig.DefineLabel ();
-
-                               if (emit_finally)
-                                       ig.BeginFinallyBlock ();
-                               
-                               if (!var.Type.IsValueType) {
-                                       var.Emit (ec);
-                                       ig.Emit (OpCodes.Brfalse, skip);
-                                       converted_vars [i].Emit (ec);
-                                       ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
-                               } else {
-                                       Expression ml = Expression.MemberLookup(ec.ContainerType, TypeManager.idisposable_type, var.Type, "Dispose", Mono.CSharp.Location.Null);
-
-                                       if (!(ml is MethodGroupExpr)) {
-                                               var.Emit (ec);
-                                               ig.Emit (OpCodes.Box, var.Type);
-                                               ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
-                                       } else {
-                                               MethodInfo mi = null;
-
-                                               foreach (MethodInfo mk in ((MethodGroupExpr) ml).Methods) {
-                                                       if (TypeManager.GetParameterData (mk).Count == 0) {
-                                                               mi = mk;
-                                                               break;
-                                                       }
-                                               }
+                       ExpressionStatement a = new SimpleAssign (var, init, loc);
+                       a = a.ResolveStatement (ec);
+                       if (a == null)
+                               return false;
 
-                                               if (mi == null) {
-                                                       Report.Error(-100, Mono.CSharp.Location.Null, "Internal error: No Dispose method which takes 0 parameters.");
-                                                       return;
-                                               }
+                       assign = a;
 
-                                               IMemoryLocation mloc = (IMemoryLocation) var;
+                       if (TypeManager.ImplementsInterface (a.Type, TypeManager.idisposable_type)) {
+                               converted_var = var;
+                               return true;
+                       }
 
-                                               mloc.AddressOf (ec, AddressOp.Load);
-                                               ig.Emit (OpCodes.Call, mi);
-                                       }
-                               }
+                       Expression e = Convert.ImplicitConversionStandard (ec, a, TypeManager.idisposable_type, var.Location);
+                       if (e == null) {
+                               Error_IsNotConvertibleToIDisposable (var);
+                               return false;
+                       }
 
-                               ig.MarkLabel (skip);
+                       converted_var = e;
 
-                               if (emit_finally) {
-                                       ig.EndExceptionBlock ();
-                                       if (i > 0)
-                                               ig.BeginFinallyBlock ();
-                               }
-                       }
+                       return true;
                }
 
-               void EmitExpression (EmitContext ec)
+               static public void Error_IsNotConvertibleToIDisposable (Expression expr)
                {
-                       //
-                       // Make a copy of the expression and operate on that.
-                       //
-                       ILGenerator ig = ec.ig;
-
-                       local_copy.Store (ec, expr);
+                       Report.SymbolRelatedToPreviousError (expr.Type);
+                       Report.Error (1674, expr.Location, "`{0}': type used in a using statement must be implicitly convertible to `System.IDisposable'",
+                               expr.GetSignatureForError ());
+               }
 
-                       if (emit_finally)
-                               ig.BeginExceptionBlock ();
+               protected override void EmitPreTryBody (EmitContext ec)
+               {
+                       assign.EmitStatement (ec);
+               }
 
-                       Statement.Emit (ec);
-                       
-                       DoEmitFinally (ec);
-                       if (emit_finally)
-                               ig.EndExceptionBlock ();
+               protected override void EmitTryBody (EmitContext ec)
+               {
+                       stmt.Emit (ec);
                }
 
-               void EmitExpressionFinally (EmitContext ec)
+               protected override void EmitFinallyBody (EmitContext ec)
                {
                        ILGenerator ig = ec.ig;
-                       if (!expr_type.IsValueType) {
+
+                       if (!var.Type.IsValueType) {
                                Label skip = ig.DefineLabel ();
-                               local_copy.Emit (ec);
+                               var.Emit (ec);
                                ig.Emit (OpCodes.Brfalse, skip);
-                               local_copy.Emit (ec);
+                               converted_var.Emit (ec);
                                ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
                                ig.MarkLabel (skip);
                        } else {
-                               Expression ml = Expression.MemberLookup (
-                                       ec.ContainerType, TypeManager.idisposable_type, expr_type,
-                                       "Dispose", Location.Null);
+                               Expression ml = Expression.MemberLookup(ec.ContainerType, TypeManager.idisposable_type, var.Type, "Dispose", Mono.CSharp.Location.Null);
 
                                if (!(ml is MethodGroupExpr)) {
-                                       local_copy.Emit (ec);
-                                       ig.Emit (OpCodes.Box, expr_type);
+                                       var.Emit (ec);
+                                       ig.Emit (OpCodes.Box, var.Type);
                                        ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
                                } else {
                                        MethodInfo mi = null;
@@ -4704,75 +5037,49 @@ namespace Mono.CSharp {
                                                return;
                                        }
 
-                                       local_copy.AddressOf (ec, AddressOp.Load);
+                                       IMemoryLocation mloc = (IMemoryLocation) var;
+
+                                       mloc.AddressOf (ec, AddressOp.Load);
                                        ig.Emit (OpCodes.Call, mi);
                                }
                        }
                }
-               
+
+               public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
+               {
+                       assign.MutateHoistedGenericType (storey);
+                       var.MutateHoistedGenericType (storey);
+                       stmt.MutateHoistedGenericType (storey);
+               }
+
                public override bool Resolve (EmitContext ec)
                {
-                       if (expression_or_block is DictionaryEntry){
-                               expr = (Expression) ((DictionaryEntry) expression_or_block).Key;
-                               var_list = (ArrayList)((DictionaryEntry)expression_or_block).Value;
+                       if (!ResolveVariable (ec))
+                               return false;
 
-                               if (!ResolveLocalVariableDecls (ec))
-                                       return false;
+                       ec.StartFlowBranching (this);
 
-                       } else if (expression_or_block is Expression){
-                               expr = (Expression) expression_or_block;
+                       bool ok = stmt.Resolve (ec);
 
-                               expr = expr.Resolve (ec);
-                               if (expr == null)
-                                       return false;
+                       ec.EndFlowBranching ();
 
-                               expr_type = expr.Type;
+                       ResolveReachability (ec);
 
-                               if (!ResolveExpression (ec))
-                                       return false;
+                       if (TypeManager.void_dispose_void == null) {
+                               TypeManager.void_dispose_void = TypeManager.GetPredefinedMethod (
+                                       TypeManager.idisposable_type, "Dispose", loc, Type.EmptyTypes);
                        }
 
-                       FlowBranchingException branching = ec.StartFlowBranching (this);
-
-                       bool ok = Statement.Resolve (ec);
-
-                       ResolveFinally (branching);
-
-                       ec.EndFlowBranching ();
-
-                       // System.Reflection.Emit automatically emits a 'leave' to the end of the finally block.
-                       // So, ensure there's some IL code after the finally block.
-                       ec.NeedReturnLabel ();
-
                        return ok;
                }
-               
-               protected override void DoEmit (EmitContext ec)
-               {
-                       if (expression_or_block is DictionaryEntry)
-                               EmitLocalVariableDecls (ec);
-                       else if (expression_or_block is Expression)
-                               EmitExpression (ec);
-               }
-
-               public override void EmitFinally (EmitContext ec)
-               {
-                       if (expression_or_block is DictionaryEntry)
-                               EmitLocalVariableDeclFinally (ec);
-                       else if (expression_or_block is Expression)
-                               EmitExpressionFinally (ec);
-               }
 
                protected override void CloneTo (CloneContext clonectx, Statement t)
                {
                        Using target = (Using) t;
 
-                       if (expression_or_block is Expression)
-                               target.expression_or_block = ((Expression) expression_or_block).Clone (clonectx);
-                       else
-                               target.expression_or_block = ((Statement) expression_or_block).Clone (clonectx);
-                       
-                       target.Statement = Statement.Clone (clonectx);
+                       target.var = var.Clone (clonectx);
+                       target.init = init.Clone (clonectx);
+                       target.stmt = stmt.Clone (clonectx);
                }
        }
 
@@ -4784,8 +5091,6 @@ namespace Mono.CSharp {
                Expression variable;
                Expression expr;
                Statement statement;
-               ArrayForeach array;
-               CollectionForeach collection;
                
                public Foreach (Expression type, LocalVariableReference var, Expression expr,
                                Statement stmt, Location l)
@@ -4807,85 +5112,24 @@ namespace Mono.CSharp {
                        if (expr == null)
                                return false;
 
-                       if (type is VarExpr) {
-                               Type element_type = null;
-                               if (TypeManager.HasElementType (expr.Type))
-                                       element_type = TypeManager.GetElementType (expr.Type);
-                               else {
-                                       MethodGroupExpr mg = Expression.MemberLookup (
-                                               ec.ContainerType, expr.Type, "GetEnumerator", MemberTypes.Method,
-                                               Expression.AllBindingFlags, loc) as MethodGroupExpr;
-                                       
-                                       if (mg == null)
-                                                       return false;
-                                       
-                                       MethodInfo get_enumerator = null;
-                                       foreach (MethodInfo mi in mg.Methods) {
-                                               if (TypeManager.GetParameterData (mi).Count != 0)
-                                                       continue;
-                                               if ((mi.Attributes & MethodAttributes.Public) != MethodAttributes.Public)
-                                                       continue;
-                                               if (CollectionForeach.IsOverride (mi))
-                                                       continue;
-                                               get_enumerator = mi;
-                                       }
-                                       
-                                       if (get_enumerator == null)
-                                               return false;
-                                       
-                                       PropertyInfo pi = TypeManager.GetProperty (get_enumerator.ReturnType, "Current");
-                                       
-                                       if (pi == null)
-                                               return false;
-                                               
-                                       element_type = pi.PropertyType;
-                               }
-
-                               type = new TypeLookupExpression (element_type.AssemblyQualifiedName);
-                
-                               LocalVariableReference lv = variable as LocalVariableReference;
-                               ((LocalInfo)lv.Block.Variables[lv.Name]).VariableType = element_type;
-                       }
-
-                       Constant c = expr as Constant;
-                       if (c != null && c.GetValue () == null) {
+                       if (expr.IsNull) {
                                Report.Error (186, loc, "Use of null is not valid in this context");
                                return false;
                        }
 
-                       TypeExpr texpr = type.ResolveAsTypeTerminal (ec, false);
-                       if (texpr == null)
-                               return false;
-
-                       Type var_type = texpr.Type;
-
                        if (expr.eclass == ExprClass.MethodGroup || expr is AnonymousMethodExpression) {
                                Report.Error (446, expr.Location, "Foreach statement cannot operate on a `{0}'",
                                        expr.ExprClassName);
                                return false;
                        }
 
-                       //
-                       // We need an instance variable.  Not sure this is the best
-                       // way of doing this.
-                       //
-                       // FIXME: When we implement propertyaccess, will those turn
-                       // out to return values in ExprClass?  I think they should.
-                       //
-                       if (!(expr.eclass == ExprClass.Variable || expr.eclass == ExprClass.Value ||
-                             expr.eclass == ExprClass.PropertyAccess || expr.eclass == ExprClass.IndexerAccess)){
-                               collection.Error_Enumerator ();
-                               return false;
-                       }
-
                        if (expr.Type.IsArray) {
-                               array = new ArrayForeach (var_type, variable, expr, statement, loc);
-                               return array.Resolve (ec);
+                               statement = new ArrayForeach (type, variable, expr, statement, loc);
                        } else {
-                               collection = new CollectionForeach (
-                                       var_type, variable, expr, statement, loc);
-                               return collection.Resolve (ec);
+                               statement = new CollectionForeach (type, variable, expr, statement, loc);
                        }
+                       
+                       return statement.Resolve (ec);
                }
 
                protected override void DoEmit (EmitContext ec)
@@ -4896,10 +5140,7 @@ namespace Mono.CSharp {
                        ec.LoopBegin = ig.DefineLabel ();
                        ec.LoopEnd = ig.DefineLabel ();
 
-                       if (collection != null)
-                               collection.Emit (ec);
-                       else
-                               array.Emit (ec);
+                       statement.Emit (ec);
                        
                        ec.LoopBegin = old_begin;
                        ec.LoopEnd = old_end;
@@ -4907,24 +5148,22 @@ namespace Mono.CSharp {
 
                protected class ArrayCounter : TemporaryVariable
                {
+                       StatementExpression increment;
+
                        public ArrayCounter (Location loc)
                                : base (TypeManager.int32_type, loc)
-                       { }
+                       {
+                       }
 
-                       public void Initialize (EmitContext ec)
+                       public void ResolveIncrement (EmitContext ec)
                        {
-                               EmitThis (ec);
-                               ec.ig.Emit (OpCodes.Ldc_I4_0);
-                               EmitStore (ec);
+                               increment = new StatementExpression (new UnaryMutator (UnaryMutator.Mode.PostIncrement, this, loc));
+                               increment.Resolve (ec);
                        }
 
-                       public void Increment (EmitContext ec)
+                       public void EmitIncrement (EmitContext ec)
                        {
-                               EmitThis (ec);
-                               Emit (ec);
-                               ec.ig.Emit (OpCodes.Ldc_I4_1);
-                               ec.ig.Emit (OpCodes.Add);
-                               EmitStore (ec);
+                               increment.Emit (ec);
                        }
                }
 
@@ -4933,15 +5172,16 @@ namespace Mono.CSharp {
                        Expression variable, expr, conv;
                        Statement statement;
                        Type array_type;
-                       Type var_type;
+                       Expression var_type;
                        TemporaryVariable[] lengths;
                        ArrayCounter[] counter;
                        int rank;
 
                        TemporaryVariable copy;
                        Expression access;
+                       Expression[] length_exprs;
 
-                       public ArrayForeach (Type var_type, Expression var,
+                       public ArrayForeach (Expression var_type, Expression var,
                                             Expression expr, Statement stmt, Location l)
                        {
                                this.var_type = var_type;
@@ -4951,6 +5191,11 @@ namespace Mono.CSharp {
                                loc = l;
                        }
 
+                       protected override void CloneTo (CloneContext clonectx, Statement target)
+                       {
+                               throw new NotImplementedException ();
+                       }
+
                        public override bool Resolve (EmitContext ec)
                        {
                                array_type = expr.Type;
@@ -4961,15 +5206,24 @@ namespace Mono.CSharp {
 
                                counter = new ArrayCounter [rank];
                                lengths = new TemporaryVariable [rank];
+                               length_exprs = new Expression [rank];
 
-                               ArrayList list = new ArrayList ();
+                               ArrayList list = new ArrayList (rank);
                                for (int i = 0; i < rank; i++) {
                                        counter [i] = new ArrayCounter (loc);
-                                       counter [i].Resolve (ec);
+                                       counter [i].ResolveIncrement (ec);                                      
 
                                        lengths [i] = new TemporaryVariable (TypeManager.int32_type, loc);
                                        lengths [i].Resolve (ec);
 
+                                       if (rank == 1) {
+                                               length_exprs [i] = new MemberAccess (copy, "Length").Resolve (ec);
+                                       } else {
+                                               ArrayList args = new ArrayList (1);
+                                               args.Add (new Argument (new IntConstant (i, loc)));
+                                               length_exprs [i] = new Invocation (new MemberAccess (copy, "GetLength"), args).Resolve (ec);
+                                       }
+
                                        list.Add (counter [i]);
                                }
 
@@ -4977,7 +5231,17 @@ namespace Mono.CSharp {
                                if (access == null)
                                        return false;
 
-                               conv = Convert.ExplicitConversion (ec, access, var_type, loc);
+                               VarExpr ve = var_type as VarExpr;
+                               if (ve != null) {
+                                       // Infer implicitly typed local variable from foreach array type
+                                       var_type = new TypeExpression (access.Type, ve.Location);
+                               }
+
+                               var_type = var_type.ResolveAsTypeTerminal (ec, false);
+                               if (var_type == null)
+                                       return false;
+
+                               conv = Convert.ExplicitConversion (ec, access, var_type.Type, loc);
                                if (conv == null)
                                        return false;
 
@@ -5007,7 +5271,7 @@ namespace Mono.CSharp {
                        {
                                ILGenerator ig = ec.ig;
 
-                               copy.Store (ec, expr);
+                               copy.EmitAssign (ec, expr);
 
                                Label[] test = new Label [rank];
                                Label[] loop = new Label [rank];
@@ -5016,13 +5280,12 @@ namespace Mono.CSharp {
                                        test [i] = ig.DefineLabel ();
                                        loop [i] = ig.DefineLabel ();
 
-                                       lengths [i].EmitThis (ec);
-                                       ((ArrayAccess) access).EmitGetLength (ec, i);
-                                       lengths [i].EmitStore (ec);
+                                       lengths [i].EmitAssign (ec, length_exprs [i]);
                                }
 
+                               IntConstant zero = new IntConstant (0, loc);
                                for (int i = 0; i < rank; i++) {
-                                       counter [i].Initialize (ec);
+                                       counter [i].EmitAssign (ec, zero);
 
                                        ig.Emit (OpCodes.Br, test [i]);
                                        ig.MarkLabel (loop [i]);
@@ -5035,7 +5298,7 @@ namespace Mono.CSharp {
                                ig.MarkLabel (ec.LoopBegin);
 
                                for (int i = rank - 1; i >= 0; i--){
-                                       counter [i].Increment (ec);
+                                       counter [i].EmitIncrement (ec);
 
                                        ig.MarkLabel (test [i]);
                                        counter [i].Emit (ec);
@@ -5045,9 +5308,22 @@ namespace Mono.CSharp {
 
                                ig.MarkLabel (ec.LoopEnd);
                        }
+
+                       public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
+                       {
+                               copy.MutateHoistedGenericType (storey);
+                               conv.MutateHoistedGenericType (storey);
+                               variable.MutateHoistedGenericType (storey);
+                               statement.MutateHoistedGenericType (storey);
+
+                               for (int i = 0; i < rank; i++) {
+                                       counter [i].MutateHoistedGenericType (storey);
+                                       lengths [i].MutateHoistedGenericType (storey);
+                               }
+                       }
                }
 
-               protected class CollectionForeach : ExceptionStatement
+               protected class CollectionForeach : Statement
                {
                        Expression variable, expr;
                        Statement statement;
@@ -5055,15 +5331,16 @@ namespace Mono.CSharp {
                        TemporaryVariable enumerator;
                        Expression init;
                        Statement loop;
+                       Statement wrapper;
 
                        MethodGroupExpr get_enumerator;
                        PropertyExpr get_current;
                        MethodInfo move_next;
-                       Type var_type, enumerator_type;
-                       bool is_disposable;
+                       Expression var_type;
+                       Type enumerator_type;
                        bool enumerator_found;
 
-                       public CollectionForeach (Type var_type, Expression var,
+                       public CollectionForeach (Expression var_type, Expression var,
                                                  Expression expr, Statement stmt, Location l)
                        {
                                this.var_type = var_type;
@@ -5073,6 +5350,11 @@ namespace Mono.CSharp {
                                loc = l;
                        }
 
+                       protected override void CloneTo (CloneContext clonectx, Statement target)
+                       {
+                               throw new NotImplementedException ();
+                       }
+
                        bool GetEnumeratorFilter (EmitContext ec, MethodInfo mi)
                        {
                                Type return_type = mi.ReturnType;
@@ -5108,6 +5390,16 @@ namespace Mono.CSharp {
                                        // way I could do this without a goto
                                        //
 
+                                       if (TypeManager.bool_movenext_void == null) {
+                                               TypeManager.bool_movenext_void = TypeManager.GetPredefinedMethod (
+                                                       TypeManager.ienumerator_type, "MoveNext", loc, Type.EmptyTypes);
+                                       }
+
+                                       if (TypeManager.ienumerator_getcurrent == null) {
+                                               TypeManager.ienumerator_getcurrent = TypeManager.GetPredefinedProperty (
+                                                       TypeManager.ienumerator_type, "Current", loc, TypeManager.object_type);
+                                       }
+
 #if GMCS_SOURCE
                                        //
                                        // Prefer a generic enumerator over a non-generic one.
@@ -5146,9 +5438,6 @@ namespace Mono.CSharp {
                                }
 
                                enumerator_type = return_type;
-                               is_disposable = !enumerator_type.IsSealed ||
-                                       TypeManager.ImplementsInterface (
-                                               enumerator_type, TypeManager.idisposable_type);
 
                                return true;
                        }
@@ -5220,7 +5509,7 @@ namespace Mono.CSharp {
                                return null;
                        }
 
-                       public void Error_Enumerator ()
+                       void Error_Enumerator ()
                        {
                                if (enumerator_found) {
                                        return;
@@ -5231,7 +5520,7 @@ namespace Mono.CSharp {
                                        TypeManager.CSharpName (expr.Type));
                        }
 
-                       public static bool IsOverride (MethodInfo m)
+                       bool IsOverride (MethodInfo m)
                        {
                                m = (MethodInfo) TypeManager.DropGenericMethodArguments (m);
 
@@ -5311,7 +5600,7 @@ namespace Mono.CSharp {
                                        get_current = tmp_get_cur;
                                        enumerator_type = tmp_enumerator_type;
                                        MethodInfo[] mi = new MethodInfo[] { (MethodInfo) result };
-                                       get_enumerator = new MethodGroupExpr (mi, loc);
+                                       get_enumerator = new MethodGroupExpr (mi, enumerator_type, loc);
 
                                        if (t != expr.Type) {
                                                expr = Convert.ExplicitConversion (
@@ -5356,17 +5645,29 @@ namespace Mono.CSharp {
                        public override bool Resolve (EmitContext ec)
                        {
                                enumerator_type = TypeManager.ienumerator_type;
-                               is_disposable = true;
 
                                if (!ProbeCollectionType (ec, expr.Type)) {
                                        Error_Enumerator ();
                                        return false;
                                }
 
+                               bool is_disposable = !enumerator_type.IsSealed ||
+                                       TypeManager.ImplementsInterface (enumerator_type, TypeManager.idisposable_type);
+
+                               VarExpr ve = var_type as VarExpr;
+                               if (ve != null) {
+                                       // Infer implicitly typed local variable from foreach enumerable type
+                                       var_type = new TypeExpression (get_current.PropertyInfo.PropertyType, var_type.Location);
+                               }
+
+                               var_type = var_type.ResolveAsTypeTerminal (ec, false);
+                               if (var_type == null)
+                                       return false;
+                                                               
                                enumerator = new TemporaryVariable (enumerator_type, loc);
                                enumerator.Resolve (ec);
 
-                               init = new Invocation (get_enumerator, new ArrayList ());
+                               init = new Invocation (get_enumerator, null);
                                init = init.Resolve (ec);
                                if (init == null)
                                        return false;
@@ -5374,71 +5675,137 @@ namespace Mono.CSharp {
                                Expression move_next_expr;
                                {
                                        MemberInfo[] mi = new MemberInfo[] { move_next };
-                                       MethodGroupExpr mg = new MethodGroupExpr (mi, loc);
+                                       MethodGroupExpr mg = new MethodGroupExpr (mi, var_type.Type, loc);
                                        mg.InstanceExpression = enumerator;
 
-                                       move_next_expr = new Invocation (mg, new ArrayList ());
+                                       move_next_expr = new Invocation (mg, null);
                                }
 
                                get_current.InstanceExpression = enumerator;
 
                                Statement block = new CollectionForeachStatement (
-                                       var_type, variable, get_current, statement, loc);
+                                       var_type.Type, variable, get_current, statement, loc);
 
                                loop = new While (move_next_expr, block, loc);
 
-                               bool ok = true;
+                               wrapper = is_disposable ?
+                                       (Statement) new DisposableWrapper (this) :
+                                       (Statement) new NonDisposableWrapper (this);
+                               return wrapper.Resolve (ec);
+                       }
 
-                               FlowBranchingException branching = null;
-                               if (is_disposable)
-                                       branching = ec.StartFlowBranching (this);
+                       protected override void DoEmit (EmitContext ec)
+                       {
+                               wrapper.Emit (ec);
+                       }
 
-                               if (!loop.Resolve (ec))
-                                       ok = false;
+                       class NonDisposableWrapper : Statement {
+                               CollectionForeach parent;
 
-                               if (is_disposable) {
-                                       ResolveFinally (branching);
-                                       ec.EndFlowBranching ();
-                               } else
-                                       emit_finally = true;
+                               internal NonDisposableWrapper (CollectionForeach parent)
+                               {
+                                       this.parent = parent;
+                               }
 
-                               return ok;
+                               protected override void CloneTo (CloneContext clonectx, Statement target)
+                               {
+                                       throw new NotSupportedException ();
+                               }
+
+                               public override bool Resolve (EmitContext ec)
+                               {
+                                       return parent.ResolveLoop (ec);
+                               }
+
+                               protected override void DoEmit (EmitContext ec)
+                               {
+                                       parent.EmitLoopInit (ec);
+                                       parent.EmitLoopBody (ec);
+                               }
+
+                               public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
+                               {
+                                       throw new NotSupportedException ();
+                               }
                        }
 
-                       protected override void DoEmit (EmitContext ec)
-                       {
-                               ILGenerator ig = ec.ig;
+                       class DisposableWrapper : ExceptionStatement {
+                               CollectionForeach parent;
 
-                               enumerator.Store (ec, init);
+                               internal DisposableWrapper (CollectionForeach parent)
+                               {
+                                       this.parent = parent;
+                               }
 
-                               //
-                               // Protect the code in a try/finalize block, so that
-                               // if the beast implement IDisposable, we get rid of it
-                               //
-                               if (is_disposable && emit_finally)
-                                       ig.BeginExceptionBlock ();
-                       
-                               loop.Emit (ec);
+                               protected override void CloneTo (CloneContext clonectx, Statement target)
+                               {
+                                       throw new NotSupportedException ();
+                               }
 
-                               //
-                               // Now the finally block
-                               //
-                               if (is_disposable) {
-                                       DoEmitFinally (ec);
-                                       if (emit_finally)
-                                               ig.EndExceptionBlock ();
+                               public override bool Resolve (EmitContext ec)
+                               {
+                                       bool ok = true;
+
+                                       ec.StartFlowBranching (this);
+
+                                       if (!parent.ResolveLoop (ec))
+                                               ok = false;
+
+                                       ec.EndFlowBranching ();
+
+                                       ResolveReachability (ec);
+
+                                       if (TypeManager.void_dispose_void == null) {
+                                               TypeManager.void_dispose_void = TypeManager.GetPredefinedMethod (
+                                                       TypeManager.idisposable_type, "Dispose", loc, Type.EmptyTypes);
+                                       }
+                                       return ok;
+                               }
+
+                               protected override void EmitPreTryBody (EmitContext ec)
+                               {
+                                       parent.EmitLoopInit (ec);
+                               }
+
+                               protected override void EmitTryBody (EmitContext ec)
+                               {
+                                       parent.EmitLoopBody (ec);
+                               }
+
+                               protected override void EmitFinallyBody (EmitContext ec)
+                               {
+                                       parent.EmitFinallyBody (ec);
                                }
+
+                               public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
+                               {
+                                       throw new NotSupportedException ();
+                               }
+                       }
+
+                       bool ResolveLoop (EmitContext ec)
+                       {
+                               return loop.Resolve (ec);
+                       }
+
+                       void EmitLoopInit (EmitContext ec)
+                       {
+                               enumerator.EmitAssign (ec, init);
                        }
 
+                       void EmitLoopBody (EmitContext ec)
+                       {
+                               loop.Emit (ec);
+                       }
 
-                       public override void EmitFinally (EmitContext ec)
+                       void EmitFinallyBody (EmitContext ec)
                        {
                                ILGenerator ig = ec.ig;
 
                                if (enumerator_type.IsValueType) {
                                        MethodInfo mi = FetchMethodDispose (enumerator_type);
                                        if (mi != null) {
-                                               enumerator.EmitLoadAddress (ec);
+                                               enumerator.AddressOf (ec, AddressOp.Load);
                                                ig.Emit (OpCodes.Call, mi);
                                        } else {
                                                enumerator.Emit (ec);
@@ -5452,16 +5819,22 @@ namespace Mono.CSharp {
                                        ig.Emit (OpCodes.Isinst, TypeManager.idisposable_type);
                                        ig.Emit (OpCodes.Dup);
                                        ig.Emit (OpCodes.Brtrue_S, call_dispose);
-                                       ig.Emit (OpCodes.Pop);
 
-                                       Label end_finally = ig.DefineLabel ();
-                                       ig.Emit (OpCodes.Br, end_finally);
+                                       // 'endfinally' empties the evaluation stack, and can appear anywhere inside a finally block
+                                       // (Partition III, Section 3.35)
+                                       ig.Emit (OpCodes.Endfinally);
 
                                        ig.MarkLabel (call_dispose);
                                        ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
-                                       ig.MarkLabel (end_finally);
                                }
                        }
+
+                       public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
+                       {
+                               enumerator_type = storey.MutateType (enumerator_type);
+                               init.MutateHoistedGenericType (storey);
+                               loop.MutateHoistedGenericType (storey);
+                       }
                }
 
                protected class CollectionForeachStatement : Statement
@@ -5482,6 +5855,11 @@ namespace Mono.CSharp {
                                this.loc = loc;
                        }
 
+                       protected override void CloneTo (CloneContext clonectx, Statement target)
+                       {
+                               throw new NotImplementedException ();
+                       }
+
                        public override bool Resolve (EmitContext ec)
                        {
                                current = current.Resolve (ec);
@@ -5492,7 +5870,7 @@ namespace Mono.CSharp {
                                if (conv == null)
                                        return false;
 
-                               assign = new Assign (variable, conv, loc);
+                               assign = new SimpleAssign (variable, conv, loc);
                                if (assign.Resolve (ec) == null)
                                        return false;
 
@@ -5507,6 +5885,12 @@ namespace Mono.CSharp {
                                assign.EmitStatement (ec);
                                statement.Emit (ec);
                        }
+
+                       public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
+                       {
+                               assign.MutateHoistedGenericType (storey);
+                               statement.MutateHoistedGenericType (storey);
+                       }
                }
 
                protected override void CloneTo (CloneContext clonectx, Statement t)
@@ -5518,5 +5902,10 @@ namespace Mono.CSharp {
                        target.expr = expr.Clone (clonectx);
                        target.statement = statement.Clone (clonectx);
                }
+
+               public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
+               {
+                       statement.MutateHoistedGenericType (storey);
+               }
        }
 }