**** Merged r45106 from MCS ****
[mono.git] / mcs / gmcs / statement.cs
old mode 100755 (executable)
new mode 100644 (file)
index b054f0c..69977e3
@@ -3,9 +3,10 @@
 //
 // Author:
 //   Miguel de Icaza (miguel@ximian.com)
-//   Martin Baulig (martin@gnome.org)
+//   Martin Baulig (martin@ximian.com)
 //
 // (C) 2001, 2002, 2003 Ximian, Inc.
+// (C) 2003, 2004 Novell, Inc.
 //
 
 using System;
@@ -45,16 +46,14 @@ namespace Mono.CSharp {
                        // in unreachable code, for instance.
                        //
 
+                       if (warn && (RootContext.WarningLevel >= 2))
+                               Report.Warning (162, loc, "Unreachable code detected");
+
                        ec.StartFlowBranching (FlowBranching.BranchingType.Block, loc);
                        bool ok = Resolve (ec);
                        ec.KillFlowBranching ();
 
-                       if (!ok)
-                               return false;
-
-                       if (warn)
-                               Report.Warning (162, loc, "Unreachable code detected");
-                       return true;
+                       return ok;
                }
                
                protected void CheckObsolete (Type type)
@@ -140,13 +139,21 @@ namespace Mono.CSharp {
 
                public override bool Resolve (EmitContext ec)
                {
+                       bool ok = true;
+
                        Report.Debug (1, "START IF BLOCK", loc);
 
                        expr = Expression.ResolveBoolean (ec, expr, loc);
                        if (expr == null){
-                               return false;
+                               ok = false;
+                               goto skip;
                        }
                        
+                       Assign ass = expr as Assign;
+                       if (ass != null && ass.Source is Constant) {
+                               Report.Warning (665, 3, loc, "Assignment in conditional expression is always constant; did you mean to use == instead of = ?");
+                       }
+
                        //
                        // Dead code elimination
                        //
@@ -168,22 +175,22 @@ namespace Mono.CSharp {
                        
                                        if ((FalseStatement != null) &&
                                            !FalseStatement.Resolve (ec))
-                               return false;
-                       }
+                                               return false;
+                               }
 
                                return true;
                        }
-                       
+               skip:
                        ec.StartFlowBranching (FlowBranching.BranchingType.Conditional, loc);
                        
-                       bool ok = TrueStatement.Resolve (ec);
+                       ok &= TrueStatement.Resolve (ec);
 
                        is_true_ret = ec.CurrentBranching.CurrentUsageVector.Reachability.IsUnreachable;
 
                        ec.CurrentBranching.CreateSibling ();
 
-                       if ((FalseStatement != null) && !FalseStatement.Resolve (ec))
-                               ok = false;
+                       if (FalseStatement != null)
+                               ok &= FalseStatement.Resolve (ec);
                                        
                        ec.EndFlowBranching ();
 
@@ -342,12 +349,14 @@ namespace Mono.CSharp {
                        }
 
                        ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
+                       if (!infinite)
+                               ec.CurrentBranching.CreateSibling ();
 
                        if (!Statement.Resolve (ec))
                                ok = false;
 
-                               ec.CurrentBranching.Infinite = infinite;
-                               ec.EndFlowBranching ();
+                       ec.CurrentBranching.Infinite = infinite;
+                       ec.EndFlowBranching ();
 
                        return ok;
                }
@@ -526,7 +535,8 @@ namespace Mono.CSharp {
 
                public override bool Resolve (EmitContext ec)
                {
-                       expr = expr.ResolveStatement (ec);
+                       if (expr != null)
+                               expr = expr.ResolveStatement (ec);
                        return expr != null;
                }
                
@@ -557,8 +567,20 @@ namespace Mono.CSharp {
 
                public override bool Resolve (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");
+                               return false;
+                       }
+
                        if (ec.ReturnType == null){
-                       if (Expr != null){
+                               if (Expr != null){
+                                       if (ec.CurrentAnonymousMethod != null){
+                                               Report.Error (1662, loc, String.Format (
+                                                       "Anonymous method could not be converted to delegate " +
+                                                       "since the return value does not match the delegate value"));
+                                       }
                                        Error (127, "Return with a value not allowed here");
                                        return false;
                                }
@@ -582,22 +604,20 @@ namespace Mono.CSharp {
                                }
                        }
 
-                       if (ec.InIterator){
-                               Error (-206, "Return statement not allowed inside iterators");
-                               return false;
-                       }
-                               
                        FlowBranching.UsageVector vector = ec.CurrentBranching.CurrentUsageVector;
 
                        if (ec.CurrentBranching.InTryOrCatch (true)) {
                                ec.CurrentBranching.AddFinallyVector (vector);
                                in_exc = true;
-                       } else if (ec.CurrentBranching.InFinally (true)) {
+                       } else if (ec.InFinally) {
                                Error (157, "Control can not leave the body of the finally block");
                                return false;
                        } else
                                vector.CheckOutParameters (ec.CurrentBranching);
 
+                       if (in_exc)
+                               ec.NeedReturnLabel ();
+
                        ec.CurrentBranching.CurrentUsageVector.Return ();
                        return true;
                }
@@ -611,18 +631,15 @@ namespace Mono.CSharp {
                                        ec.ig.Emit (OpCodes.Stloc, ec.TemporaryReturn ());
                        }
 
-                       if (in_exc) {
-                               ec.NeedReturnLabel ();
+                       if (in_exc)
                                ec.ig.Emit (OpCodes.Leave, ec.ReturnLabel);
-                       } else {
+                       else
                                ec.ig.Emit (OpCodes.Ret);
                        }
                }
-       }
 
        public class Goto : Statement {
                string target;
-               Block block;
                LabeledStatement label;
                
                public override bool Resolve (EmitContext ec)
@@ -636,13 +653,13 @@ namespace Mono.CSharp {
                                label.AddUsageVector (ec.CurrentBranching.CurrentUsageVector);
 
                        ec.CurrentBranching.CurrentUsageVector.Goto ();
+                       label.AddReference ();
 
                        return true;
                }
                
-               public Goto (Block parent_block, string label, Location l)
+               public Goto (string label, Location l)
                {
-                       block = parent_block;
                        loc = l;
                        target = label;
                }
@@ -665,6 +682,7 @@ namespace Mono.CSharp {
                bool defined;
                bool referenced;
                Label label;
+               ILGenerator ig;
 
                FlowBranching.UsageVector vectors;
                
@@ -677,6 +695,7 @@ namespace Mono.CSharp {
                {
                        if (defined)
                                return label;
+                       ig = ec.ig;
                        label = ec.ig.DefineLabel ();
                        defined = true;
 
@@ -706,16 +725,23 @@ namespace Mono.CSharp {
                {
                        ec.CurrentBranching.Label (vectors);
 
-                       referenced = true;
-
                        return true;
                }
 
                protected override void DoEmit (EmitContext ec)
                {
+                       if (ig != null && ig != ec.ig) {
+                               Report.Error (1632, "Control cannot leave body of anonymous method");
+                               return;
+                       }
                        LabelTarget (ec);
                        ec.ig.MarkLabel (label);
                }
+
+               public void AddReference ()
+               {
+                       referenced = true;
+               }
        }
        
 
@@ -755,7 +781,7 @@ namespace Mono.CSharp {
        /// </summary>
        public class GotoCase : Statement {
                Expression expr;
-               Label label;
+               SwitchLabel sl;
                
                public GotoCase (Expression e, Location l)
                {
@@ -785,7 +811,7 @@ namespace Mono.CSharp {
                        if (val == null)
                                return false;
                                        
-                       SwitchLabel sl = (SwitchLabel) ec.Switch.Elements [val];
+                       sl = (SwitchLabel) ec.Switch.Elements [val];
 
                        if (sl == null){
                                Report.Error (
@@ -794,15 +820,13 @@ namespace Mono.CSharp {
                                return false;
                        }
 
-                       label = sl.ILLabelCode;
-
                        ec.CurrentBranching.CurrentUsageVector.Goto ();
                        return true;
                }
 
                protected override void DoEmit (EmitContext ec)
                {
-                       ec.ig.Emit (OpCodes.Br, label);
+                       ec.ig.Emit (OpCodes.Br, sl.GetILLabelCode (ec));
                }
        }
        
@@ -817,7 +841,6 @@ namespace Mono.CSharp {
 
                public override bool Resolve (EmitContext ec)
                {
-                       bool in_catch = ec.CurrentBranching.InCatch ();
                        ec.CurrentBranching.CurrentUsageVector.Throw ();
 
                        if (expr != null){
@@ -828,28 +851,33 @@ namespace Mono.CSharp {
                                ExprClass eclass = expr.eclass;
 
                                if (!(eclass == ExprClass.Variable || eclass == ExprClass.PropertyAccess ||
-                                     eclass == ExprClass.Value || eclass == ExprClass.IndexerAccess)) {
-                                       expr.Error_UnexpectedKind ("value, variable, property or indexer access ");
+                                       eclass == ExprClass.Value || eclass == ExprClass.IndexerAccess)) {
+                                       expr.Error_UnexpectedKind ("value, variable, property or indexer access ", loc);
                                        return false;
                                }
 
                                Type t = expr.Type;
-                               
+
                                if ((t != TypeManager.exception_type) &&
-                                   !t.IsSubclassOf (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");
+                                               "The type caught or thrown must be derived " +
+                                               "from System.Exception");
                                        return false;
                                }
-                       } else if (!in_catch) {
-                               Error (156,
-                                      "A throw statement with no argument is only " +
-                                      "allowed in a catch clause");
+                               return true;
+                       }
+
+                       if (!ec.InCatch) {
+                               Error (156, "A throw statement with no arguments is not allowed outside of a catch clause");
                                return false;
                        }
 
+                       if (ec.InFinally) {
+                               Error (724, "A throw statement with no argument is only allowed in a catch clause nested inside of the innermost catch clause");
+                               return false;
+                       }
                        return true;
                }
                        
@@ -879,18 +907,21 @@ namespace Mono.CSharp {
                        if (!ec.CurrentBranching.InLoop () && !ec.CurrentBranching.InSwitch ()){
                                Error (139, "No enclosing loop or switch to continue to");
                                return false;
-                       } else if (ec.CurrentBranching.InFinally (false)) {
+                       } else if (ec.InFinally && ec.CurrentBranching.BreakCrossesTryCatchBoundary()) {
                                Error (157, "Control can not leave the body of the finally block");
                                return false;
                        } else if (ec.CurrentBranching.InTryOrCatch (false))
                                ec.CurrentBranching.AddFinallyVector (
                                        ec.CurrentBranching.CurrentUsageVector);
-                       else if (ec.CurrentBranching.InLoop ())
+                       else if (ec.CurrentBranching.InLoop () || ec.CurrentBranching.InSwitch ())
                                ec.CurrentBranching.AddBreakVector (
                                        ec.CurrentBranching.CurrentUsageVector);
 
                        crossing_exc = ec.CurrentBranching.BreakCrossesTryCatchBoundary ();
 
+                       if (!crossing_exc)
+                               ec.NeedReturnLabel ();
+
                        ec.CurrentBranching.CurrentUsageVector.Break ();
                        return true;
                }
@@ -902,7 +933,6 @@ namespace Mono.CSharp {
                        if (crossing_exc)
                                ig.Emit (OpCodes.Leave, ec.LoopEnd);
                        else {
-                               ec.NeedReturnLabel ();
                                ig.Emit (OpCodes.Br, ec.LoopEnd);
                }
        }
@@ -922,7 +952,7 @@ namespace Mono.CSharp {
                        if (!ec.CurrentBranching.InLoop () && !ec.CurrentBranching.InSwitch ()){
                                Error (139, "No enclosing loop to continue to");
                                return false;
-                       } else if (ec.CurrentBranching.InFinally (false)) {
+                       } else if (ec.InFinally) {
                                Error (157, "Control can not leave the body of the finally block");
                                return false;
                        } else if (ec.CurrentBranching.InTryOrCatch (false))
@@ -945,13 +975,17 @@ namespace Mono.CSharp {
                }
        }
 
+       //
+       // The information about a user-perceived local variable
+       //
        public class LocalInfo {
                public Expression Type;
 
                //
                // Most of the time a variable will be stored in a LocalBuilder
                //
-               // But sometimes, it will be stored in a field.  The context of the field will
+               // But sometimes, it will be stored in a field (variables that have been
+               // hoisted by iterators or by anonymous methods).  The context of the field will
                // be stored in the EmitContext
                //
                //
@@ -968,11 +1002,22 @@ namespace Mono.CSharp {
                enum Flags : byte {
                        Used = 1,
                        ReadOnly = 2,
-                       Fixed = 4
+                       Pinned = 4,
+                       IsThis = 8,
+                       Captured = 16,
+                       AddressTaken = 32,
+                       CompilerGenerated = 64
                }
 
-               Flags flags;
+               public enum ReadOnlyContext: byte {
+                       Using,
+                       Foreach,
+                       Fixed
+               }
 
+               Flags flags;
+               ReadOnlyContext ro_context;
+               
                public LocalInfo (Expression type, string name, Block block, Location l)
                {
                        Type = type;
@@ -1009,8 +1054,13 @@ namespace Mono.CSharp {
 
                public bool Resolve (EmitContext ec)
                {
-                       if (VariableType == null)
-                               VariableType = ec.DeclSpace.ResolveType (Type, false, Location);
+                       if (VariableType == null) {
+                               TypeExpr texpr = Type.ResolveAsTypeTerminal (ec);
+                               if (texpr == null)
+                                       return false;
+                               
+                               VariableType = texpr.Type;
+                       }
 
                        if (VariableType == TypeManager.void_type) {
                                Report.Error (1547, Location,
@@ -1018,9 +1068,10 @@ namespace Mono.CSharp {
                                return false;
                        }
 
-                       if (VariableType == null)
+                       if (VariableType.IsAbstract && VariableType.IsSealed) {
+                               Report.Error (723, Location, "Cannot declare variable of static type '{0}'", TypeManager.CSharpName (VariableType));
                                return false;
-
+                       }
 // TODO: breaks the build
 //                     if (VariableType.IsPointer && !ec.InUnsafe)
 //                             Expression.UnsafeError (Location);
@@ -1028,21 +1079,48 @@ namespace Mono.CSharp {
                        return true;
                }
 
-               public void MakePinned ()
-               {
-                       TypeManager.MakePinned (LocalBuilder);
-                       flags |= Flags.Fixed;
-               }
-
+               //
+               // Whether the variable is Fixed (because its Pinned or its a value type)
+               //
                public bool IsFixed {
                        get {
-                               if (((flags & Flags.Fixed) != 0) || TypeManager.IsValueType (VariableType))
+                               if (((flags & Flags.Pinned) != 0) || TypeManager.IsValueType (VariableType))
                                        return true;
                                
                                return false;
                        }
                }
                
+               public bool IsCaptured {
+                       get {
+                               return (flags & Flags.Captured) != 0;
+                       }
+
+                       set {
+                               flags |= Flags.Captured;
+                       }
+               }
+
+               public bool AddressTaken {
+                       get {
+                               return (flags & Flags.AddressTaken) != 0;
+                       }
+
+                       set {
+                               flags |= Flags.AddressTaken;
+                       }
+               }
+
+               public bool CompilerGenerated {
+                       get {
+                               return (flags & Flags.CompilerGenerated) != 0;
+                       }
+
+                       set {
+                               flags |= Flags.CompilerGenerated;
+                       }
+               }
+
                public override string ToString ()
                {
                        return String.Format ("LocalInfo ({0},{1},{2},{3})",
@@ -1054,7 +1132,7 @@ namespace Mono.CSharp {
                                return (flags & Flags.Used) != 0;
                        }
                        set {
-                               flags = value ? (flags | Flags.Used) : (flags & ~Flags.Used);
+                               flags = value ? (flags | Flags.Used) : (unchecked (flags & ~Flags.Used));
                        }
                }
 
@@ -1062,13 +1140,51 @@ namespace Mono.CSharp {
                        get {
                                return (flags & Flags.ReadOnly) != 0;
                        }
+               }
+
+               public void SetReadOnlyContext (ReadOnlyContext context)
+               {
+                       flags |= Flags.ReadOnly;
+                       ro_context = context;
+               }
+
+               public string GetReadOnlyContext ()
+               {
+                       if (!ReadOnly)
+                               throw new InternalErrorException ("Variable is not readonly");
+
+                       switch (ro_context) {
+                               case ReadOnlyContext.Fixed:
+                                       return "fixed variable";
+                               case ReadOnlyContext.Foreach:
+                                       return "foreach iteration variable";
+                               case ReadOnlyContext.Using:
+                                       return "using variable";
+                       }
+                       throw new NotImplementedException ();
+               }
+
+               //
+               // Whether the variable is pinned, if Pinned the variable has been 
+               // allocated in a pinned slot with DeclareLocal.
+               //
+               public bool Pinned {
+                       get {
+                               return (flags & Flags.Pinned) != 0;
+                       }
                        set {
-                               flags = value ? (flags | Flags.ReadOnly) : (flags & ~Flags.ReadOnly);
+                               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);
+                       }
+               }
        }
                
        /// <summary>
@@ -1086,19 +1202,23 @@ namespace Mono.CSharp {
        ///   they contain extra information that is not necessary on normal blocks.
        /// </remarks>
        public class Block : Statement {
-               public readonly Block     Parent;
+               public Block    Parent;
                public readonly Location  StartLocation;
                public Location           EndLocation = Location.Null;
 
+               public readonly ToplevelBlock Toplevel;
+
                [Flags]
-               public enum Flags : byte {
+               public enum Flags {
                        Implicit  = 1,
                        Unchecked = 2,
                        BlockUsed = 4,
                        VariablesInitialized = 8,
                        HasRet = 16,
                        IsDestructor = 32,
-                       HasVarargs = 64 
+                       HasVarargs = 64,
+                       IsToplevel = 128,
+                       Unsafe = 256
                }
                Flags flags;
 
@@ -1117,6 +1237,15 @@ namespace Mono.CSharp {
                        }
                }
 
+               public bool Unsafe {
+                       get {
+                               return (flags & Flags.Unsafe) != 0;
+                       }
+                       set {
+                               flags |= Flags.Unsafe;
+                       }
+               }
+
                public bool HasVarargs {
                        get {
                                if (Parent != null)
@@ -1143,7 +1272,7 @@ namespace Mono.CSharp {
                // statements.
                //
                ArrayList children;
-               
+
                //
                // Labels.  (label, block) pairs.
                //
@@ -1158,12 +1287,17 @@ namespace Mono.CSharp {
                // Keeps track of constants
                Hashtable constants;
 
+               //
+               // Temporary variables.
+               //
+               ArrayList temporary_variables;
+               
                //
                // If this is a switch section, the enclosing switch block.
                //
                Block switch_block;
 
-               static int id;
+               protected static int id;
 
                int this_id;
                
@@ -1175,42 +1309,33 @@ namespace Mono.CSharp {
                        : this (parent, flags, Location.Null, Location.Null)
                { }
 
-               public Block (Block parent, Flags flags, Parameters parameters)
-                       : this (parent, flags, parameters, Location.Null, Location.Null)
-               { }
-
                public Block (Block parent, Location start, Location end)
                        : this (parent, (Flags) 0, start, end)
                { }
 
-               public Block (Block parent, Parameters parameters, Location start, Location end)
-                       : this (parent, (Flags) 0, parameters, start, end)
-               { }
-
                public Block (Block parent, Flags flags, Location start, Location end)
-                       : this (parent, flags, Parameters.EmptyReadOnlyParameters, start, end)
-               { }
-
-               public Block (Block parent, Flags flags, Parameters parameters,
-                             Location start, Location end)
                {
                        if (parent != null)
                                parent.AddChild (this);
                        
                        this.Parent = parent;
                        this.flags = flags;
-                       this.parameters = parameters;
                        this.StartLocation = start;
                        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.child_variable_names == null)
-                                       parent.child_variable_names = new Hashtable();
+                               if (parent.known_variables == null)
+                                       parent.known_variables = new Hashtable ();
                                // share with parent
-                               child_variable_names = parent.child_variable_names;
+                               known_variables = parent.known_variables;
                        }
                                
                }
@@ -1348,40 +1473,63 @@ namespace Mono.CSharp {
                // </summary>
                public LocalInfo ThisVariable {
                        get {
-                               if (this_variable != null)
-                                       return this_variable;
-                               else if (Parent != null)
-                                       return Parent.ThisVariable;
-                               else
-                                       return null;
+                               for (Block b = this; b != null; b = b.Parent) {
+                                       if (b.this_variable != null)
+                                               return b.this_variable;
+                               }
+                               
+                               return null;
                        }
                }
 
-               Hashtable child_variable_names;
+               Hashtable known_variables;
 
                // <summary>
-               //   Marks a variable with name @name as being used in a child block.
+               //   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>
-               public void AddChildVariableName (string name)
+               void AddKnownVariable (string name, LocalInfo info)
                {
-                       if (child_variable_names == null)
-                               child_variable_names = new Hashtable ();
+                       if (known_variables == null)
+                               known_variables = new Hashtable ();
 
-                       if (!child_variable_names.Contains (name))
-                               child_variable_names.Add (name, true);
+                       known_variables [name] = info;
                }
 
-               // <summary>
-               //   Checks whether a variable name has already been used in a child block.
-               // </summary>
-               public bool IsVariableNameUsedInChildBlock (string name)
+               LocalInfo GetKnownVariableInfo (string name)
+               {
+                       if (known_variables == null)
+                               return null;
+                       return (LocalInfo) known_variables [name];
+               }
+
+               public bool CheckInvariantMeaningInBlock (string name, Expression e, Location loc)
                {
-                       if (child_variable_names == null)
+                       LocalInfo kvi = GetKnownVariableInfo (name);
+                       if (kvi == null || kvi.Block == this)
+                               return true;
+
+                       if (known_variables != kvi.Block.known_variables) {
+                               Report.SymbolRelatedToPreviousError (kvi.Location, name);
+                               Report.Error (135, loc, "'{0}' has a different meaning in a child block", name);
                                return false;
+                       }
+
+                       //
+                       // this block and kvi.Block are the same textual block.
+                       // However, different variables are extant.
+                       //
+                       // Check if the variable is in scope in both blocks.  We use
+                       // 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 && GetLocalInfo (name) != null))
+                               return true;
 
-                       return child_variable_names.Contains (name);
+                       Report.SymbolRelatedToPreviousError (kvi.Location, name);
+                       Report.Error (136, loc, "'{0}' has a different meaning later in the block", name);
+                       return false;
                }
 
                // <summary>
@@ -1401,64 +1549,54 @@ namespace Mono.CSharp {
 
                        this_variable = new LocalInfo (tc, this, l);
                        this_variable.Used = true;
+                       this_variable.IsThis = true;
 
                        variables.Add ("this", this_variable);
 
                        return this_variable;
                }
 
-               public LocalInfo AddVariable (Expression type, string name, Parameters pars, Location l)
+               public LocalInfo AddVariable (Expression type, string name, Location l)
                {
                        if (variables == null)
                                variables = new Hashtable ();
 
                        LocalInfo vi = GetLocalInfo (name);
                        if (vi != null) {
-                               if (vi.Block != this)
-                                       Report.Error (136, l, "A local variable named `" + name + "' " +
-                                                     "cannot be declared in this scope since it would " +
-                                                     "give a different meaning to `" + name + "', which " +
-                                                     "is already used in a `parent or current' scope to " +
-                                                     "denote something else");
+                               Report.SymbolRelatedToPreviousError (vi.Location, name);
+                               if (known_variables == vi.Block.known_variables)
+                                       Report.Error (128, l,
+                                               "A local variable '{0}' is already declared in this scope", name);
                                else
-                                       Report.Error (128, l, "A local variable `" + name + "' is already " +
-                                                     "defined in this scope");
+                                       Report.Error (136, l,
+                                               "'{0}' hides the declaration of local variable '{0}' in a parent scope", name);
                                return null;
                        }
 
-                       if (IsVariableNameUsedInChildBlock (name)) {
-                               Report.Error (136, l, "A local variable named `" + name + "' " +
-                                             "cannot be declared in this scope since it would " +
-                                             "give a different meaning to `" + name + "', which " +
-                                             "is already used in a `child' scope to denote something " +
-                                             "else");
+                       vi = GetKnownVariableInfo (name);
+                       if (vi != null) {
+                               Report.SymbolRelatedToPreviousError (vi.Location, name);
+                               Report.Error (136, l,
+                                       "A child block already has a declaration of local variable '{0}':" +
+                                       " allowing this declaration would violate 'invariant meaning in a block'", 
+                                       name);
                                return null;
                        }
 
-                       if (pars != null) {
-                               int idx;
-                               Parameter p = pars.GetParameterByName (name, out idx);
-                               if (p != null) {
-                                       Report.Error (136, l, "A local variable named `" + name + "' " +
-                                                     "cannot be declared in this scope since it would " +
-                                                     "give a different meaning to `" + name + "', which " +
-                                                     "is already used in a `parent or current' scope to " +
-                                                     "denote something else");
-                                       return null;
-                               }
+                       int idx;
+                       Parameter p = Toplevel.Parameters.GetParameterByName (name, out idx);
+                       if (p != null) {
+                               Report.SymbolRelatedToPreviousError (p.Location, name);
+                               Report.Error (136, l, "'{0}' hides a method parameter", name);
+                               return null;
                        }
 
                        vi = new LocalInfo (type, name, this, l);
 
                        variables.Add (name, vi);
 
-                       // Mark 'name' as "used by a child block" in every surrounding block
-                       Block cur = this;
-                       while (cur != null && cur.Implicit) 
-                               cur = cur.Parent;
-                       if (cur != null)
-                               for (Block par = cur.Parent; par != null; par = par.Parent)
-                                       par.AddChildVariableName (name);
+                       for (Block b = this; b != null; b = b.Parent)
+                               b.AddKnownVariable (name, vi);
 
                        if ((flags & Flags.VariablesInitialized) != 0)
                                throw new Exception ();
@@ -1467,9 +1605,9 @@ namespace Mono.CSharp {
                        return vi;
                }
 
-               public bool AddConstant (Expression type, string name, Expression value, Parameters pars, Location l)
+               public bool AddConstant (Expression type, string name, Expression value, Location l)
                {
-                       if (AddVariable (type, name, pars, l) == null)
+                       if (AddVariable (type, name, l) == null)
                                return false;
                        
                        if (constants == null)
@@ -1479,6 +1617,22 @@ namespace Mono.CSharp {
                        return true;
                }
 
+               static int next_temp_id = 0;
+
+               public LocalInfo AddTemporaryVariable (TypeExpr te, Location loc)
+               {
+                       if (temporary_variables == null)
+                               temporary_variables = new ArrayList ();
+
+                       int id = ++next_temp_id;
+                       string name = "$s_" + id.ToString ();
+
+                       LocalInfo li = new LocalInfo (te, name, this, loc);
+                       li.CompilerGenerated = true;
+                       temporary_variables.Add (li);
+                       return li;
+               }
+
                public Hashtable Variables {
                        get {
                                return variables;
@@ -1531,16 +1685,6 @@ namespace Mono.CSharp {
                        return e != null;
                }
                
-               Parameters parameters = null;
-               public Parameters Parameters {
-                       get {
-                               Block b = this;
-                               while (b.Parent != null)
-                                       b = b.Parent;
-                               return b.parameters;
-                       }
-               }
-
                /// <returns>
                ///   A list of labels that were not used within this block
                /// </returns>
@@ -1589,7 +1733,7 @@ namespace Mono.CSharp {
                public VariableMap ParameterMap {
                        get {
                                if ((flags & Flags.VariablesInitialized) == 0)
-                                       throw new Exception ();
+                                       throw new Exception ("Variables have not been initialized yet");
 
                                return param_map;
                        }
@@ -1598,17 +1742,12 @@ namespace Mono.CSharp {
                public VariableMap LocalMap {
                        get {
                                if ((flags & Flags.VariablesInitialized) == 0)
-                                       throw new Exception ();
+                                       throw new Exception ("Variables have not been initialized yet");
 
                                return local_map;
                        }
                }
 
-               public bool LiftVariable (LocalInfo local_info)
-               {
-                       return false;
-               }
-               
                /// <summary>
                ///   Emits the variable declarations and labels.
                /// </summary>
@@ -1616,9 +1755,13 @@ namespace Mono.CSharp {
                ///   tc: is our typecontainer (to resolve type references)
                ///   ig: is the code generator:
                /// </remarks>
-               public void EmitMeta (EmitContext ec, InternalParameters ip)
+               public void ResolveMeta (ToplevelBlock toplevel, EmitContext ec, InternalParameters ip)
                {
-                       ILGenerator ig = ec.ig;
+                       bool old_unsafe = ec.InUnsafe;
+
+                       // If some parent block was unsafe, we remain unsafe even if this block
+                       // isn't explicitly marked as such.
+                       ec.InUnsafe |= Unsafe;
 
                        //
                        // Compute the VariableMap's.
@@ -1647,7 +1790,6 @@ namespace Mono.CSharp {
 
                        bool old_check_state = ec.ConstantCheckState;
                        ec.ConstantCheckState = (flags & Flags.Unchecked) == 0;
-                       bool remap_locals = ec.RemapToProxy;
                                
                        //
                        // Process this block variables
@@ -1673,11 +1815,6 @@ namespace Mono.CSharp {
                                                        continue;
                                        }
 
-                                       if (remap_locals)
-                                               vi.FieldBuilder = ec.MapVariable (name, vi.VariableType);
-                                       else
-                                               vi.LocalBuilder = ig.DeclareLocal (vi.VariableType);
-
                                        if (constants == null)
                                                continue;
 
@@ -1687,14 +1824,11 @@ namespace Mono.CSharp {
 
                                        ec.CurrentBlock = this;
                                        Expression e = cv.Resolve (ec);
-                                       if (e == null)
-                                               continue;
 
                                        Constant ce = e as Constant;
                                        if (ce == null){
                                                Report.Error (133, vi.Location,
-                                                             "The expression being assigned to `" +
-                                                             name + "' must be constant (" + e + ")");
+                                                             "The expression being assigned to '{0}' must be constant", name);
                                                continue;
                                        }
 
@@ -1715,7 +1849,59 @@ namespace Mono.CSharp {
                        //
                        if (children != null){
                                foreach (Block b in children)
-                                       b.EmitMeta (ec, ip);
+                                       b.ResolveMeta (toplevel, ec, ip);
+                       }
+                       ec.InUnsafe = old_unsafe;
+               }
+
+               //
+               // Emits the local variable declarations for a block
+               //
+               public void EmitMeta (EmitContext ec)
+               {
+                       ILGenerator ig = ec.ig;
+                       
+                       if (variables != null){
+                               bool have_captured_vars = ec.HaveCapturedVariables ();
+                               
+                               foreach (DictionaryEntry de in variables){
+                                       LocalInfo vi = (LocalInfo) de.Value;
+
+                                       if (have_captured_vars && ec.IsCaptured (vi))
+                                               continue;
+
+                                       if (vi.Pinned)
+                                               //
+                                               // This is needed to compile on both .NET 1.x and .NET 2.x
+                                               // the later introduced `DeclareLocal (Type t, bool pinned)'
+                                               //
+                                               vi.LocalBuilder = TypeManager.DeclareLocalPinned (ig, vi.VariableType);
+                                       else if (!vi.IsThis)
+                                               vi.LocalBuilder = ig.DeclareLocal (vi.VariableType);
+                               }
+                       }
+
+                       if (temporary_variables != null) {
+                               AnonymousContainer am = ec.CurrentAnonymousMethod;
+                               TypeBuilder scope = null;
+                               if ((am != null) && am.IsIterator) {
+                                       scope = am.Scope.ScopeTypeBuilder;
+                                       if (scope == null)
+                                               throw new InternalErrorException ();
+                               }
+                               foreach (LocalInfo vi in temporary_variables) {
+                                       if (scope != null) {
+                                               if (vi.FieldBuilder == null)
+                                                       vi.FieldBuilder = scope.DefineField (
+                                                               vi.Name, vi.VariableType, FieldAttributes.Assembly);
+                                       } else
+                                               vi.LocalBuilder = ig.DeclareLocal (vi.VariableType);
+                               }
+                       }
+
+                       if (children != null){
+                               foreach (Block b in children)
+                                       b.EmitMeta (ec);
                        }
                }
 
@@ -1723,7 +1909,7 @@ namespace Mono.CSharp {
                {
                        string name;
                        
-                       if (variables != null){
+                       if ((variables != null) && (RootContext.WarningLevel >= 3)) {
                                foreach (DictionaryEntry de in variables){
                                        LocalInfo vi = (LocalInfo) de.Value;
                                        
@@ -1733,19 +1919,17 @@ namespace Mono.CSharp {
                                        name = (string) de.Key;
                                                
                                        if (vector.IsAssigned (vi.VariableInfo)){
-                                               Report.Warning (
-                                                       219, vi.Location, "The variable `" + name +
-                                                       "' is assigned but its value is never used");
+                                               Report.Warning (219, vi.Location, "The variable '{0}' is assigned but its value is never used", name);
                                        } else {
-                                               Report.Warning (
-                                                       168, vi.Location, "The variable `" +
-                                                       name +
-                                                       "' is declared but never used");
-                                       } 
+                                               Report.Warning (168, vi.Location, "The variable '{0}' is declared but never used", name);
+                                       }
                                }
                        }
                }
 
+               bool unreachable_shown;
+               bool unreachable;
+
                public override bool Resolve (EmitContext ec)
                {
                        Block prev_block = ec.CurrentBlock;
@@ -1758,36 +1942,37 @@ namespace Mono.CSharp {
 
                        Report.Debug (4, "RESOLVE BLOCK", StartLocation, ec.CurrentBranching);
 
-                       bool unreachable = false, warning_shown = false;
-
+                       //
+                       // This flag is used to notate nested statements as unreachable from the beginning of this block.
+                       // For the purposes of this resolution, it doesn't matter that the whole block is unreachable 
+                       // from the beginning of the function.  The outer Resolve() that detected the unreachability is
+                       // responsible for handling the situation.
+                       //
                        int statement_count = statements.Count;
                        for (int ix = 0; ix < statement_count; ix++){
                                Statement s = (Statement) statements [ix];
-                               
-                               if (unreachable && !(s is LabeledStatement)) {
-                                       if (s == EmptyStatement.Value)
-                                               s.loc = EndLocation;
 
-                                       if (!s.ResolveUnreachable (ec, !warning_shown))
-                                               ok = false;
+                               if (unreachable) {
+                                       if (s is Block)
+                                               ((Block) s).unreachable = true;
 
-                                       if (s != EmptyStatement.Value)
-                                               warning_shown = true;
-                                       else
-                                               s.loc = Location.Null;
+                                       if (!unreachable_shown && (RootContext.WarningLevel >= 2)) {
+                                               Report.Warning (
+                                                       162, loc, "Unreachable code detected");
+                                               unreachable_shown = true;
+                                       }
+                               }
 
+                               if (!s.Resolve (ec)) {
+                                       ok = false;
                                        statements [ix] = EmptyStatement.Value;
                                        continue;
                                }
 
-                               if (s.Resolve (ec) == false) {
-                                       ok = false;
+                               if (unreachable && !(s is LabeledStatement) && !(s is Block))
                                        statements [ix] = EmptyStatement.Value;
-                                       continue;
-                               }
 
                                num_statements = ix + 1;
-
                                if (s is LabeledStatement)
                                        unreachable = false;
                                else
@@ -1797,7 +1982,6 @@ namespace Mono.CSharp {
                        Report.Debug (4, "RESOLVE BLOCK DONE", StartLocation,
                                      ec.CurrentBranching, statement_count, num_statements);
 
-
                        FlowBranching.UsageVector vector = ec.DoEndFlowBranching ();
 
                        ec.CurrentBlock = prev_block;
@@ -1831,6 +2015,21 @@ namespace Mono.CSharp {
                        return ok;
                }
                
+               public override bool ResolveUnreachable (EmitContext ec, bool warn)
+               {
+                       unreachable_shown = true;
+                       unreachable = true;
+
+                       if (warn && (RootContext.WarningLevel >= 2))
+                               Report.Warning (162, loc, "Unreachable code detected");
+
+                       ec.StartFlowBranching (FlowBranching.BranchingType.Block, loc);
+                       bool ok = Resolve (ec);
+                       ec.KillFlowBranching ();
+
+                       return ok;
+               }
+               
                protected override void DoEmit (EmitContext ec)
                {
                        for (int ix = 0; ix < num_statements; ix++){
@@ -1839,7 +2038,7 @@ namespace Mono.CSharp {
                                // Check whether we are the last statement in a
                                // top-level block.
 
-                               if ((Parent == null) && (ix+1 == num_statements))
+                               if (((Parent == null) || Implicit) && (ix+1 == num_statements) && !(s is Block))
                                        ec.IsLastStatement = true;
                                else
                                        ec.IsLastStatement = false;
@@ -1859,7 +2058,7 @@ namespace Mono.CSharp {
 
                        if (emit_debug_info) {
                                if (is_lexical_block)
-                                       ec.ig.BeginScope ();
+                                       ec.BeginScope ();
 
                                if (variables != null) {
                                        foreach (DictionaryEntry de in variables) {
@@ -1869,7 +2068,7 @@ namespace Mono.CSharp {
                                                if (vi.LocalBuilder == null)
                                                        continue;
 
-                                               vi.LocalBuilder.SetLocalSymInfo (name);
+                                               ec.DefineLocalVariable (name, vi.LocalBuilder);
                                        }
                                }
                        }
@@ -1879,32 +2078,228 @@ namespace Mono.CSharp {
                        ec.Mark (EndLocation, true); 
 
                        if (emit_debug_info && is_lexical_block)
-                               ec.ig.EndScope ();
+                               ec.EndScope ();
 
                        ec.CurrentBlock = prev_block;
                }
-       }
 
-       //
-       // 
-       public class ToplevelBlock : Block {
-               public ToplevelBlock (Parameters parameters, Location start) :
-                       base (null, parameters, start, Location.Null)
+               //
+               // Returns true if we ar ea child of `b'.
+               //
+               public bool IsChildOf (Block b)
                {
+                       Block current = this;
+                       
+                       do {
+                               if (current.Parent == b)
+                                       return true;
+                               current = current.Parent;
+                       } while (current != null);
+                       return false;
                }
 
-               public ToplevelBlock (Flags flags, Parameters parameters, Location start) :
-                       base (null, flags, parameters, start, Location.Null)
+               public override string ToString ()
                {
+                       return String.Format ("{0} ({1}:{2})", GetType (),ID, StartLocation);
                }
        }
-       
-       public class SwitchLabel {
-               Expression label;
+
+       //
+       // 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
+               //
+               ToplevelBlock container;
+               CaptureContext capture_context;
+               FlowBranching top_level_branching;
+
+               Hashtable capture_contexts;
+               ArrayList children;
+
+               //
+               // The parameters for the block.
+               //
+               public readonly Parameters Parameters;
+                       
+               public void RegisterCaptureContext (CaptureContext cc)
+               {
+                       if (capture_contexts == null)
+                               capture_contexts = new Hashtable ();
+                       capture_contexts [cc] = cc;
+               }
+
+               public void CompleteContexts ()
+               {
+                       if (capture_contexts == null)
+                               return;
+
+                       foreach (CaptureContext cc in capture_contexts.Keys){
+                               cc.AdjustScopes ();
+                       }
+               }
+
+               public CaptureContext ToplevelBlockCaptureContext {
+                       get {
+                               return capture_context;
+                       }
+               }
+
+               public ToplevelBlock Container {
+                       get {
+                               return container;
+                       }
+               }
+
+               protected void AddChild (ToplevelBlock block)
+               {
+                       if (children == null)
+                               children = new ArrayList ();
+
+                       children.Add (block);
+               }
+
+               //
+               // Parent is only used by anonymous blocks to link back to their
+               // parents
+               //
+               public ToplevelBlock (ToplevelBlock container, Parameters parameters, Location start) :
+                       this (container, (Flags) 0, parameters, start)
+               {
+               }
+               
+               public ToplevelBlock (Parameters parameters, Location start) :
+                       this (null, (Flags) 0, parameters, start)
+               {
+               }
+
+               public ToplevelBlock (Flags flags, Parameters parameters, Location start) :
+                       this (null, flags, parameters, start)
+               {
+               }
+
+               public ToplevelBlock (ToplevelBlock container, Flags flags, Parameters parameters, Location start) :
+                       base (null, flags | Flags.IsToplevel, start, Location.Null)
+               {
+                       Parameters = parameters == null ? Parameters.EmptyReadOnlyParameters : parameters;
+                       this.container = container;
+
+                       if (container != null)
+                               container.AddChild (this);
+               }
+
+               public ToplevelBlock (Location loc) : this (null, (Flags) 0, null, loc)
+               {
+               }
+
+               public void SetHaveAnonymousMethods (Location loc, AnonymousContainer host)
+               {
+                       if (capture_context == null)
+                               capture_context = new CaptureContext (this, loc, host);
+               }
+
+               public CaptureContext CaptureContext {
+                       get {
+                               return capture_context;
+                       }
+               }
+
+               public FlowBranching 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, AnonymousContainer new_host)
+               {
+                       foreach (ToplevelBlock block in children) {
+                               if (block.CaptureContext == null)
+                                       continue;
+
+                               block.container = new_parent;
+                               block.CaptureContext.ReParent (new_parent, new_host);
+                       }
+               }
+
+               //
+               // 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 (pars, this, idx, name, loc);
+                       }
+                       return null;
+               }
+
+               //
+               // 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)
+               {
+                       for (ToplevelBlock t = this; t != null; t = t.Container) {
+                               if (t.IsLocalParameter (name))
+                                       return true;
+                       }
+                       return false;
+               }
+
+               public bool ResolveMeta (EmitContext ec, InternalParameters ip)
+               {
+                       int errors = Report.Errors;
+
+                       if (top_level_branching != null)
+                               return true;
+
+                       ResolveMeta (this, ec, ip);
+
+                       top_level_branching = ec.StartFlowBranching (this);
+
+                       return Report.Errors == errors;
+               }
+       }
+       
+       public class SwitchLabel {
+               Expression label;
                object converted;
                public Location loc;
-               public Label ILLabel;
-               public Label ILLabelCode;
+
+               Label il_label;
+               bool  il_label_set;
+               Label il_label_code;
+               bool  il_label_code_set;
 
                //
                // if expr == null, then it is the default case.
@@ -1927,15 +2322,30 @@ namespace Mono.CSharp {
                        }
                }
 
+               public Label GetILLabel (EmitContext ec)
+               {
+                       if (!il_label_set){
+                               il_label = ec.ig.DefineLabel ();
+                               il_label_set = true;
+                       }
+                       return il_label;
+               }
+
+               public Label GetILLabelCode (EmitContext ec)
+               {
+                       if (!il_label_code_set){
+                               il_label_code = ec.ig.DefineLabel ();
+                               il_label_code_set = true;
+                       }
+                       return il_label_code;
+               }                               
+               
                //
                // Resolves the expression, reduces it to a literal if possible
                // and then converts it to the requested type.
                //
                public bool ResolveAndReduce (EmitContext ec, Type required_type)
                {
-                       ILLabel = ec.ig.DefineLabel ();
-                       ILLabelCode = ec.ig.DefineLabel ();
-
                        if (label == null)
                                return true;
                        
@@ -1952,7 +2362,6 @@ namespace Mono.CSharp {
                        if (e is StringConstant || e is NullLiteral){
                                if (required_type == TypeManager.string_type){
                                        converted = e;
-                                       ILLabel = ec.ig.DefineLabel ();
                                        return true;
                                }
                        }
@@ -1994,9 +2403,11 @@ namespace Mono.CSharp {
                //
                // Computed
                //
-               bool got_default;
                Label default_target;
                Expression new_expr;
+               bool is_constant;
+               SwitchSection constant_section;
+               SwitchSection default_section;
 
                //
                // The types allowed to be implicitly cast from
@@ -2013,7 +2424,7 @@ namespace Mono.CSharp {
 
                public bool GotDefault {
                        get {
-                               return got_default;
+                               return default_section != null;
                        }
                }
 
@@ -2047,12 +2458,12 @@ namespace Mono.CSharp {
 
                        if (allowed_types == null){
                                allowed_types = new Type [] {
+                                       TypeManager.int32_type,
+                                       TypeManager.uint32_type,
                                        TypeManager.sbyte_type,
                                        TypeManager.byte_type,
                                        TypeManager.short_type,
                                        TypeManager.ushort_type,
-                                       TypeManager.int32_type,
-                                       TypeManager.uint32_type,
                                        TypeManager.int64_type,
                                        TypeManager.uint64_type,
                                        TypeManager.char_type,
@@ -2075,22 +2486,34 @@ namespace Mono.CSharp {
                                if (e == null)
                                        continue;
 
+                               //
+                               // Ignore over-worked ImplicitUserConversions that do
+                               // an implicit conversion in addition to the user conversion.
+                               // 
+                               if (e is UserCast){
+                                       UserCast ue = e as UserCast;
+
+                                       if (ue.Source != Expr)
+                                               e = null;
+                               }
+                               
                                if (converted != null){
-                                       Report.Error (-12, loc, "More than one conversion to an integral " +
-                                                     " type exists for type `" +
-                                                     TypeManager.CSharpName (Expr.Type)+"'");
+                                       Report.ExtraInformation (
+                                               loc,
+                                               String.Format ("reason: more than one conversion to an integral type exist for type {0}",
+                                                              TypeManager.CSharpName (Expr.Type)));
                                        return null;
-                               } else
+                               } else {
                                        converted = e;
+                               }
                        }
                        return converted;
                }
 
-               void error152 (string n)
-               {
-                       Report.Error (
-                               152, "The label `" + n + ":' " +
-                               "is already present on this switch statement");
+               static string Error152 {
+                       get {
+                               return "The label '{0}:' already occurs in this switch statement";
+                       }
                }
                
                //
@@ -2106,8 +2529,6 @@ namespace Mono.CSharp {
                        bool error = false;
                        Elements = new Hashtable ();
                                
-                       got_default = false;
-
                        if (TypeManager.IsEnumType (SwitchType)){
                                compare_type = TypeManager.EnumToUnderlying (SwitchType);
                        } else
@@ -2121,11 +2542,11 @@ namespace Mono.CSharp {
                                        }
 
                                        if (sl.Label == null){
-                                               if (got_default){
-                                                       error152 ("default");
+                                               if (default_section != null){
+                                                       Report.Error (152, sl.loc, Error152, "default");
                                                        error = true;
                                                }
-                                               got_default = true;
+                                               default_section = ss;
                                                continue;
                                        }
                                        
@@ -2230,7 +2651,7 @@ namespace Mono.CSharp {
                                        }
 
                                        if (lname != null){
-                                               error152 ("case + " + lname);
+                                               Report.Error (152, sl.loc, Error152, "case " + lname);
                                                error = true;
                                        }
                                }
@@ -2418,7 +2839,7 @@ namespace Mono.CSharp {
                                                ig.Emit (OpCodes.Ldloc, val);
                                                EmitObjectInteger (ig, key);
                                                SwitchLabel sl = (SwitchLabel) Elements [key];
-                                               ig.Emit (OpCodes.Beq, sl.ILLabel);
+                                               ig.Emit (OpCodes.Beq, sl.GetILLabel (ec));
                                        }
                                }
                                else
@@ -2474,7 +2895,7 @@ namespace Mono.CSharp {
                                                if (System.Convert.ToInt64 (key) == kb.nFirst + iJump)
                                                {
                                                        SwitchLabel sl = (SwitchLabel) Elements [key];
-                                                       rgLabels [iJump] = sl.ILLabel;
+                                                       rgLabels [iJump] = sl.GetILLabel (ec);
                                                        iKey++;
                                                }
                                                else
@@ -2502,8 +2923,8 @@ namespace Mono.CSharp {
                        {
                                foreach (SwitchLabel sl in ss.Labels)
                                {
-                                       ig.MarkLabel (sl.ILLabel);
-                                       ig.MarkLabel (sl.ILLabelCode);
+                                       ig.MarkLabel (sl.GetILLabel (ec));
+                                       ig.MarkLabel (sl.GetILLabelCode (ec));
                                        if (sl.Label == null)
                                        {
                                                ig.MarkLabel (lblDefault);
@@ -2531,12 +2952,11 @@ namespace Mono.CSharp {
                        Label end_of_switch = ig.DefineLabel ();
                        Label next_test = ig.DefineLabel ();
                        Label null_target = ig.DefineLabel ();
-                       bool default_found = false;
                        bool first_test = true;
                        bool pending_goto_end = false;
+                       bool null_marked = false;
                        bool null_found;
-                       bool default_at_end = false;
-                       
+
                        ig.Emit (OpCodes.Ldloc, val);
                        
                        if (Elements.Contains (NullLiteral.Null)){
@@ -2547,21 +2967,26 @@ namespace Mono.CSharp {
                        ig.Emit (OpCodes.Ldloc, val);
                        ig.Emit (OpCodes.Call, TypeManager.string_isinterneted_string);
                        ig.Emit (OpCodes.Stloc, val);
-               
+
                        int section_count = Sections.Count;
                        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;
-                               bool mark_default = false;
                                null_found = false;
                                for (int label = 0; label < label_count; label++){
                                        SwitchLabel sl = (SwitchLabel) ss.Labels [label];
-                                       ig.MarkLabel (sl.ILLabel);
+                                       ig.MarkLabel (sl.GetILLabel (ec));
                                        
                                        if (!first_test){
                                                ig.MarkLabel (next_test);
@@ -2570,12 +2995,7 @@ namespace Mono.CSharp {
                                        //
                                        // If we are the default target
                                        //
-                                       if (sl.Label == null){
-                                               if (label+1 == label_count)
-                                                       default_at_end = true;
-                                               mark_default = true;
-                                               default_found = true;
-                                       } else {
+                                       if (sl.Label != null){
                                                object lit = sl.Converted;
 
                                                if (lit is NullLiteral){
@@ -2599,27 +3019,39 @@ namespace Mono.CSharp {
                                                }
                                        }
                                }
-                               if (null_found)
+                               if (null_found) {
                                        ig.MarkLabel (null_target);
+                                       null_marked = true;
+                               }
                                ig.MarkLabel (sec_begin);
                                foreach (SwitchLabel sl in ss.Labels)
-                                       ig.MarkLabel (sl.ILLabelCode);
+                                       ig.MarkLabel (sl.GetILLabelCode (ec));
 
-                               if (mark_default)
-                                       ig.MarkLabel (default_target);
                                ss.Block.Emit (ec);
                                pending_goto_end = !ss.Block.HasRet;
                                first_test = false;
                        }
                        ig.MarkLabel (next_test);
-                       if (default_found){
-                               if (!default_at_end)
-                                       ig.Emit (OpCodes.Br, default_target);
-                       } else 
-                               ig.MarkLabel (default_target);
+                       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);
                }
 
+               SwitchSection FindSection (SwitchLabel label)
+               {
+                       foreach (SwitchSection ss in Sections){
+                               foreach (SwitchLabel sl in ss.Labels){
+                                       if (label == sl)
+                                               return ss;
+                               }
+                       }
+
+                       return null;
+               }
+
                public override bool Resolve (EmitContext ec)
                {
                        Expr = Expr.Resolve (ec);
@@ -2645,6 +3077,16 @@ namespace Mono.CSharp {
                        Report.Debug (1, "START OF SWITCH BLOCK", loc, ec.CurrentBranching);
                        ec.StartFlowBranching (FlowBranching.BranchingType.Switch, loc);
 
+                       is_constant = new_expr is Constant;
+                       if (is_constant) {
+                               object key = ((Constant) new_expr).GetValue ();
+                               SwitchLabel label = (SwitchLabel) Elements [key];
+
+                               constant_section = FindSection (label);
+                               if (constant_section == null)
+                                       constant_section = default_section;
+                       }
+
                        bool first = true;
                        foreach (SwitchSection ss in Sections){
                                if (!first)
@@ -2653,12 +3095,20 @@ namespace Mono.CSharp {
                                else
                                        first = false;
 
-                               if (ss.Block.Resolve (ec) != true)
-                                       return false;
+                               if (is_constant && (ss != constant_section)) {
+                                       // If we're a constant switch, we're only emitting
+                                       // one single section - mark all the others as
+                                       // unreachable.
+                                       ec.CurrentBranching.CurrentUsageVector.Goto ();
+                                       if (!ss.Block.ResolveUnreachable (ec, true))
+                                               return false;
+                               } else {
+                                       if (!ss.Block.Resolve (ec))
+                                               return false;
+                       }
                        }
 
-
-                       if (!got_default)
+                       if (default_section == null)
                                ec.CurrentBranching.CreateSibling (
                                        null, FlowBranching.SiblingType.SwitchSection);
 
@@ -2673,12 +3123,16 @@ namespace Mono.CSharp {
                
                protected override void DoEmit (EmitContext ec)
                {
+                       ILGenerator ig = ec.ig;
+
                        // Store variable for comparission purposes
-                       LocalBuilder value = ec.ig.DeclareLocal (SwitchType);
+                       LocalBuilder value;
+                       if (!is_constant) {
+                               value = ig.DeclareLocal (SwitchType);
                        new_expr.Emit (ec);
-                       ec.ig.Emit (OpCodes.Stloc, value);
-
-                       ILGenerator ig = ec.ig;
+                               ig.Emit (OpCodes.Stloc, value);
+                       } else
+                               value = null;
 
                        default_target = ig.DefineLabel ();
 
@@ -2692,7 +3146,10 @@ namespace Mono.CSharp {
                        ec.Switch = this;
 
                        // Emit Code.
-                       if (SwitchType == TypeManager.string_type)
+                       if (is_constant) {
+                               if (constant_section != null)
+                                       constant_section.Block.Emit (ec);
+                       } else if (SwitchType == TypeManager.string_type)
                                SimpleSwitchEmit (ec, value);
                        else
                                TableSwitchEmit (ec, value);
@@ -2708,9 +3165,34 @@ namespace Mono.CSharp {
                }
        }
 
-       public class Lock : Statement {
+       public abstract class ExceptionStatement : Statement
+       {
+               public abstract void EmitFinally (EmitContext ec);
+
+               protected bool emit_finally = true;
+               ArrayList parent_vectors;
+
+               protected void DoEmitFinally (EmitContext ec)
+               {
+                       if (emit_finally)
+                               ec.ig.BeginFinallyBlock ();
+                       else if (ec.InIterator)
+                               ec.CurrentIterator.MarkFinally (ec, parent_vectors);
+                       EmitFinally (ec);
+               }
+
+               protected void ResolveFinally (FlowBranchingException branching)
+               {
+                       emit_finally = branching.EmitFinally;
+                       if (!emit_finally)
+                               branching.Parent.StealFinallyClauses (ref parent_vectors);
+               }
+       }
+
+       public class Lock : ExceptionStatement {
                Expression expr;
                Statement Statement;
+               LocalBuilder temp;
                        
                public Lock (Expression expr, Statement stmt, Location l)
                {
@@ -2732,11 +3214,26 @@ namespace Mono.CSharp {
                                return false;
                        }
 
-                       ec.StartFlowBranching (FlowBranching.BranchingType.Exception, loc);
+                       FlowBranchingException branching = ec.StartFlowBranching (this);
                        bool ok = Statement.Resolve (ec);
-                       ec.EndFlowBranching ();
+                       if (!ok) {
+                               ec.KillFlowBranching ();
+                               return false;
+                       }
 
-                       return ok;
+                       ResolveFinally (branching);
+
+                       FlowBranching.Reachability reachability = ec.EndFlowBranching ();
+                       if (reachability.Returns != FlowBranching.FlowReturns.Always) {
+                               // Unfortunately, System.Reflection.Emit automatically emits
+                               // a leave to the end of the finally block.
+                               // This is a problem if `returns' is true since we may jump
+                               // to a point after the end of the method.
+                               // As a workaround, emit an explicit ret here.
+                               ec.NeedReturnLabel ();
+                       }
+
+                       return true;
                }
                
                protected override void DoEmit (EmitContext ec)
@@ -2744,7 +3241,7 @@ namespace Mono.CSharp {
                        Type type = expr.Type;
                        
                        ILGenerator ig = ec.ig;
-                       LocalBuilder temp = ig.DeclareLocal (type);
+                       temp = ig.DeclareLocal (type);
                                
                        expr.Emit (ec);
                        ig.Emit (OpCodes.Dup);
@@ -2752,18 +3249,21 @@ namespace Mono.CSharp {
                        ig.Emit (OpCodes.Call, TypeManager.void_monitor_enter_object);
 
                        // try
-                       ig.BeginExceptionBlock ();
-                       Label finish = ig.DefineLabel ();
+                       if (emit_finally)
+                               ig.BeginExceptionBlock ();
                        Statement.Emit (ec);
-                       // ig.Emit (OpCodes.Leave, finish);
-
-                       ig.MarkLabel (finish);
                        
                        // finally
-                       ig.BeginFinallyBlock ();
+                       DoEmitFinally (ec);
+                       if (emit_finally)
+                               ig.EndExceptionBlock ();
+               }
+
+               public override void EmitFinally (EmitContext ec)
+               {
+                       ILGenerator ig = ec.ig;
                        ig.Emit (OpCodes.Ldloc, temp);
                        ig.Emit (OpCodes.Call, TypeManager.void_monitor_exit_object);
-                       ig.EndExceptionBlock ();
                }
        }
 
@@ -2845,6 +3345,7 @@ namespace Mono.CSharp {
                public Unsafe (Block b)
                {
                        Block = b;
+                       Block.Unsafe = true;
                }
 
                public override bool Resolve (EmitContext ec)
@@ -2877,15 +3378,81 @@ namespace Mono.CSharp {
                ArrayList declarators;
                Statement statement;
                Type expr_type;
-               FixedData[] data;
+               Emitter[] data;
                bool has_ret;
 
-               struct FixedData {
-                       public bool is_object;
-                       public LocalInfo vi;
-                       public Expression expr;
-                       public Expression converted;
-               }                       
+               abstract class Emitter
+               {
+                       protected LocalInfo vi;
+                       protected Expression converted;
+
+                       protected Emitter (Expression expr, LocalInfo li)
+                       {
+                               converted = expr;
+                               vi = li;
+                       }
+
+                       public abstract void Emit (EmitContext ec);
+                       public abstract void EmitExit (ILGenerator ig);
+               }
+
+               class ExpressionEmitter: Emitter {
+                       public ExpressionEmitter (Expression converted, LocalInfo li) :
+                               base (converted, li)
+                       {
+                       }
+
+                       public override void Emit (EmitContext ec) {
+                               //
+                               // Store pointer in pinned location
+                               //
+                               converted.Emit (ec);
+                               ec.ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
+                       }
+
+                       public override void EmitExit (ILGenerator ig)
+                       {
+                               ig.Emit (OpCodes.Ldc_I4_0);
+                               ig.Emit (OpCodes.Conv_U);
+                               ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
+                       }
+               }
+
+               class StringEmitter: Emitter {
+                       LocalBuilder pinned_string;
+                       Location loc;
+
+                       public StringEmitter (Expression expr, LocalInfo li, Location loc):
+                               base (expr, li)
+                       {
+                               this.loc = loc;
+                       }
+
+                       public override void Emit (EmitContext ec)
+                       {
+                               ILGenerator ig = ec.ig;
+                               pinned_string = TypeManager.DeclareLocalPinned (ig, TypeManager.string_type);
+                                       
+                               converted.Emit (ec);
+                               ig.Emit (OpCodes.Stloc, pinned_string);
+
+                               Expression sptr = new StringPtr (pinned_string, loc);
+                               converted = Convert.ImplicitConversionRequired (
+                                       ec, sptr, vi.VariableType, loc);
+                                       
+                               if (converted == null)
+                                       return;
+
+                               converted.Emit (ec);
+                               ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
+                       }
+
+                       public override void EmitExit(ILGenerator ig)
+                       {
+                               ig.Emit (OpCodes.Ldnull);
+                               ig.Emit (OpCodes.Stloc, pinned_string);
+                       }
+               }
 
                public Fixed (Expression type, ArrayList decls, Statement stmt, Location l)
                {
@@ -2902,18 +3469,15 @@ namespace Mono.CSharp {
                                return false;
                        }
                        
-                       expr_type = ec.DeclSpace.ResolveType (type, false, loc);
-                       if (expr_type == null)
+                       TypeExpr texpr = type.ResolveAsTypeTerminal (ec);
+                       if (texpr == null)
                                return false;
 
+                       expr_type = texpr.Type;
+
                        CheckObsolete (expr_type);
 
-                       if (ec.RemapToProxy){
-                               Report.Error (-210, loc, "Fixed statement not allowed in iterators");
-                               return false;
-                       }
-                       
-                       data = new FixedData [declarators.Count];
+                       data = new Emitter [declarators.Count];
 
                        if (!expr_type.IsPointer){
                                Report.Error (209, loc, "Variables in a fixed statement must be pointers");
@@ -2925,8 +3489,8 @@ namespace Mono.CSharp {
                                LocalInfo vi = (LocalInfo) p.First;
                                Expression e = (Expression) p.Second;
 
-                               vi.VariableInfo = null;
-                               vi.ReadOnly = true;
+                               vi.VariableInfo.SetAssigned (ec);
+                               vi.SetReadOnlyContext (LocalInfo.ReadOnlyContext.Fixed);
 
                                //
                                // The rules for the possible declarators are pretty wise,
@@ -2950,7 +3514,6 @@ namespace Mono.CSharp {
                                if (e is Unary && ((Unary) e).Oper == Unary.Operator.AddressOf){
                                        Expression child = ((Unary) e).Expr;
 
-                                       vi.MakePinned ();
                                        if (child is ParameterReference || child is LocalVariableReference){
                                                Report.Error (
                                                        213, loc, 
@@ -2971,10 +3534,7 @@ namespace Mono.CSharp {
                                        if (!TypeManager.VerifyUnManaged (child.Type, loc))
                                                return false;
 
-                                       data [i].is_object = true;
-                                       data [i].expr = e;
-                                       data [i].converted = null;
-                                       data [i].vi = vi;
+                                       data [i] = new ExpressionEmitter (e, vi);
                                        i++;
 
                                        continue;
@@ -2992,7 +3552,6 @@ namespace Mono.CSharp {
                                if (e.Type.IsArray){
                                        Type array_type = TypeManager.GetElementType (e.Type);
                                        
-                                       vi.MakePinned ();
                                        //
                                        // Provided that array_type is unmanaged,
                                        //
@@ -3003,17 +3562,14 @@ namespace Mono.CSharp {
                                        // and T* is implicitly convertible to the
                                        // pointer type given in the fixed statement.
                                        //
-                                       ArrayPtr array_ptr = new ArrayPtr (e, loc);
+                                       ArrayPtr array_ptr = new ArrayPtr (e, array_type, loc);
                                        
                                        Expression converted = Convert.ImplicitConversionRequired (
                                                ec, array_ptr, vi.VariableType, loc);
                                        if (converted == null)
                                                return false;
 
-                                       data [i].is_object = false;
-                                       data [i].expr = e;
-                                       data [i].converted = converted;
-                                       data [i].vi = vi;
+                                       data [i] = new ExpressionEmitter (converted, vi);
                                        i++;
 
                                        continue;
@@ -3023,14 +3579,30 @@ namespace Mono.CSharp {
                                // Case 3: string
                                //
                                if (e.Type == TypeManager.string_type){
-                                       data [i].is_object = false;
-                                       data [i].expr = e;
-                                       data [i].converted = null;
-                                       data [i].vi = vi;
+                                       data [i] = new StringEmitter (e, vi, loc);
                                        i++;
                                        continue;
                                }
 
+                               // 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;
+                                       }
+                               }
+
                                //
                                // For other cases, flag a `this is already fixed expression'
                                //
@@ -3060,80 +3632,22 @@ namespace Mono.CSharp {
                
                protected override void DoEmit (EmitContext ec)
                {
-                       ILGenerator ig = ec.ig;
-
-                       LocalBuilder [] clear_list = new LocalBuilder [data.Length];
-                       
                        for (int i = 0; i < data.Length; i++) {
-                               LocalInfo vi = data [i].vi;
+                               data [i].Emit (ec);
+                       }
 
-                               //
-                               // Case 1: & object.
-                               //
-                               if (data [i].is_object) {
-                                       //
-                                       // Store pointer in pinned location
-                                       //
-                                       data [i].expr.Emit (ec);
-                                       ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
-                                       clear_list [i] = vi.LocalBuilder;
-                                       continue;
-                               }
-
-                               //
-                               // Case 2: Array
-                               //
-                               if (data [i].expr.Type.IsArray){
-                                       //
-                                       // Store pointer in pinned location
-                                       //
-                                       data [i].converted.Emit (ec);
-                                       
-                                       ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
-                                       clear_list [i] = vi.LocalBuilder;
-                                       continue;
-                               }
-
-                               //
-                               // Case 3: string
-                               //
-                               if (data [i].expr.Type == TypeManager.string_type){
-                                       LocalBuilder pinned_string = ig.DeclareLocal (TypeManager.string_type);
-                                       TypeManager.MakePinned (pinned_string);
-                                       clear_list [i] = pinned_string;
-                                       
-                                       data [i].expr.Emit (ec);
-                                       ig.Emit (OpCodes.Stloc, pinned_string);
-
-                                       Expression sptr = new StringPtr (pinned_string, loc);
-                                       Expression converted = Convert.ImplicitConversionRequired (
-                                               ec, sptr, vi.VariableType, loc);
-                                       
-                                       if (converted == null)
-                                               continue;
-
-                                       converted.Emit (ec);
-                                       ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
-                               }
-                       }
-
-                       statement.Emit (ec);
+                       statement.Emit (ec);
 
                        if (has_ret)
                                return;
 
+                       ILGenerator ig = ec.ig;
+
                        //
                        // Clear the pinned variable
                        //
                        for (int i = 0; i < data.Length; i++) {
-                               if (data [i].is_object || data [i].expr.Type.IsArray) {
-                                       ig.Emit (OpCodes.Ldc_I4_0);
-                                       ig.Emit (OpCodes.Conv_U);
-                                       ig.Emit (OpCodes.Stloc, clear_list [i]);
-                               } else if (data [i].expr.Type == TypeManager.string_type){
-                                       ig.Emit (OpCodes.Ldnull);
-                                       ig.Emit (OpCodes.Stloc, clear_list [i]);
-                               }
+                               data [i].EmitExit (ig);
                        }
                }
        }
@@ -3171,28 +3685,39 @@ namespace Mono.CSharp {
 
                public override bool Resolve (EmitContext ec)
                {
-                       if (type_expr != null) {
-                               type = ec.DeclSpace.ResolveType (type_expr, false, loc);
-                               if (type == null)
-                                       return false;
+                       bool was_catch = ec.InCatch;
+                       ec.InCatch = true;
+                       try {
+                               if (type_expr != null) {
+                                       TypeExpr te = type_expr.ResolveAsTypeTerminal (ec);
+                                       if (te == null)
+                                               return false;
 
-                               CheckObsolete (type);
+                                       type = te.ResolveType (ec);
 
-                               if (type != TypeManager.exception_type && !type.IsSubclassOf (TypeManager.exception_type)){
-                                       Error (155, "The type caught or thrown must be derived from System.Exception");
-                                       return false;
-                               }
-                       } else
-                               type = null;
+                                       CheckObsolete (type);
 
-                       return Block.Resolve (ec);
+                                       if (type != TypeManager.exception_type && !type.IsSubclassOf (TypeManager.exception_type)){
+                                               Error (155, "The type caught or thrown must be derived from System.Exception");
+                                               return false;
+                                       }
+                               } else
+                                       type = null;
+
+                               return Block.Resolve (ec);
+                       }
+                       finally {
+                               ec.InCatch = was_catch;
+                       }
                }
        }
 
-       public class Try : Statement {
+       public class Try : ExceptionStatement {
                public readonly Block Fini, Block;
                public readonly ArrayList Specific;
                public readonly Catch General;
+
+               bool need_exc_block;
                
                //
                // specific, general and fini might all be null.
@@ -3214,7 +3739,7 @@ namespace Mono.CSharp {
                {
                        bool ok = true;
                        
-                       ec.StartFlowBranching (FlowBranching.BranchingType.Exception, Block.StartLocation);
+                       FlowBranchingException branching = ec.StartFlowBranching (this);
 
                        Report.Debug (1, "START OF TRY BLOCK", Block.StartLocation);
 
@@ -3246,13 +3771,14 @@ namespace Mono.CSharp {
 
                                Type resolvedType = c.CatchType;
                                for (int ii = 0; ii < last_index; ++ii) {
-                                       if (resolvedType.IsSubclassOf (prevCatches [ii])) {
-                                               Report.Error_T (160, c.loc, prevCatches [ii].FullName);
+                                       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;
                                        }
                                }
 
                                prevCatches [last_index++] = resolvedType;
+                               need_exc_block = true;
                        }
 
                        Report.Debug (1, "END OF CATCH BLOCKS", ec.CurrentBranching);
@@ -3265,6 +3791,8 @@ namespace Mono.CSharp {
 
                                if (!General.Resolve (ec))
                                        ok = false;
+
+                               need_exc_block = true;
                        }
 
                        Report.Debug (1, "END OF GENERAL CATCH BLOCKS", ec.CurrentBranching);
@@ -3275,11 +3803,22 @@ namespace Mono.CSharp {
                                                Fini, FlowBranching.SiblingType.Finally);
 
                                Report.Debug (1, "STARTED SIBLING FOR FINALLY", ec.CurrentBranching, vector);
-
+                               bool was_finally = ec.InFinally;
+                               ec.InFinally = true;
                                if (!Fini.Resolve (ec))
                                        ok = false;
+                               ec.InFinally = was_finally;
+
+                               if (!ec.InIterator)
+                                       need_exc_block = true;
                        }
 
+                       if (ec.InIterator) {
+                               ResolveFinally (branching);
+                               need_exc_block |= emit_finally;
+                       } else
+                               emit_finally = Fini != null;
+
                        FlowBranching.Reachability reachability = ec.EndFlowBranching ();
 
                        FlowBranching.UsageVector f_vector = ec.CurrentBranching.CurrentUsageVector;
@@ -3287,9 +3826,10 @@ namespace Mono.CSharp {
                        Report.Debug (1, "END OF TRY", ec.CurrentBranching, reachability, vector, f_vector);
 
                        if (reachability.Returns != FlowBranching.FlowReturns.Always) {
-                               // Unfortunately, System.Reflection.Emit automatically emits a leave
-                               // to the end of the finally block.  This is a problem if `returns'
-                               // is true since we may jump to a point after the end of the method.
+                               // Unfortunately, System.Reflection.Emit automatically emits
+                               // a leave to the end of the finally block.  This is a problem
+                               // if `returns' is true since we may jump to a point after the
+                               // end of the method.
                                // As a workaround, emit an explicit ret here.
                                ec.NeedReturnLabel ();
                        }
@@ -3300,15 +3840,11 @@ namespace Mono.CSharp {
                protected override void DoEmit (EmitContext ec)
                {
                        ILGenerator ig = ec.ig;
-                       Label finish = ig.DefineLabel ();;
 
-                       ig.BeginExceptionBlock ();
+                       if (need_exc_block)
+                               ig.BeginExceptionBlock ();
                        Block.Emit (ec);
 
-                       //
-                       // System.Reflection.Emit provides this automatically:
-                       // ig.Emit (OpCodes.Leave, finish);
-
                        foreach (Catch c in Specific){
                                LocalInfo vi;
                                
@@ -3332,25 +3868,36 @@ namespace Mono.CSharp {
                                General.Block.Emit (ec);
                        }
 
-                       ig.MarkLabel (finish);
-                       if (Fini != null){
-                               ig.BeginFinallyBlock ();
+                       DoEmitFinally (ec);
+                       if (need_exc_block)
+                               ig.EndExceptionBlock ();
+               }
+
+               public override void EmitFinally (EmitContext ec)
+               {
+                       if (Fini != null)
                                Fini.Emit (ec);
+               }
+
+               public bool HasCatch
+               {
+                       get {
+                               return General != null || Specific.Count > 0;
                        }
-                       
-                       ig.EndExceptionBlock ();
                }
        }
 
-       public class Using : Statement {
+       public class Using : ExceptionStatement {
                object expression_or_block;
                Statement Statement;
                ArrayList var_list;
                Expression expr;
                Type expr_type;
                Expression conv;
+               Expression [] resolved_vars;
                Expression [] converted_vars;
                ExpressionStatement [] assign;
+               LocalBuilder local_copy;
                
                public Using (object expression_or_block, Statement stmt, Location l)
                {
@@ -3364,40 +3911,51 @@ namespace Mono.CSharp {
                //
                bool ResolveLocalVariableDecls (EmitContext ec)
                {
-                       bool need_conv = false;
-                       expr_type = ec.DeclSpace.ResolveType (expr, false, loc);
                        int i = 0;
 
-                       if (expr_type == null)
+                       TypeExpr texpr = expr.ResolveAsTypeTerminal (ec);
+                       if (texpr == null)
                                return false;
 
+                       expr_type = texpr.Type;
+
                        //
                        // 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];
-                       if (!TypeManager.ImplementsInterface (expr_type, TypeManager.idisposable_type)){
-                               foreach (DictionaryEntry e in var_list){
-                                       Expression var = (Expression) e.Key;
 
-                                       var = var.ResolveLValue (ec, new EmptyExpression ());
-                                       if (var == null)
-                                               return false;
-                                       
-                                       converted_vars [i] = Convert.ImplicitConversionRequired (
-                                               ec, var, TypeManager.idisposable_type, loc);
+                       bool need_conv = !TypeManager.ImplementsInterface (
+                               expr_type, TypeManager.idisposable_type);
 
-                                       if (converted_vars [i] == null)
-                                               return false;
+                       foreach (DictionaryEntry e in var_list){
+                               Expression var = (Expression) e.Key;
+
+                               var = var.ResolveLValue (ec, new EmptyExpression ());
+                               if (var == null)
+                                       return false;
+
+                               resolved_vars [i] = var;
+
+                               if (!need_conv) {
                                        i++;
+                                       continue;
                                }
-                               need_conv = true;
+
+                               converted_vars [i] = Convert.ImplicitConversionRequired (
+                                       ec, var, TypeManager.idisposable_type, loc);
+
+                               if (converted_vars [i] == null)
+                                       return false;
+
+                               i++;
                        }
 
                        i = 0;
                        foreach (DictionaryEntry e in var_list){
-                               LocalVariableReference var = (LocalVariableReference) e.Key;
+                               Expression var = resolved_vars [i];
                                Expression new_expr = (Expression) e.Value;
                                Expression a;
 
@@ -3418,11 +3976,11 @@ namespace Mono.CSharp {
                bool ResolveExpression (EmitContext ec)
                {
                        if (!TypeManager.ImplementsInterface (expr_type, TypeManager.idisposable_type)){
-                               conv = Convert.ImplicitConversionRequired (
-                                       ec, expr, TypeManager.idisposable_type, loc);
-
-                               if (conv == null)
+                               if (Convert.ImplicitConversion (ec, expr, TypeManager.idisposable_type, loc) == null) {
+                                       Report.Error (1674, loc, "'{0}': type used in a using statement must be implicitly convertible to 'System.IDisposable'",
+                                               TypeManager.CSharpName (expr_type));
                                        return false;
+                               }
                        }
 
                        return true;
@@ -3431,31 +3989,40 @@ namespace Mono.CSharp {
                //
                // Emits the code for the case of using using a local variable declaration.
                //
-               bool EmitLocalVariableDecls (EmitContext ec)
+               void EmitLocalVariableDecls (EmitContext ec)
                {
                        ILGenerator ig = ec.ig;
                        int i = 0;
 
                        for (i = 0; i < assign.Length; i++) {
                                assign [i].EmitStatement (ec);
-                               
-                               ig.BeginExceptionBlock ();
+
+                               if (emit_finally)
+                                       ig.BeginExceptionBlock ();
                        }
                        Statement.Emit (ec);
 
                        var_list.Reverse ();
-                       foreach (DictionaryEntry e in var_list){
-                               LocalVariableReference var = (LocalVariableReference) e.Key;
+
+                       DoEmitFinally (ec);
+               }
+
+               void EmitLocalVariableDeclFinally (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 ();
-                               i--;
                                
                                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);
+                                       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, TypeManager.idisposable_type, var.Type, "Dispose", Mono.CSharp.Location.Null);
 
@@ -3467,7 +4034,7 @@ namespace Mono.CSharp {
                                                MethodInfo mi = null;
 
                                                foreach (MethodInfo mk in ((MethodGroupExpr) ml).Methods) {
-                                                       if (mk.GetParameters().Length == 0) {
+                                                       if (TypeManager.GetArgumentTypes (mk).Length == 0) {
                                                                mi = mk;
                                                                break;
                                                        }
@@ -3475,47 +4042,85 @@ namespace Mono.CSharp {
 
                                                if (mi == null) {
                                                        Report.Error(-100, Mono.CSharp.Location.Null, "Internal error: No Dispose method which takes 0 parameters.");
-                                                       return false;
+                                                       return;
                                                }
 
-                                               var.AddressOf (ec, AddressOp.Load);
+                                               IMemoryLocation mloc = (IMemoryLocation) var;
+
+                                               mloc.AddressOf (ec, AddressOp.Load);
                                                ig.Emit (OpCodes.Call, mi);
                                        }
                                }
 
                                ig.MarkLabel (skip);
-                               ig.EndExceptionBlock ();
-                       }
 
-                       return false;
+                               if (emit_finally) {
+                                       ig.EndExceptionBlock ();
+                                       if (i > 0)
+                                               ig.BeginFinallyBlock ();
+                               }
+                       }
                }
 
-               bool EmitExpression (EmitContext ec)
+               void EmitExpression (EmitContext ec)
                {
                        //
                        // Make a copy of the expression and operate on that.
                        //
                        ILGenerator ig = ec.ig;
-                       LocalBuilder local_copy = ig.DeclareLocal (expr_type);
+                       local_copy = ig.DeclareLocal (expr_type);
                        if (conv != null)
                                conv.Emit (ec);
                        else
                                expr.Emit (ec);
                        ig.Emit (OpCodes.Stloc, local_copy);
 
-                       ig.BeginExceptionBlock ();
+                       if (emit_finally)
+                               ig.BeginExceptionBlock ();
+
                        Statement.Emit (ec);
                        
-                       Label skip = ig.DefineLabel ();
-                       ig.BeginFinallyBlock ();
-                       ig.Emit (OpCodes.Ldloc, local_copy);
-                       ig.Emit (OpCodes.Brfalse, skip);
-                       ig.Emit (OpCodes.Ldloc, local_copy);
-                       ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
-                       ig.MarkLabel (skip);
-                       ig.EndExceptionBlock ();
+                       DoEmitFinally (ec);
+                       if (emit_finally)
+                               ig.EndExceptionBlock ();
+               }
 
-                       return false;
+               void EmitExpressionFinally (EmitContext ec)
+               {
+                       ILGenerator ig = ec.ig;
+                       if (!local_copy.LocalType.IsValueType) {
+                               Label skip = ig.DefineLabel ();
+                               ig.Emit (OpCodes.Ldloc, local_copy);
+                               ig.Emit (OpCodes.Brfalse, skip);
+                               ig.Emit (OpCodes.Ldloc, local_copy);
+                               ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
+                               ig.MarkLabel (skip);
+                       } else {
+                               Expression ml = Expression.MemberLookup(ec, TypeManager.idisposable_type, local_copy.LocalType, "Dispose", Mono.CSharp.Location.Null);
+
+                               if (!(ml is MethodGroupExpr)) {
+                                       ig.Emit (OpCodes.Ldloc, local_copy);
+                                       ig.Emit (OpCodes.Box, local_copy.LocalType);
+                                       ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
+                               } else {
+                                       MethodInfo mi = null;
+
+                                       foreach (MethodInfo mk in ((MethodGroupExpr) ml).Methods) {
+                                               if (TypeManager.GetArgumentTypes (mk).Length == 0) {
+                                                       mi = mk;
+                                                       break;
+                                               }
+                                       }
+
+                                       if (mi == null) {
+                                               Report.Error(-100, Mono.CSharp.Location.Null, "Internal error: No Dispose method which takes 0 parameters.");
+                                               return;
+                                       }
+
+                                       ig.Emit (OpCodes.Ldloca, local_copy);
+                                       ig.Emit (OpCodes.Call, mi);
+                               }
+                       }
                }
                
                public override bool Resolve (EmitContext ec)
@@ -3540,7 +4145,7 @@ namespace Mono.CSharp {
                                        return false;
                        }
 
-                       ec.StartFlowBranching (FlowBranching.BranchingType.Exception, loc);
+                       FlowBranchingException branching = ec.StartFlowBranching (this);
 
                        bool ok = Statement.Resolve (ec);
 
@@ -3548,7 +4153,8 @@ namespace Mono.CSharp {
                                ec.KillFlowBranching ();
                                return false;
                        }
-                                       
+
+                       ResolveFinally (branching);                                     
                        FlowBranching.Reachability reachability = ec.EndFlowBranching ();
 
                        if (reachability.Returns != FlowBranching.FlowReturns.Always) {
@@ -3569,6 +4175,14 @@ namespace Mono.CSharp {
                        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);
+               }
        }
 
        /// <summary>
@@ -3579,10 +4193,8 @@ namespace Mono.CSharp {
                Expression variable;
                Expression expr;
                Statement statement;
-               ForeachHelperMethods hm;
-               Expression empty, conv;
-               Type array_type, element_type;
-               Type var_type;
+               ArrayForeach array;
+               CollectionForeach collection;
                
                public Foreach (Expression type, LocalVariableReference var, Expression expr,
                                Statement stmt, Location l)
@@ -3600,10 +4212,17 @@ namespace Mono.CSharp {
                        if (expr == null)
                                return false;
 
-                       var_type = ec.DeclSpace.ResolveType (type, false, loc);
-                       if (var_type == null)
+                       if (expr is NullLiteral) {
+                               Report.Error (186, expr.Location, "Use of null is not valid in this context");
                                return false;
-                       
+                       }
+
+                       TypeExpr texpr = type.ResolveAsTypeTerminal (ec);
+                       if (texpr == null)
+                               return false;
+
+                       Type var_type = texpr.Type;
+
                        //
                        // We need an instance variable.  Not sure this is the best
                        // way of doing this.
@@ -3613,595 +4232,666 @@ namespace Mono.CSharp {
                        //
                        if (!(expr.eclass == ExprClass.Variable || expr.eclass == ExprClass.Value ||
                              expr.eclass == ExprClass.PropertyAccess || expr.eclass == ExprClass.IndexerAccess)){
-                               error1579 (expr.Type);
+                               CollectionForeach.error1579 (expr.Type, loc);
                                return false;
                        }
 
                        if (expr.Type.IsArray) {
-                               array_type = expr.Type;
-                               element_type = TypeManager.GetElementType (array_type);
-
-                               empty = new EmptyExpression (element_type);
+                               array = new ArrayForeach (var_type, variable, expr, statement, loc);
+                               return array.Resolve (ec);
                        } else {
-                               hm = ProbeCollectionType (ec, expr.Type);
-                               if (hm == null){
-                                       error1579 (expr.Type);
-                                       return false;
-                               }                       
+                               collection = new CollectionForeach (
+                                       var_type, variable, expr, statement, loc);
+                               return collection.Resolve (ec);
+                       }
+               }
 
-                               array_type = expr.Type;
-                               element_type = hm.element_type;
+               protected override void DoEmit (EmitContext ec)
+               {
+                       ILGenerator ig = ec.ig;
+                       
+                       Label old_begin = ec.LoopBegin, old_end = ec.LoopEnd;
+                       ec.LoopBegin = ig.DefineLabel ();
+                       ec.LoopEnd = ig.DefineLabel ();
+
+                       if (collection != null)
+                               collection.Emit (ec);
+                       else
+                               array.Emit (ec);
+                       
+                       ec.LoopBegin = old_begin;
+                       ec.LoopEnd = old_end;
+               }
+
+               protected class TemporaryVariable : Expression, IMemoryLocation
+               {
+                       LocalInfo li;
 
-                               empty = new EmptyExpression (hm.element_type);
+                       public TemporaryVariable (Type type, Location loc)
+                       {
+                               this.type = type;
+                               this.loc = loc;
+                               eclass = ExprClass.Value;
                        }
 
-                       bool ok = true;
+                       public override Expression DoResolve (EmitContext ec)
+                       {
+                               if (li != null)
+                                       return this;
 
-                       ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
-                       ec.CurrentBranching.CreateSibling ();
+                               TypeExpr te = new TypeExpression (type, loc);
+                               li = ec.CurrentBlock.AddTemporaryVariable (te, loc);
+                               if (!li.Resolve (ec))
+                                       return null;
 
-                       //
-                       //
-                       // FIXME: maybe we can apply the same trick we do in the
-                       // array handling to avoid creating empty and conv in some cases.
-                       //
-                       // Although it is not as important in this case, as the type
-                       // will not likely be object (what the enumerator will return).
-                       //
-                       conv = Convert.ExplicitConversion (ec, empty, var_type, loc);
-                       if (conv == null)
-                               ok = false;
+                               AnonymousContainer am = ec.CurrentAnonymousMethod;
+                               if ((am != null) && am.IsIterator)
+                                       ec.CaptureVariable (li);
 
-                       variable = variable.ResolveLValue (ec, empty);
-                       if (variable == null)
-                               ok = false;
+                               return this;
+                       }
 
-                       bool disposable = (hm != null) && hm.is_disposable;
-                       if (disposable)
-                               ec.StartFlowBranching (FlowBranching.BranchingType.Exception, loc);
+                       public override void Emit (EmitContext ec)
+                       {
+                               ILGenerator ig = ec.ig;
 
-                       if (!statement.Resolve (ec))
-                               ok = false;
+                               if (li.FieldBuilder != null) {
+                                       ig.Emit (OpCodes.Ldarg_0);
+                                       ig.Emit (OpCodes.Ldfld, li.FieldBuilder);
+                               } else {
+                                       ig.Emit (OpCodes.Ldloc, li.LocalBuilder);
+                               }
+                       }
 
-                       if (disposable)
-                               ec.EndFlowBranching ();
+                       public void EmitLoadAddress (EmitContext ec)
+                       {
+                               ILGenerator ig = ec.ig;
 
-                       ec.EndFlowBranching ();
+                               if (li.FieldBuilder != null) {
+                                       ig.Emit (OpCodes.Ldarg_0);
+                                       ig.Emit (OpCodes.Ldflda, li.FieldBuilder);
+                               } else {
+                                       ig.Emit (OpCodes.Ldloca, li.LocalBuilder);
+                               }
+                       }
 
-                       return ok;
-               }
-               
-               //
-               // Retrieves a `public bool MoveNext ()' method from the Type `t'
-               //
-               static MethodInfo FetchMethodMoveNext (Type t)
-               {
-                       MemberList move_next_list;
-                       
-                       move_next_list = TypeContainer.FindMembers (
-                               t, MemberTypes.Method,
-                               BindingFlags.Public | BindingFlags.Instance,
-                               Type.FilterName, "MoveNext");
-                       if (move_next_list.Count == 0)
-                               return null;
+                       public void Store (EmitContext ec, Expression right_side)
+                       {
+                               if (li.FieldBuilder != null)
+                                       ec.ig.Emit (OpCodes.Ldarg_0);
 
-                       foreach (MemberInfo m in move_next_list){
-                               MethodInfo mi = (MethodInfo) m;
-                               Type [] args;
-                               
-                               args = TypeManager.GetArgumentTypes (mi);
-                               if (args != null && args.Length == 0){
-                                       if (mi.ReturnType == TypeManager.bool_type)
-                                               return mi;
+                               right_side.Emit (ec);
+                               if (li.FieldBuilder != null) {
+                                       ec.ig.Emit (OpCodes.Stfld, li.FieldBuilder);
+                               } else {
+                                       ec.ig.Emit (OpCodes.Stloc, li.LocalBuilder);
                                }
                        }
-                       return null;
-               }
-               
-               //
-               // Retrieves a `public T get_Current ()' method from the Type `t'
-               //
-               static MethodInfo FetchMethodGetCurrent (Type t)
-               {
-                       MemberList get_current_list;
 
-                       get_current_list = TypeContainer.FindMembers (
-                               t, MemberTypes.Method,
-                               BindingFlags.Public | BindingFlags.Instance,
-                               Type.FilterName, "get_Current");
-                       if (get_current_list.Count == 0)
-                               return null;
+                       public void EmitThis (EmitContext ec)
+                       {
+                               if (li.FieldBuilder != null) {
+                                       ec.ig.Emit (OpCodes.Ldarg_0);
+                               }
+                       }
 
-                       foreach (MemberInfo m in get_current_list){
-                               MethodInfo mi = (MethodInfo) m;
-                               Type [] args;
+                       public void EmitStore (ILGenerator ig)
+                       {
+                               if (li.FieldBuilder != null)
+                                       ig.Emit (OpCodes.Stfld, li.FieldBuilder);
+                               else
+                                       ig.Emit (OpCodes.Stloc, li.LocalBuilder);
+                       }
 
-                               args = TypeManager.GetArgumentTypes (mi);
-                               if (args != null && args.Length == 0)
-                                       return mi;
+                       public void AddressOf (EmitContext ec, AddressOp mode)
+                       {
+                               EmitLoadAddress (ec);
                        }
-                       return null;
                }
 
-               // 
-               // This struct records the helper methods used by the Foreach construct
-               //
-               class ForeachHelperMethods {
-                       public EmitContext ec;
-                       public MethodInfo get_enumerator;
-                       public MethodInfo move_next;
-                       public MethodInfo get_current;
-                       public Type element_type;
-                       public Type enumerator_type;
-                       public bool is_disposable;
-
-                       public ForeachHelperMethods (EmitContext ec)
+               protected class ArrayCounter : TemporaryVariable
+               {
+                       public ArrayCounter (Location loc)
+                               : base (TypeManager.int32_type, loc)
+                       { }
+
+                       public void Initialize (EmitContext ec)
+                       {
+                               EmitThis (ec);
+                               ec.ig.Emit (OpCodes.Ldc_I4_0);
+                               EmitStore (ec.ig);
+                       }
+
+                       public void Increment (EmitContext ec)
                        {
-                               this.ec = ec;
-                               this.element_type = TypeManager.object_type;
-                               this.enumerator_type = TypeManager.ienumerator_type;
-                               this.is_disposable = true;
+                               EmitThis (ec);
+                               Emit (ec);
+                               ec.ig.Emit (OpCodes.Ldc_I4_1);
+                               ec.ig.Emit (OpCodes.Add);
+                               EmitStore (ec.ig);
                        }
                }
-               
-               static bool GetEnumeratorFilter (MemberInfo m, object criteria)
+
+               protected class ArrayForeach : Statement
                {
-                       if (m == null)
-                               return false;
-                       
-                       if (!(m is MethodInfo))
-                               return false;
-                       
-                       if (m.Name != "GetEnumerator")
-                               return false;
+                       Expression variable, expr, conv;
+                       Statement statement;
+                       Type array_type;
+                       Type var_type;
+                       TemporaryVariable[] lengths;
+                       ArrayCounter[] counter;
+                       int rank;
 
-                       MethodInfo mi = (MethodInfo) m;
-                       Type [] args = TypeManager.GetArgumentTypes (mi);
-                       if (args != null){
-                               if (args.Length != 0)
-                                       return false;
+                       TemporaryVariable copy;
+                       Expression access;
+
+                       public ArrayForeach (Type var_type, Expression var,
+                                            Expression expr, Statement stmt, Location l)
+                       {
+                               this.var_type = var_type;
+                               this.variable = var;
+                               this.expr = expr;
+                               statement = stmt;
+                               loc = l;
                        }
-                       ForeachHelperMethods hm = (ForeachHelperMethods) criteria;
-                       EmitContext ec = hm.ec;
 
-                       //
-                       // Check whether GetEnumerator is accessible to us
-                       //
-                       MethodAttributes prot = mi.Attributes & MethodAttributes.MemberAccessMask;
+                       public override bool Resolve (EmitContext ec)
+                       {
+                               array_type = expr.Type;
+                               rank = array_type.GetArrayRank ();
 
-                       Type declaring = mi.DeclaringType;
-                       if (prot == MethodAttributes.Private){
-                               if (declaring != ec.ContainerType)
-                                       return false;
-                       } else if (prot == MethodAttributes.FamANDAssem){
-                               // If from a different assembly, false
-                               if (!(mi is MethodBuilder))
-                                       return false;
-                               //
-                               // Are we being invoked from the same class, or from a derived method?
-                               //
-                               if (ec.ContainerType != declaring){
-                                       if (!ec.ContainerType.IsSubclassOf (declaring))
-                                               return false;
+                               copy = new TemporaryVariable (array_type, loc);
+                               copy.Resolve (ec);
+
+                               counter = new ArrayCounter [rank];
+                               lengths = new TemporaryVariable [rank];
+
+                               ArrayList list = new ArrayList ();
+                               for (int i = 0; i < rank; i++) {
+                                       counter [i] = new ArrayCounter (loc);
+                                       counter [i].Resolve (ec);
+
+                                       lengths [i] = new TemporaryVariable (TypeManager.int32_type, loc);
+                                       lengths [i].Resolve (ec);
+
+                                       list.Add (counter [i]);
                                }
-                       } else if (prot == MethodAttributes.FamORAssem){
-                               if (!(mi is MethodBuilder ||
-                                     ec.ContainerType == declaring ||
-                                     ec.ContainerType.IsSubclassOf (declaring)))
+
+                               access = new ElementAccess (copy, list, loc).Resolve (ec);
+                               if (access == null)
                                        return false;
-                       } if (prot == MethodAttributes.Family){
-                               if (!(ec.ContainerType == declaring ||
-                                     ec.ContainerType.IsSubclassOf (declaring)))
+
+                               conv = Convert.ExplicitConversion (ec, access, var_type, loc);
+                               if (conv == null)
                                        return false;
+
+                               bool ok = true;
+
+                               ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
+                               ec.CurrentBranching.CreateSibling ();
+
+                               variable = variable.ResolveLValue (ec, conv);
+                               if (variable == null)
+                                       ok = false;
+
+                               if (!statement.Resolve (ec))
+                                       ok = false;
+
+                               ec.EndFlowBranching ();
+
+                               return ok;
                        }
 
-                       if ((mi.ReturnType == TypeManager.ienumerator_type) && (declaring == TypeManager.string_type))
-                               //
-                               // Apply the same optimization as MS: skip the GetEnumerator
-                               // returning an IEnumerator, and use the one returning a 
-                               // CharEnumerator instead. This allows us to avoid the 
-                               // try-finally block and the boxing.
-                               //
-                               return false;
+                       protected override void DoEmit (EmitContext ec)
+                       {
+                               ILGenerator ig = ec.ig;
 
-                       //
-                       // Ok, we can access it, now make sure that we can do something
-                       // with this `GetEnumerator'
-                       //
-                       
-                       Type return_type = mi.ReturnType;
-                       if (mi.ReturnType == TypeManager.ienumerator_type ||
-                           TypeManager.ienumerator_type.IsAssignableFrom (return_type) ||
-                           (!RootContext.StdLib && TypeManager.ImplementsInterface (return_type, TypeManager.ienumerator_type))) {
-                               
-                               //
-                               // If it is not an interface, lets try to find the methods ourselves.
-                               // For example, if we have:
-                               // public class Foo : IEnumerator { public bool MoveNext () {} public int Current { get {}}}
-                               // We can avoid the iface call. This is a runtime perf boost.
-                               // even bigger if we have a ValueType, because we avoid the cost
-                               // of boxing.
-                               //
-                               // We have to make sure that both methods exist for us to take
-                               // this path. If one of the methods does not exist, we will just
-                               // use the interface. Sadly, this complex if statement is the only
-                               // way I could do this without a goto
-                               //
-                               
-                               if (return_type.IsInterface ||
-                                   (hm.move_next = FetchMethodMoveNext (return_type)) == null ||
-                                   (hm.get_current = FetchMethodGetCurrent (return_type)) == null) {
-                                       
-                                       hm.move_next = TypeManager.bool_movenext_void;
-                                       hm.get_current = TypeManager.object_getcurrent_void;
-                                       return true;    
+                               copy.Store (ec, expr);
+
+                               Label[] test = new Label [rank];
+                               Label[] loop = new Label [rank];
+
+                               for (int i = 0; i < rank; i++) {
+                                       test [i] = ig.DefineLabel ();
+                                       loop [i] = ig.DefineLabel ();
+
+                                       lengths [i].EmitThis (ec);
+                                       ((ArrayAccess) access).EmitGetLength (ec, i);
+                                       lengths [i].EmitStore (ig);
                                }
 
-                       } else {
+                               for (int i = 0; i < rank; i++) {
+                                       counter [i].Initialize (ec);
 
-                               //
-                               // Ok, so they dont return an IEnumerable, we will have to
-                               // find if they support the GetEnumerator pattern.
-                               //
-                               
-                               hm.move_next = FetchMethodMoveNext (return_type);
-                               if (hm.move_next == null)
-                                       return false;
-                               
-                               hm.get_current = FetchMethodGetCurrent (return_type);
-                               if (hm.get_current == null)
-                                       return false;
-                       }
-                       
-                       hm.element_type = hm.get_current.ReturnType;
-                       hm.enumerator_type = return_type;
-                       hm.is_disposable = !hm.enumerator_type.IsSealed ||
-                               TypeManager.ImplementsInterface (
-                                       hm.enumerator_type, TypeManager.idisposable_type);
+                                       ig.Emit (OpCodes.Br, test [i]);
+                                       ig.MarkLabel (loop [i]);
+                               }
 
-                       return true;
-               }
-               
-               /// <summary>
-               ///   This filter is used to find the GetEnumerator method
-               ///   on which IEnumerator operates
-               /// </summary>
-               static MemberFilter FilterEnumerator;
-               
-               static Foreach ()
-               {
-                       FilterEnumerator = new MemberFilter (GetEnumeratorFilter);
-               }
+                               ((IAssignMethod) variable).EmitAssign (ec, conv, false, false);
 
-                void error1579 (Type t)
-                {
-                        Report.Error (1579, loc,
-                                      "foreach statement cannot operate on variables of type `" +
-                                      t.FullName + "' because that class does not provide a " +
-                                      " GetEnumerator method or it is inaccessible");
-                }
+                               statement.Emit (ec);
 
-               static bool TryType (Type t, ForeachHelperMethods hm)
-               {
-                       MemberList mi;
-                       
-                       mi = TypeContainer.FindMembers (t, MemberTypes.Method,
-                                                       BindingFlags.Public | BindingFlags.NonPublic |
-                                                       BindingFlags.Instance | BindingFlags.DeclaredOnly,
-                                                       FilterEnumerator, hm);
+                               ig.MarkLabel (ec.LoopBegin);
 
-                       if (mi.Count == 0)
-                               return false;
+                               for (int i = rank - 1; i >= 0; i--){
+                                       counter [i].Increment (ec);
+
+                                       ig.MarkLabel (test [i]);
+                                       counter [i].Emit (ec);
+                                       lengths [i].Emit (ec);
+                                       ig.Emit (OpCodes.Blt, loop [i]);
+                               }
 
-                       hm.get_enumerator = (MethodInfo) mi [0];
-                       return true;    
+                               ig.MarkLabel (ec.LoopEnd);
+                       }
                }
-               
-               //
-               // Looks for a usable GetEnumerator in the Type, and if found returns
-               // the three methods that participate: GetEnumerator, MoveNext and get_Current
-               //
-               ForeachHelperMethods ProbeCollectionType (EmitContext ec, Type t)
+
+               protected class CollectionForeach : ExceptionStatement
                {
-                       ForeachHelperMethods hm = new ForeachHelperMethods (ec);
+                       Expression variable, expr;
+                       Statement statement;
 
-                       for (Type tt = t; tt != null && tt != TypeManager.object_type;){
-                               if (TryType (tt, hm))
-                                       return hm;
-                               tt = tt.BaseType;
-                       }
+                       TemporaryVariable enumerator;
+                       Expression init;
+                       Statement loop;
 
-                       //
-                       // Now try to find the method in the interfaces
-                       //
-                       while (t != null){
-                               Type [] ifaces = t.GetInterfaces ();
+                       MethodGroupExpr get_enumerator;
+                       PropertyExpr get_current;
+                       MethodInfo move_next;
+                       Type var_type, enumerator_type;
+                       bool is_disposable;
 
-                               foreach (Type i in ifaces){
-                                       if (TryType (i, hm))
-                                               return hm;
+                       public CollectionForeach (Type var_type, Expression var,
+                                                 Expression expr, Statement stmt, Location l)
+                       {
+                               this.var_type = var_type;
+                               this.variable = var;
+                               this.expr = expr;
+                               statement = stmt;
+                               loc = l;
+                       }
+
+                       bool GetEnumeratorFilter (EmitContext ec, MethodInfo mi)
+                       {
+                               Type [] args = TypeManager.GetArgumentTypes (mi);
+                               if (args != null){
+                                       if (args.Length != 0)
+                                               return false;
                                }
-                               
+
+                               if (TypeManager.IsOverride (mi))
+                                       return false;
+                       
+                               // Check whether GetEnumerator is public
+                               if ((mi.Attributes & MethodAttributes.Public) != MethodAttributes.Public)
+                                       return false;
+
+                               if ((mi.ReturnType == TypeManager.ienumerator_type) && (mi.DeclaringType == TypeManager.string_type))
+                                       //
+                                       // Apply the same optimization as MS: skip the GetEnumerator
+                                       // returning an IEnumerator, and use the one returning a 
+                                       // CharEnumerator instead. This allows us to avoid the 
+                                       // try-finally block and the boxing.
+                                       //
+                                       return false;
+
                                //
-                               // Since TypeBuilder.GetInterfaces only returns the interface
-                               // types for this type, we have to keep looping, but once
-                               // we hit a non-TypeBuilder (ie, a Type), then we know we are
-                               // done, because it returns all the types
+                               // Ok, we can access it, now make sure that we can do something
+                               // with this `GetEnumerator'
                                //
-                               if ((t is TypeBuilder))
-                                       t = t.BaseType;
-                               else
-                                       break;
-                       } 
 
-                       return null;
-               }
+                               Type return_type = mi.ReturnType;
+                               if (mi.ReturnType == TypeManager.ienumerator_type ||
+                                   TypeManager.ienumerator_type.IsAssignableFrom (return_type) ||
+                                   (!RootContext.StdLib && TypeManager.ImplementsInterface (return_type, TypeManager.ienumerator_type))) {
+                                       //
+                                       // If it is not an interface, lets try to find the methods ourselves.
+                                       // For example, if we have:
+                                       // public class Foo : IEnumerator { public bool MoveNext () {} public int Current { get {}}}
+                                       // We can avoid the iface call. This is a runtime perf boost.
+                                       // even bigger if we have a ValueType, because we avoid the cost
+                                       // of boxing.
+                                       //
+                                       // We have to make sure that both methods exist for us to take
+                                       // this path. If one of the methods does not exist, we will just
+                                       // use the interface. Sadly, this complex if statement is the only
+                                       // way I could do this without a goto
+                                       //
 
-               //
-               // FIXME: possible optimization.
-               // We might be able to avoid creating `empty' if the type is the sam
-               //
-               bool EmitCollectionForeach (EmitContext ec)
-               {
-                       ILGenerator ig = ec.ig;
-                       VariableStorage enumerator;
+                                       if (return_type.IsInterface ||
+                                           !FetchMoveNext (ec, return_type) ||
+                                           !FetchGetCurrent (ec, return_type)) {
+                                               move_next = TypeManager.bool_movenext_void;
+                                               get_current = new PropertyExpr (
+                                                       ec, TypeManager.ienumerator_getcurrent, loc);
+                                               return true;
+                                       }
+                               } else {
+                                       //
+                                       // Ok, so they dont return an IEnumerable, we will have to
+                                       // find if they support the GetEnumerator pattern.
+                                       //
 
-                       enumerator = new VariableStorage (ec, hm.enumerator_type);
-                       enumerator.EmitThis ();
-                       //
-                       // Instantiate the enumerator
-                       //
-                       if (expr.Type.IsValueType){
-                               if (expr is IMemoryLocation){
-                                       IMemoryLocation ml = (IMemoryLocation) expr;
+                                       if (!FetchMoveNext (ec, return_type))
+                                               return false;
 
-                                       Expression ml1 = Expression.MemberLookup(ec, TypeManager.ienumerator_type, expr.Type, "GetEnumerator", Mono.CSharp.Location.Null);
+                                       if (!FetchGetCurrent (ec, return_type))
+                                               return false;
+                               }
 
-                                       if (!(ml1 is MethodGroupExpr)) {
-                                               expr.Emit(ec);
-                                               ec.ig.Emit(OpCodes.Box, expr.Type);
-                                       } else {
-                                               ml.AddressOf (ec, AddressOp.Load);
-                                       }
-                               } else
-                                       throw new Exception ("Expr " + expr + " of type " + expr.Type +
-                                                            " does not implement IMemoryLocation");
-                               ig.Emit (OpCodes.Callvirt, hm.get_enumerator);
-                       } else {
-                               expr.Emit (ec);
-                               ig.Emit (OpCodes.Callvirt, hm.get_enumerator);
+                               enumerator_type = return_type;
+                               is_disposable = !enumerator_type.IsSealed ||
+                                       TypeManager.ImplementsInterface (
+                                               enumerator_type, TypeManager.idisposable_type);
+
+                               return true;
                        }
-                       enumerator.EmitStore ();
 
                        //
-                       // Protect the code in a try/finalize block, so that
-                       // if the beast implement IDisposable, we get rid of it
+                       // Retrieves a `public bool MoveNext ()' method from the Type `t'
                        //
-                       if (hm.is_disposable)
-                               ig.BeginExceptionBlock ();
-                       
-                       Label end_try = ig.DefineLabel ();
-                       
-                       ig.MarkLabel (ec.LoopBegin);
-                       
-                       enumerator.EmitCall (hm.move_next);
-                       
-                       ig.Emit (OpCodes.Brfalse, end_try);
-                       if (ec.InIterator)
-                               ec.EmitThis ();
-                       
-                       enumerator.EmitCall (hm.get_current);
+                       bool FetchMoveNext (EmitContext ec, Type t)
+                       {
+                               MemberList move_next_list;
 
-                       if (ec.InIterator){
-                               conv.Emit (ec);
-                               ig.Emit (OpCodes.Stfld, ((FieldExpr) variable).FieldInfo);
-                       } else 
-                               ((IAssignMethod)variable).EmitAssign (ec, conv);
+                               move_next_list = TypeContainer.FindMembers (
+                                       t, MemberTypes.Method,
+                                       BindingFlags.Public | BindingFlags.Instance,
+                                       Type.FilterName, "MoveNext");
+                               if (move_next_list.Count == 0)
+                                       return false;
+
+                               foreach (MemberInfo m in move_next_list){
+                                       MethodInfo mi = (MethodInfo) m;
+                                       Type [] args;
                                
-                       statement.Emit (ec);
-                       ig.Emit (OpCodes.Br, ec.LoopBegin);
-                       ig.MarkLabel (end_try);
-                       
-                       // The runtime provides this for us.
-                       // ig.Emit (OpCodes.Leave, end);
+                                       args = TypeManager.GetArgumentTypes (mi);
+                                       if ((args != null) && (args.Length == 0) &&
+                                           TypeManager.TypeToCoreType (mi.ReturnType) == TypeManager.bool_type) {
+                                               move_next = mi;
+                                               return true;
+                                       }
+                               }
 
+                               return false;
+                       }
+               
                        //
-                       // Now the finally block
+                       // Retrieves a `public T get_Current ()' method from the Type `t'
                        //
-                       if (hm.is_disposable) {
-                               Label call_dispose = ig.DefineLabel ();
-                               ig.BeginFinallyBlock ();
+                       bool FetchGetCurrent (EmitContext ec, Type t)
+                       {
+                               PropertyExpr pe = Expression.MemberLookup (
+                                       ec, t, "Current", MemberTypes.Property,
+                                       Expression.AllBindingFlags, loc) as PropertyExpr;
+                               if (pe == null)
+                                       return false;
 
-                               enumerator.EmitThis ();
-                               enumerator.EmitLoad ();
-                               ig.Emit (OpCodes.Isinst, TypeManager.idisposable_type);
-                               ig.Emit (OpCodes.Dup);
-                               ig.Emit (OpCodes.Brtrue_S, call_dispose);
-                               ig.Emit (OpCodes.Pop);
-                               ig.Emit (OpCodes.Endfinally);
-                               
-                               ig.MarkLabel (call_dispose);
-                               ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
-                               
+                               get_current = pe;
+                               return true;
+                       }
 
-                               // The runtime generates this anyways.
-                               // ig.Emit (OpCodes.Endfinally);
+                       // 
+                       // Retrieves a `public void Dispose ()' method from the Type `t'
+                       //
+                       static MethodInfo FetchMethodDispose (Type t)
+                       {
+                               MemberList dispose_list;
 
-                               ig.EndExceptionBlock ();
+                               dispose_list = TypeContainer.FindMembers (
+                                       t, MemberTypes.Method,
+                                       BindingFlags.Public | BindingFlags.Instance,
+                                       Type.FilterName, "Dispose");
+                               if (dispose_list.Count == 0)
+                                       return null;
+
+                               foreach (MemberInfo m in dispose_list){
+                                       MethodInfo mi = (MethodInfo) m;
+                                       Type [] args;
+
+                                       args = TypeManager.GetArgumentTypes (mi);
+                                       if (args != null && args.Length == 0){
+                                               if (mi.ReturnType == TypeManager.void_type)
+                                                       return mi;
+                                       }
+                               }
+                               return null;
                        }
 
-                       ig.MarkLabel (ec.LoopEnd);
-                       return false;
-               }
+                       static public void error1579 (Type t, Location loc)
+                       {
+                               Report.Error (1579, loc, "foreach statement cannot operate on " +
+                                             "variables of type `{0}' because that class does " +
+                                             "not provide a GetEnumerator method or it is " +
+                                             "inaccessible", t.FullName);
+                       }
 
-               //
-               // FIXME: possible optimization.
-               // We might be able to avoid creating `empty' if the type is the sam
-               //
-               bool EmitArrayForeach (EmitContext ec)
-               {
-                       int rank = array_type.GetArrayRank ();
-                       ILGenerator ig = ec.ig;
+                       bool TryType (EmitContext ec, Type t)
+                       {
+                               MethodGroupExpr mg = Expression.MemberLookup (
+                                       ec, t, "GetEnumerator", MemberTypes.Method,
+                                       Expression.AllBindingFlags, loc) as MethodGroupExpr;
+                               if (mg == null)
+                                       return false;
 
-                       VariableStorage copy = new VariableStorage (ec, array_type);
-                       
-                       //
-                       // Make our copy of the array
-                       //
-                       copy.EmitThis ();
-                       expr.Emit (ec);
-                       copy.EmitStore ();
-                       
-                       if (rank == 1){
-                               VariableStorage counter = new VariableStorage (ec,TypeManager.int32_type);
+                               foreach (MethodBase mb in mg.Methods) {
+                                       if (!GetEnumeratorFilter (ec, (MethodInfo) mb))
+                                               continue;
 
-                               Label loop, test;
+                                       MethodInfo[] mi = new MethodInfo[] { (MethodInfo) mb };
+                                       get_enumerator = new MethodGroupExpr (mi, loc);
 
-                               counter.EmitThis ();
-                               ig.Emit (OpCodes.Ldc_I4_0);
-                               counter.EmitStore ();
-                               test = ig.DefineLabel ();
-                               ig.Emit (OpCodes.Br, test);
+                                       if (t != expr.Type) {
+                                               expr = Convert.ExplicitConversion (
+                                                       ec, expr, t, loc);
+                                               if (expr == null)
+                                                       throw new InternalErrorException ();
+                                       }
 
-                               loop = ig.DefineLabel ();
-                               ig.MarkLabel (loop);
+                                       get_enumerator.InstanceExpression = expr;
+                                       get_enumerator.IsBase = t != expr.Type;
 
-                               if (ec.InIterator)
-                                       ec.EmitThis ();
-                               
-                               copy.EmitThis ();
-                               copy.EmitLoad ();
-                               counter.EmitThis ();
-                               counter.EmitLoad ();
+                                       return true;
+                               }
+
+                               return false;
+                       }               
+
+                       bool ProbeCollectionType (EmitContext ec, Type t)
+                       {
+                               for (Type tt = t; tt != null && tt != TypeManager.object_type;){
+                                       if (TryType (ec, tt))
+                                               return true;
+                                       tt = tt.BaseType;
+                               }
 
                                //
-                               // Load the value, we load the value using the underlying type,
-                               // then we use the variable.EmitAssign to load using the proper cast.
+                               // Now try to find the method in the interfaces
                                //
-                               ArrayAccess.EmitLoadOpcode (ig, element_type);
-                               if (ec.InIterator){
-                                       conv.Emit (ec);
-                                       ig.Emit (OpCodes.Stfld, ((FieldExpr) variable).FieldInfo);
-                               } else 
-                                       ((IAssignMethod)variable).EmitAssign (ec, conv);
+                               while (t != null){
+                                       Type [] ifaces = t.GetInterfaces ();
 
-                               statement.Emit (ec);
-
-                               ig.MarkLabel (ec.LoopBegin);
-                               counter.EmitThis ();
-                               counter.EmitThis ();
-                               counter.EmitLoad ();
-                               ig.Emit (OpCodes.Ldc_I4_1);
-                               ig.Emit (OpCodes.Add);
-                               counter.EmitStore ();
-
-                               ig.MarkLabel (test);
-                               counter.EmitThis ();
-                               counter.EmitLoad ();
-                               copy.EmitThis ();
-                               copy.EmitLoad ();
-                               ig.Emit (OpCodes.Ldlen);
-                               ig.Emit (OpCodes.Conv_I4);
-                               ig.Emit (OpCodes.Blt, loop);
-                       } else {
-                               VariableStorage [] dim_len   = new VariableStorage [rank];
-                               VariableStorage [] dim_count = new VariableStorage [rank];
-                               Label [] loop = new Label [rank];
-                               Label [] test = new Label [rank];
-                               int dim;
+                                       foreach (Type i in ifaces){
+                                               if (TryType (ec, i))
+                                                       return true;
+                                       }
                                
-                               for (dim = 0; dim < rank; dim++){
-                                       dim_len [dim] = new VariableStorage (ec, TypeManager.int32_type);
-                                       dim_count [dim] = new VariableStorage (ec, TypeManager.int32_type);
-                                       test [dim] = ig.DefineLabel ();
-                                       loop [dim] = ig.DefineLabel ();
-                               }
-                                       
-                               for (dim = 0; dim < rank; dim++){
-                                       dim_len [dim].EmitThis ();
-                                       copy.EmitThis ();
-                                       copy.EmitLoad ();
-                                       IntLiteral.EmitInt (ig, dim);
-                                       ig.Emit (OpCodes.Callvirt, TypeManager.int_getlength_int);
-                                       dim_len [dim].EmitStore ();
-                                       
+                                       //
+                                       // Since TypeBuilder.GetInterfaces only returns the interface
+                                       // types for this type, we have to keep looping, but once
+                                       // we hit a non-TypeBuilder (ie, a Type), then we know we are
+                                       // done, because it returns all the types
+                                       //
+                                       if ((t is TypeBuilder))
+                                               t = t.BaseType;
+                                       else
+                                               break;
                                }
 
-                               for (dim = 0; dim < rank; dim++){
-                                       dim_count [dim].EmitThis ();
-                                       ig.Emit (OpCodes.Ldc_I4_0);
-                                       dim_count [dim].EmitStore ();
-                                       ig.Emit (OpCodes.Br, test [dim]);
-                                       ig.MarkLabel (loop [dim]);
+                               return false;
+                       }
+
+                       public override bool Resolve (EmitContext ec)
+                       {
+                               enumerator_type = TypeManager.ienumerator_type;
+                               is_disposable = true;
+
+                               if (!ProbeCollectionType (ec, expr.Type)) {
+                                       error1579 (expr.Type, loc);
+                                       return false;
                                }
 
-                               if (ec.InIterator)
-                                       ec.EmitThis ();
-                               copy.EmitThis ();
-                               copy.EmitLoad ();
-                               for (dim = 0; dim < rank; dim++){
-                                       dim_count [dim].EmitThis ();
-                                       dim_count [dim].EmitLoad ();
+                               enumerator = new TemporaryVariable (enumerator_type, loc);
+                               enumerator.Resolve (ec);
+
+                               init = new Invocation (get_enumerator, new ArrayList (), loc);
+                               init = init.Resolve (ec);
+                               if (init == null)
+                                       return false;
+
+                               Expression move_next_expr;
+                               {
+                                       MemberInfo[] mi = new MemberInfo[] { move_next };
+                                       MethodGroupExpr mg = new MethodGroupExpr (mi, loc);
+                                       mg.InstanceExpression = enumerator;
+
+                                       move_next_expr = new Invocation (mg, new ArrayList (), loc);
                                }
 
+                               get_current.InstanceExpression = enumerator;
+
+                               Statement block = new CollectionForeachStatement (
+                                       var_type, variable, get_current, statement, loc);
+
+                               loop = new While (move_next_expr, block, loc);
+
+                               bool ok = true;
+
+                               ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
+                               ec.CurrentBranching.CreateSibling ();
+
+                               FlowBranchingException branching = null;
+                               if (is_disposable)
+                                       branching = ec.StartFlowBranching (this);
+
+                               if (!loop.Resolve (ec))
+                                       ok = false;
+
+                               if (is_disposable) {
+                                       ResolveFinally (branching);
+                                       ec.EndFlowBranching ();
+                               } else
+                                       emit_finally = true;
+
+                               ec.EndFlowBranching ();
+
+                               return ok;
+                       }
+
+                       protected override void DoEmit (EmitContext ec)
+                       {
+                               ILGenerator ig = ec.ig;
+
+                               enumerator.Store (ec, init);
+
                                //
-                               // FIXME: Maybe we can cache the computation of `get'?
+                               // Protect the code in a try/finalize block, so that
+                               // if the beast implement IDisposable, we get rid of it
                                //
-                               Type [] args = new Type [rank];
-                               MethodInfo get;
-
-                               for (int i = 0; i < rank; i++)
-                                       args [i] = TypeManager.int32_type;
-
-                               ModuleBuilder mb = CodeGen.Module.Builder;
-                               get = mb.GetArrayMethod (
-                                       array_type, "Get",
-                                       CallingConventions.HasThis| CallingConventions.Standard,
-                                       var_type, args);
-                               ig.Emit (OpCodes.Call, get);
-                               if (ec.InIterator){
-                                       conv.Emit (ec);
-                                       ig.Emit (OpCodes.Stfld, ((FieldExpr) variable).FieldInfo);
-                               } else 
-                                       ((IAssignMethod)variable).EmitAssign (ec, conv);
-                               statement.Emit (ec);
-                               ig.MarkLabel (ec.LoopBegin);
-                               for (dim = rank - 1; dim >= 0; dim--){
-                                       dim_count [dim].EmitThis ();
-                                       dim_count [dim].EmitThis ();
-                                       dim_count [dim].EmitLoad ();
-                                       ig.Emit (OpCodes.Ldc_I4_1);
-                                       ig.Emit (OpCodes.Add);
-                                       dim_count [dim].EmitStore ();
-
-                                       ig.MarkLabel (test [dim]);
-                                       dim_count [dim].EmitThis ();
-                                       dim_count [dim].EmitLoad ();
-                                       dim_len [dim].EmitThis ();
-                                       dim_len [dim].EmitLoad ();
-                                       ig.Emit (OpCodes.Blt, loop [dim]);
+                               if (is_disposable && emit_finally)
+                                       ig.BeginExceptionBlock ();
+                       
+                               loop.Emit (ec);
+
+                               //
+                               // Now the finally block
+                               //
+                               if (is_disposable) {
+                                       DoEmitFinally (ec);
+                                       if (emit_finally)
+                                               ig.EndExceptionBlock ();
+                               }
+                       }
+
+
+                       public override void EmitFinally (EmitContext ec)
+                       {
+                               ILGenerator ig = ec.ig;
+
+                               if (enumerator_type.IsValueType) {
+                                       enumerator.Emit (ec);
+
+                                       MethodInfo mi = FetchMethodDispose (enumerator_type);
+                                       if (mi != null) {
+                                               enumerator.EmitLoadAddress (ec);
+                                               ig.Emit (OpCodes.Call, mi);
+                                       } else {
+                                               enumerator.Emit (ec);
+                                               ig.Emit (OpCodes.Box, enumerator_type);
+                                               ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
+                                       }
+                               } else {
+                                       Label call_dispose = ig.DefineLabel ();
+
+                                       enumerator.Emit (ec);
+                                       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);
+
+                                       ig.MarkLabel (call_dispose);
+                                       ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
+                                       ig.MarkLabel (end_finally);
                                }
                        }
-                       ig.MarkLabel (ec.LoopEnd);
-                       
-                       return false;
                }
-               
-               protected override void DoEmit (EmitContext ec)
+
+               protected class CollectionForeachStatement : Statement
                {
-                       ILGenerator ig = ec.ig;
-                       
-                       Label old_begin = ec.LoopBegin, old_end = ec.LoopEnd;
-                       ec.LoopBegin = ig.DefineLabel ();
-                       ec.LoopEnd = ig.DefineLabel ();
-                       
-                       if (hm != null)
-                               EmitCollectionForeach (ec);
-                       else
-                               EmitArrayForeach (ec);
-                       
-                       ec.LoopBegin = old_begin;
-                       ec.LoopEnd = old_end;
+                       Type type;
+                       Expression variable, current, conv;
+                       Statement statement;
+                       Assign assign;
+
+                       public CollectionForeachStatement (Type type, Expression variable,
+                                                          Expression current, Statement statement,
+                                                          Location loc)
+                       {
+                               this.type = type;
+                               this.variable = variable;
+                               this.current = current;
+                               this.statement = statement;
+                               this.loc = loc;
+                       }
+
+                       public override bool Resolve (EmitContext ec)
+                       {
+                               current = current.Resolve (ec);
+                               if (current == null)
+                                       return false;
+
+                               conv = Convert.ExplicitConversion (ec, current, type, loc);
+                               if (conv == null)
+                                       return false;
+
+                               assign = new Assign (variable, conv, loc);
+                               if (assign.Resolve (ec) == null)
+                                       return false;
+
+                               if (!statement.Resolve (ec))
+                                       return false;
+
+                               return true;
+                       }
+
+                       protected override void DoEmit (EmitContext ec)
+                       {
+                               assign.EmitStatement (ec);
+                               statement.Emit (ec);
+                       }
                }
        }
 }