Fix Firebird 'make dist' and build
[mono.git] / mcs / gmcs / expression.cs
old mode 100755 (executable)
new mode 100644 (file)
index 889d3eb..1d35cb5
@@ -46,13 +46,13 @@ namespace Mono.CSharp {
                public override void Emit (EmitContext ec)
                {
                        if (args != null) 
-                               Invocation.EmitArguments (ec, mi, args);
+                               Invocation.EmitArguments (ec, mi, args, false, null);
 
                        ec.ig.Emit (OpCodes.Call, mi);
                        return;
                }
                
-               static public Expression MakeSimpleCall (EmitContext ec, MethodGroupExpr mg,
+               static public StaticCallExpr MakeSimpleCall (EmitContext ec, MethodGroupExpr mg,
                                                         Expression e, Location loc)
                {
                        ArrayList args;
@@ -81,16 +81,20 @@ namespace Mono.CSharp {
                        if (TypeManager.TypeToCoreType (type) != TypeManager.void_type)
                                ec.ig.Emit (OpCodes.Pop);
                }
+               
+               public MethodInfo Method {
+                       get { return mi; }
+               }
        }
 
        public class ParenthesizedExpression : Expression
        {
                public Expression Expr;
 
-               public ParenthesizedExpression (Expression expr, Location loc)
+               public ParenthesizedExpression (Expression expr)
                {
                        this.Expr = expr;
-                       this.loc = loc;
+                       this.loc = expr.Location;
                }
 
                public override Expression DoResolve (EmitContext ec)
@@ -169,10 +173,8 @@ namespace Mono.CSharp {
 
                void Error23 (Type t)
                {
-                       Error (
-                               23, "Operator " + OperName (Oper) +
-                               " cannot be applied to operand of type `" +
-                               TypeManager.CSharpName (t) + "'");
+                       Report.Error (23, loc, "Operator `{0}' cannot be applied to operand of type `{1}'",
+                               OperName (Oper), TypeManager.CSharpName (t));
                }
 
                /// <remarks>
@@ -213,6 +215,10 @@ namespace Mono.CSharp {
                                e = new IntConstant (-((ShortConstant) expr).Value);
                        else if (expr is UShortConstant)
                                e = new IntConstant (-((UShortConstant) expr).Value);
+                       else if (expr is SByteConstant)
+                               e = new IntConstant (-((SByteConstant) expr).Value);
+                       else if (expr is ByteConstant)
+                               e = new IntConstant (-((ByteConstant) expr).Value);
                        return e;
                }
 
@@ -228,12 +234,18 @@ namespace Mono.CSharp {
                        
                        switch (Oper){
                        case Operator.UnaryPlus:
+                               if (expr_type == TypeManager.bool_type){
+                                       result = null;
+                                       Error23 (expr_type);
+                                       return false;
+                               }
+                               
                                result = e;
                                return true;
                                
                        case Operator.UnaryNegation:
                                result = TryReduceNegative (e);
-                               return true;
+                               return result != null;
                                
                        case Operator.LogicalNot:
                                if (expr_type != TypeManager.bool_type) {
@@ -319,11 +331,22 @@ namespace Mono.CSharp {
 
                Expression ResolveOperator (EmitContext ec)
                {
-                       Type expr_type = Expr.Type;
+                       //
+                       // Step 1: Default operations on CLI native types.
+                       //
+
+                       // Attempt to use a constant folding operation.
+                       if (Expr is Constant){
+                               Expression result;
+                               
+                               if (Reduce (ec, (Constant) Expr, out result))
+                                       return result;
+                       }
 
                        //
-                       // Step 1: Perform Operator Overload location
+                       // Step 2: Perform Operator Overload location
                        //
+                       Type expr_type = Expr.Type;
                        Expression mg;
                        string op_name;
                        
@@ -349,18 +372,6 @@ namespace Mono.CSharp {
                        if (expr_type == null)
                                return null;
                        
-                       //
-                       // Step 2: Default operations on CLI native types.
-                       //
-
-                       // Attempt to use a constant folding operation.
-                       if (Expr is Constant){
-                               Expression result;
-                               
-                               if (Reduce (ec, (Constant) Expr, out result))
-                                       return result;
-                       }
-
                        switch (Oper){
                        case Operator.LogicalNot:
                                if (expr_type != TypeManager.bool_type) {
@@ -383,37 +394,28 @@ namespace Mono.CSharp {
                                        Expression e;
 
                                        e = Convert.ImplicitConversion (ec, Expr, TypeManager.int32_type, loc);
-                                       if (e != null){
-                                               type = TypeManager.int32_type;
-                                               return this;
-                                       }
+                                       if (e != null)
+                                               goto ok;
                                        e = Convert.ImplicitConversion (ec, Expr, TypeManager.uint32_type, loc);
-                                       if (e != null){
-                                               type = TypeManager.uint32_type;
-                                               return this;
-                                       }
+                                       if (e != null)
+                                               goto ok;
                                        e = Convert.ImplicitConversion (ec, Expr, TypeManager.int64_type, loc);
-                                       if (e != null){
-                                               type = TypeManager.int64_type;
-                                               return this;
-                                       }
+                                       if (e != null)
+                                               goto ok;
                                        e = Convert.ImplicitConversion (ec, Expr, TypeManager.uint64_type, loc);
-                                       if (e != null){
-                                               type = TypeManager.uint64_type;
-                                               return this;
-                                       }
+                                       if (e != null)
+                                               goto ok;
                                        Error23 (expr_type);
                                        return null;
+                               ok:
+                                       Expr = e;
+                                       expr_type = e.Type;
                                }
+
                                type = expr_type;
                                return this;
 
                        case Operator.AddressOf:
-                               if (Expr.eclass != ExprClass.Variable){
-                                       Error (211, "Cannot take the address of non-variables");
-                                       return null;
-                               }
-                               
                                if (!ec.InUnsafe) {
                                        UnsafeError (loc); 
                                        return null;
@@ -424,17 +426,29 @@ namespace Mono.CSharp {
                                }
 
                                IVariable variable = Expr as IVariable;
-                               if (!ec.InFixedInitializer && ((variable == null) || !variable.VerifyFixed (false))) {
-                                       Error (212, "You can only take the address of an unfixed expression inside " +
+                               bool is_fixed = variable != null && variable.VerifyFixed ();
+
+                               if (!ec.InFixedInitializer && !is_fixed) {
+                                       Error (212, "You can only take the address of unfixed expression inside " +
                                               "of a fixed statement initializer");
                                        return null;
                                }
 
-                               if (ec.InFixedInitializer && ((variable != null) && variable.VerifyFixed (false))) {
-                                       Error (213, "You can not fix an already fixed expression");
+                               if (ec.InFixedInitializer && is_fixed) {
+                                       Error (213, "You cannot use the fixed statement to take the address of an already fixed expression");
                                        return null;
                                }
 
+                               LocalVariableReference lr = Expr as LocalVariableReference;
+                               if (lr != null){
+                                       if (lr.local_info.IsCaptured){
+                                               AnonymousMethod.Error_AddressOfCapturedVar (lr.Name, loc);
+                                               return null;
+                                       }
+                                       lr.local_info.AddressTaken = true;
+                                       lr.local_info.Used = true;
+                               }
+
                                // According to the specs, a variable is considered definitely assigned if you take
                                // its address.
                                if ((variable != null) && (variable.VariableInfo != null))
@@ -450,7 +464,7 @@ namespace Mono.CSharp {
                                }
                                
                                if (!expr_type.IsPointer){
-                                       Error (193, "The * or -> operator can only be applied to pointers");
+                                       Error (193, "The * or -> operator must be applied to a pointer");
                                        return null;
                                }
                                
@@ -556,14 +570,23 @@ namespace Mono.CSharp {
 
                public override Expression DoResolve (EmitContext ec)
                {
-                       if (Oper == Operator.AddressOf)
-                               Expr = Expr.ResolveLValue (ec, new EmptyExpression ());
+                       if (Oper == Operator.AddressOf) {
+                               Expr = Expr.DoResolveLValue (ec, new EmptyExpression ());
+
+                               if (Expr == null || Expr.eclass != ExprClass.Variable){
+                                       Error (211, "Cannot take the address of the given expression");
+                                       return null;
+                               }
+                       }
                        else
                                Expr = Expr.Resolve (ec);
                        
                        if (Expr == null)
                                return null;
 
+                       if (TypeManager.IsNullableType (Expr.Type))
+                               return new Nullable.LiftedUnaryOperator (Oper, Expr, loc).Resolve (ec);
+
                        eclass = ExprClass.Value;
                        return ResolveOperator (ec);
                }
@@ -571,10 +594,8 @@ namespace Mono.CSharp {
                public override Expression DoResolveLValue (EmitContext ec, Expression right)
                {
                        if (Oper == Operator.Indirection)
-                               return base.DoResolveLValue (ec, right);
+                               return DoResolve (ec);
 
-                       Error (131, "The left-hand side of an assignment must be a " +
-                              "variable, property or indexer");
                        return null;
                }
 
@@ -641,73 +662,67 @@ namespace Mono.CSharp {
        // after semantic analysis (this is so we can take the address
        // of an indirection).
        //
-       public class Indirection : Expression, IMemoryLocation, IAssignMethod {
+       public class Indirection : Expression, IMemoryLocation, IAssignMethod, IVariable {
                Expression expr;
                LocalTemporary temporary;
-               bool have_temporary;
+               bool prepared;
                
                public Indirection (Expression expr, Location l)
                {
                        this.expr = expr;
-                       this.type = TypeManager.GetElementType (expr.Type);
+                       type = TypeManager.HasElementType (expr.Type) ? TypeManager.GetElementType (expr.Type) : expr.Type;
                        eclass = ExprClass.Variable;
                        loc = l;
                }
-
-               void LoadExprValue (EmitContext ec)
-               {
-               }
                
                public override void Emit (EmitContext ec)
                {
-                       ILGenerator ig = ec.ig;
-
-                       if (temporary != null){
-                               if (have_temporary) {
-                                       temporary.Emit (ec);
-                               } else {
+                       if (!prepared)
                                expr.Emit (ec);
+
+                       LoadFromPtr (ec.ig, Type);
+               }
+
+               public void Emit (EmitContext ec, bool leave_copy)
+               {
+                       Emit (ec);
+                       if (leave_copy) {
                                ec.ig.Emit (OpCodes.Dup);
+                               temporary = new LocalTemporary (ec, expr.Type);
                                temporary.Store (ec);
-                               have_temporary = true;
-                               }
-                       } else
-                               expr.Emit (ec);
-                       
-                       LoadFromPtr (ig, Type);
+                       }
                }
 
-               public void EmitAssign (EmitContext ec, Expression source)
+               public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
                {
-                       if (temporary != null){
-                               if (have_temporary)
-                                       temporary.Emit (ec);
-                               else {
-                                       expr.Emit (ec);
-                                       ec.ig.Emit (OpCodes.Dup);
-                                       temporary.Store (ec);
-                                       have_temporary = true;
-                               }
-                       } else 
-                               expr.Emit (ec);
+                       prepared = prepare_for_load;
+
+                       expr.Emit (ec);
+
+                       if (prepare_for_load)
+                               ec.ig.Emit (OpCodes.Dup);
 
                        source.Emit (ec);
+                       if (leave_copy) {
+                               ec.ig.Emit (OpCodes.Dup);
+                               temporary = new LocalTemporary (ec, expr.Type);
+                               temporary.Store (ec);
+                       }
+
                        StoreFromPtr (ec.ig, type);
+
+                       if (temporary != null)
+                               temporary.Emit (ec);
                }
-               
+
                public void AddressOf (EmitContext ec, AddressOp Mode)
                {
-                       if (temporary != null){
-                               if (have_temporary){
-                                       temporary.Emit (ec);
-                                       return;
-                               }
-                               expr.Emit (ec);
-                               ec.ig.Emit (OpCodes.Dup);
-                               temporary.Store (ec);
-                               have_temporary = true;
-                       } else
-                               expr.Emit (ec);
+                       expr.Emit (ec);
+               }
+
+               public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
+               {
+                       return DoResolve (ec);
                }
 
                public override Expression DoResolve (EmitContext ec)
@@ -717,16 +732,27 @@ namespace Mono.CSharp {
                        //
                        return this;
                }
-
-               public new void CacheTemporaries (EmitContext ec)
+               
+               public override string ToString ()
                {
-                       temporary = new LocalTemporary (ec, expr.Type);
+                       return "*(" + expr + ")";
                }
 
-               public override string ToString ()
+               #region IVariable Members
+
+               public VariableInfo VariableInfo {
+                       get {
+                               return null;
+                       }
+               }
+
+               public bool VerifyFixed ()
                {
-                       return "*(" + expr + ")";
+                       // A pointer-indirection is always fixed.
+                       return true;
                }
+
+               #endregion
        }
        
        /// <summary>
@@ -758,13 +784,15 @@ namespace Mono.CSharp {
                }
                
                Mode mode;
+               bool is_expr = false;
+               bool recurse = false;
+               
                Expression expr;
-               LocalTemporary temp_storage;
 
                //
                // This is expensive for the simplest case.
                //
-               Expression method;
+               StaticCallExpr method;
                        
                public UnaryMutator (Mode m, Expression e, Location l)
                {
@@ -779,14 +807,6 @@ namespace Mono.CSharp {
                                "++" : "--";
                }
                
-               void Error23 (Type t)
-               {
-                       Error (
-                               23, "Operator " + OperName (mode) + 
-                               " cannot be applied to operand of type `" +
-                               TypeManager.CSharpName (t) + "'");
-               }
-
                /// <summary>
                ///   Returns whether an object of type `t' can be incremented
                ///   or decremented with add/sub (ie, basically whether we can
@@ -827,16 +847,15 @@ namespace Mono.CSharp {
 
                        mg = MemberLookup (ec, expr_type, op_name, MemberTypes.Method, AllBindingFlags, loc);
 
-                       if (mg == null && expr_type.BaseType != null)
-                               mg = MemberLookup (ec, expr_type.BaseType, op_name,
-                                                  MemberTypes.Method, AllBindingFlags, loc);
-                       
                        if (mg != null) {
                                method = StaticCallExpr.MakeSimpleCall (
                                        ec, (MethodGroupExpr) mg, expr, loc);
 
                                type = method.Type;
-                               return this;
+                       } else if (!IsIncrementableNumber (expr_type)) {
+                               Error (187, "No such operator '" + OperName (mode) + "' defined for type '" +
+                                      TypeManager.CSharpName (expr_type) + "'");
+                                  return null;
                        }
 
                        //
@@ -847,37 +866,20 @@ namespace Mono.CSharp {
                        type = expr_type;
                        if (expr.eclass == ExprClass.Variable){
                                LocalVariableReference var = expr as LocalVariableReference;
-                               if ((var != null) && var.IsReadOnly)
+                               if ((var != null) && var.IsReadOnly) {
                                        Error (1604, "cannot assign to `" + var.Name + "' because it is readonly");
-                               if (IsIncrementableNumber (expr_type) ||
-                                   expr_type == TypeManager.decimal_type){
-                                       return this;
+                                       return null;
                                }
-                       } else if (expr.eclass == ExprClass.IndexerAccess){
-                               IndexerAccess ia = (IndexerAccess) expr;
-                               
-                               temp_storage = new LocalTemporary (ec, expr.Type);
-                               
-                               expr = ia.ResolveLValue (ec, temp_storage);
+                       } else if (expr.eclass == ExprClass.IndexerAccess || expr.eclass == ExprClass.PropertyAccess){
+                               expr = expr.ResolveLValue (ec, this, Location);
                                if (expr == null)
                                        return null;
-
-                               return this;
-                       } else if (expr.eclass == ExprClass.PropertyAccess){
-                               PropertyExpr pe = (PropertyExpr) expr;
-
-                               if (pe.VerifyAssignable ())
-                                       return this;
-
-                               return null;
                        } else {
-                               expr.Error_UnexpectedKind ("variable, indexer or property access");
+                               expr.Error_UnexpectedKind (ec, "variable, indexer or property access", loc);
                                return null;
                        }
 
-                       Error (187, "No such operator '" + OperName (mode) + "' defined for type '" +
-                              TypeManager.CSharpName (expr_type) + "'");
-                       return null;
+                       return this;
                }
 
                public override Expression DoResolve (EmitContext ec)
@@ -888,6 +890,10 @@ namespace Mono.CSharp {
                                return null;
 
                        eclass = ExprClass.Value;
+
+                       if (TypeManager.IsNullableType (expr.Type))
+                               return new Nullable.LiftedUnaryMutator (mode, expr, loc).Resolve (ec);
+
                        return ResolveOperator (ec);
                }
 
@@ -976,114 +982,38 @@ namespace Mono.CSharp {
                        }
                        
                }
-
-               static EmptyExpression empty_expr;
                
                void EmitCode (EmitContext ec, bool is_expr)
                {
-                       ILGenerator ig = ec.ig;
-                       IAssignMethod ia = (IAssignMethod) expr;
-                       Type expr_type = expr.Type;
-
-                       ia.CacheTemporaries (ec);
+                       recurse = true;
+                       this.is_expr = is_expr;
+                       ((IAssignMethod) expr).EmitAssign (ec, this, is_expr && (mode == Mode.PreIncrement || mode == Mode.PreDecrement), true);
+               }
 
+               public override void Emit (EmitContext ec)
+               {
                        //
-                       // NOTE: We should probably handle three cases:
-                       //
-                       //     * method invocation required.
-                       //     * direct stack manipulation possible
-                       //     * the object requires an "instance" field
+                       // We use recurse to allow ourselfs to be the source
+                       // of an assignment. This little hack prevents us from
+                       // having to allocate another expression
                        //
-                       if (temp_storage == null){
-                               //
-                               // Temporary improvement: if we are dealing with something that does
-                               // not require complicated instance setup, avoid using a temporary
-                               //
-                               // For now: only localvariables when not remapped
-                               //
-
-                               if (method == null &&
-                                   ((expr is LocalVariableReference) ||(expr is FieldExpr && ((FieldExpr) expr).FieldInfo.IsStatic))){
-                                       if (empty_expr == null)
-                                               empty_expr = new EmptyExpression ();
-                                       
-                                       switch (mode){
-                                       case Mode.PreIncrement:
-                                       case Mode.PreDecrement:
-                                               expr.Emit (ec);
-                                       
-                                               LoadOneAndEmitOp (ec, expr_type);
-                                               if (is_expr)
-                                                       ig.Emit (OpCodes.Dup);
-                                               ia.EmitAssign (ec, empty_expr);
-                                               break;
-                                               
-                                       case Mode.PostIncrement:
-                                       case Mode.PostDecrement:
-                                               expr.Emit (ec);
-                                               if (is_expr)
-                                                       ig.Emit (OpCodes.Dup);
-                                               
-                                               LoadOneAndEmitOp (ec, expr_type);
-                                               ia.EmitAssign (ec, empty_expr);
-                                               break;
-                                       }
-                                       return;
-                               }
-                               temp_storage = new LocalTemporary (ec, expr_type);
+                       if (recurse) {
+                               ((IAssignMethod) expr).Emit (ec, is_expr && (mode == Mode.PostIncrement  || mode == Mode.PostDecrement));
+                               if (method == null)
+                                       LoadOneAndEmitOp (ec, expr.Type);
+                               else
+                                       ec.ig.Emit (OpCodes.Call, method.Method);
+                               recurse = false;
+                               return;
                        }
                        
-                       switch (mode){
-                       case Mode.PreIncrement:
-                       case Mode.PreDecrement:
-                               if (method == null){
-                                       expr.Emit (ec);
-                                       
-                                       LoadOneAndEmitOp (ec, expr_type);
-                               } else 
-                                       method.Emit (ec);
-                               
-                               temp_storage.Store (ec);
-                               ia.EmitAssign (ec, temp_storage);
-                               if (is_expr)
-                                       temp_storage.Emit (ec);
-                               break;
-                               
-                       case Mode.PostIncrement:
-                       case Mode.PostDecrement:
-                               if (is_expr)
-                                       expr.Emit (ec);
-                               
-                               if (method == null){
-                                       if (!is_expr)
-                                               expr.Emit (ec);
-                                       else
-                                               ig.Emit (OpCodes.Dup);
-                                       
-                                       LoadOneAndEmitOp (ec, expr_type);
-                               } else {
-                                       method.Emit (ec);
-                               }
-                               
-                               temp_storage.Store (ec);
-                               ia.EmitAssign (ec, temp_storage);
-                               break;
-                       }
-
-                       temp_storage.Release (ec);
-               }
-
-               public override void Emit (EmitContext ec)
-               {
                        EmitCode (ec, true);
-                       
                }
                
                public override void EmitStatement (EmitContext ec)
                {
                        EmitCode (ec, false);
                }
-
        }
 
        /// <summary>
@@ -1095,7 +1025,7 @@ namespace Mono.CSharp {
        ///   size. 
        /// </remarks>
        public abstract class Probe : Expression {
-               public readonly Expression ProbeType;
+               public Expression ProbeType;
                protected Expression expr;
                protected Type probe_type;
                
@@ -1114,10 +1044,10 @@ namespace Mono.CSharp {
 
                public override Expression DoResolve (EmitContext ec)
                {
-                       probe_type = ec.DeclSpace.ResolveType (ProbeType, false, loc);
-
-                       if (probe_type == null)
+                       TypeExpr texpr = ProbeType.ResolveAsTypeTerminal (ec);
+                       if (texpr == null)
                                return null;
+                       probe_type = texpr.Type;
 
                        CheckObsoleteAttribute (probe_type);
 
@@ -1125,6 +1055,10 @@ namespace Mono.CSharp {
                        if (expr == null)
                                return null;
                        
+                       if (expr.Type.IsPointer) {
+                               Report.Error (244, loc, "\"is\" or \"as\" are not valid on pointer types");
+                               return null;
+                       }
                        return this;
                }
        }
@@ -1223,7 +1157,7 @@ namespace Mono.CSharp {
                        // then e != null (objects) or true (value types)
                        //
                        e = Convert.ImplicitConversionStandard (ec, expr, probe_type, loc);
-                       if (e != null){
+                       if (e != null && !(e is NullCast)){
                                expr = e;
                                if (etype.IsValueType)
                                        action = Action.AlwaysTrue;
@@ -1232,6 +1166,9 @@ namespace Mono.CSharp {
 
                                warning_always_matches = true;
                        } else if (Convert.ExplicitReferenceConversionExists (etype, probe_type)){
+                               if (etype.IsGenericParameter)
+                                       expr = new BoxedCast (expr, etype);
+
                                //
                                // Second case: explicit reference convresion
                                //
@@ -1244,20 +1181,15 @@ namespace Mono.CSharp {
                                warning_never_matches = true;
                        }
                        
-                       if (RootContext.WarningLevel >= 1){
-                               if (warning_always_matches)
-                                       Warning (183, "The expression is always of type `" +
-                                                TypeManager.CSharpName (probe_type) + "'");
-                               else if (warning_never_matches){
-                                       if (!(probe_type.IsInterface || expr.Type.IsInterface))
-                                               Warning (184,
-                                                        "The expression is never of type `" +
-                                                        TypeManager.CSharpName (probe_type) + "'");
-                               }
+                       if (warning_always_matches)
+                               Report.Warning (183, 1, loc, "The given expression is always of the provided (`{0}') type", TypeManager.CSharpName (probe_type));
+                       else if (warning_never_matches){
+                               if (!(probe_type.IsInterface || expr.Type.IsInterface))
+                                       Report.Warning (184, 1, loc, "The given expression is never of the provided (`{0}') type", TypeManager.CSharpName (probe_type));
                        }
 
                        return this;
-               }                               
+               }
        }
 
        /// <summary>
@@ -1283,10 +1215,9 @@ namespace Mono.CSharp {
 
                static void Error_CannotConvertType (Type source, Type target, Location loc)
                {
-                       Report.Error (
-                               39, loc, "as operator can not convert from `" +
-                               TypeManager.CSharpName (source) + "' to `" +
-                               TypeManager.CSharpName (target) + "'");
+                       Report.Error (39, loc, "Cannot convert type `{0}' to `{1}' via a built-in conversion",
+                               TypeManager.CSharpName (source),
+                               TypeManager.CSharpName (target));
                }
                
                public override Expression DoResolve (EmitContext ec)
@@ -1300,9 +1231,9 @@ namespace Mono.CSharp {
                        eclass = ExprClass.Value;
                        Type etype = expr.Type;
 
-                       if (TypeManager.IsValueType (probe_type)){
-                               Report.Error (77, loc, "The as operator should be used with a reference type only (" +
-                                             TypeManager.CSharpName (probe_type) + " is a value type)");
+                       if (probe_type.IsValueType) {
+                               Report.Error (77, loc, "The as operator must be used with a reference type (`" +
+                                             TypeManager.CSharpName (probe_type) + "' is a value type)");
                                return null;
                        
                        }
@@ -1315,6 +1246,9 @@ namespace Mono.CSharp {
                        }
 
                        if (Convert.ExplicitReferenceConversionExists (etype, probe_type)){
+                               if (etype.IsGenericParameter)
+                                       expr = new BoxedCast (expr, etype);
+
                                do_isinst = true;
                                return this;
                        }
@@ -1334,6 +1268,11 @@ namespace Mono.CSharp {
                Expression target_type;
                Expression expr;
                        
+               public Cast (Expression cast_type, Expression expr)
+                       : this (cast_type, expr, cast_type.Location)
+               {
+               }
+
                public Cast (Expression cast_type, Expression expr, Location loc)
                {
                        this.target_type = cast_type;
@@ -1401,11 +1340,18 @@ namespace Mono.CSharp {
                        return true;
                }
 
+               // TODO: move to constant
                /// <summary>
                ///   Attempts to do a compile-time folding of a constant cast.
                /// </summary>
                Expression TryReduce (EmitContext ec, Type target_type)
                {
+                       if (expr.Type == target_type)
+                               return expr;
+
+                       if (TypeManager.IsEnumType (target_type) && TypeManager.EnumToUnderlying (target_type) == expr.Type)
+                               return new EnumConstant ((Constant)expr, target_type);
+
                        Expression real_expr = expr;
                        if (real_expr is EnumConstant)
                                real_expr = ((EnumConstant) real_expr).Child;
@@ -1846,19 +1792,39 @@ namespace Mono.CSharp {
                        return null;
                }
                
+               public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
+               {
+                       expr = expr.DoResolveLValue (ec, right_side);
+                       if (expr == null)
+                               return null;
+
+                       return ResolveRest (ec);
+               }
+
                public override Expression DoResolve (EmitContext ec)
                {
                        expr = expr.Resolve (ec);
                        if (expr == null)
                                return null;
 
-                       type = ec.DeclSpace.ResolveType (target_type, false, Location);
-                       
-                       if (type == null)
+                       return ResolveRest (ec);
+               }
+
+               Expression ResolveRest (EmitContext ec)
+               {
+                       TypeExpr target = target_type.ResolveAsTypeTerminal (ec);
+                       if (target == null)
                                return null;
+                       
+                       type = target.Type;
 
                        CheckObsoleteAttribute (type);
 
+                       if (type.IsAbstract && type.IsSealed) {
+                               Report.Error (716, loc, "Cannot convert to static type `{0}'", TypeManager.CSharpName (type));
+                               return null;
+                       }
+
                        eclass = ExprClass.Value;
 
                        if (expr is Constant){
@@ -1875,7 +1841,7 @@ namespace Mono.CSharp {
                        expr = Convert.ExplicitConversion (ec, expr, type, loc);
                        return expr;
                }
-
+               
                public override void Emit (EmitContext ec)
                {
                        //
@@ -1933,12 +1899,12 @@ namespace Mono.CSharp {
                        oper_names [(int) Operator.LogicalAnd] = "op_LogicalAnd";
                }
 
-               public Binary (Operator oper, Expression left, Expression right, Location loc)
+               public Binary (Operator oper, Expression left, Expression right)
                {
                        this.oper = oper;
                        this.left = left;
                        this.right = right;
-                       this.loc = loc;
+                       this.loc = left.Location;
                }
 
                public Operator Oper {
@@ -2065,7 +2031,7 @@ namespace Mono.CSharp {
                // type, otherwise ConvertImplict() already finds the user-defined conversion for us,
                // so we don't explicitly check for performance reasons.
                //
-               bool DoNumericPromotions (EmitContext ec, Type l, Type r, bool check_user_conv)
+               bool DoNumericPromotions (EmitContext ec, Type l, Type r, Expression lexpr, Expression rexpr, bool check_user_conv)
                {
                        if (IsOfType (ec, l, r, TypeManager.double_type, check_user_conv)){
                                //
@@ -2139,6 +2105,10 @@ namespace Mono.CSharp {
                                    (other == TypeManager.int32_type) ||
                                    (other == TypeManager.int64_type))
                                        Error_OperatorAmbiguous (loc, oper, l, r);
+                               else {
+                                       left = ForceConversion (ec, left, TypeManager.uint64_type);
+                                       right = ForceConversion (ec, right, TypeManager.uint64_type);
+                               }
                                type = TypeManager.uint64_type;
                        } else if (IsOfType (ec, l, r, TypeManager.int64_type, check_user_conv)){
                                //
@@ -2213,6 +2183,12 @@ namespace Mono.CSharp {
                                left = ForceConversion (ec, left, TypeManager.int32_type);
                                right = ForceConversion (ec, right, TypeManager.int32_type);
 
+                               bool strConv =
+                                       Convert.ImplicitConversionExists (ec, lexpr, TypeManager.string_type) &&
+                                       Convert.ImplicitConversionExists (ec, rexpr, TypeManager.string_type);
+                               if (strConv && left != null && right != null)
+                                       Error_OperatorAmbiguous (loc, oper, l, r);
+
                                type = TypeManager.int32_type;
                        }
 
@@ -2221,10 +2197,8 @@ namespace Mono.CSharp {
 
                static public void Error_OperatorCannotBeApplied (Location loc, string name, Type l, Type r)
                {
-                       Report.Error (19, loc,
-                              "Operator " + name + " cannot be applied to operands of type `" +
-                              TypeManager.CSharpName (l) + "' and `" +
-                              TypeManager.CSharpName (r) + "'");
+                       Report.Error (19, loc, "Operator `{0}' cannot be applied to operands of type `{1}' and `{2}'",
+                              name, TypeManager.CSharpName (l), TypeManager.CSharpName (r));
                }
                
                void Error_OperatorCannotBeApplied ()
@@ -2288,10 +2262,10 @@ namespace Mono.CSharp {
                                type = e.Type;
 
                                if (type == TypeManager.int32_type || type == TypeManager.uint32_type){
-                                       right = new Binary (Binary.Operator.BitwiseAnd, right, new IntLiteral (31), loc);
+                                       right = new Binary (Binary.Operator.BitwiseAnd, right, new IntLiteral (31));
                                        right = right.DoResolve (ec);
                                } else {
-                                       right = new Binary (Binary.Operator.BitwiseAnd, right, new IntLiteral (63), loc);
+                                       right = new Binary (Binary.Operator.BitwiseAnd, right, new IntLiteral (63));
                                        right = right.DoResolve (ec);
                                }
 
@@ -2301,31 +2275,36 @@ namespace Mono.CSharp {
                        return null;
                }
 
+               //
+               // This is used to check if a test 'x == null' can be optimized to a reference equals,
+               // i.e., not invoke op_Equality.
+               //
+               static bool EqualsNullIsReferenceEquals (Type t)
+               {
+                       return t == TypeManager.object_type || t == TypeManager.string_type ||
+                               t == TypeManager.delegate_type || t.IsSubclassOf (TypeManager.delegate_type);
+               }
+
+               static void Warning_UnintendedReferenceComparison (Location loc, string side, Type type)
+               {
+                       Report.Warning ((side == "left" ? 252 : 253), 2, loc,
+                               "Possible unintended reference comparison; to get a value comparison, " +
+                               "cast the {0} hand side to type `{1}'.", side, TypeManager.CSharpName (type));
+               }
+
                Expression ResolveOperator (EmitContext ec)
                {
                        Type l = left.Type;
                        Type r = right.Type;
 
-                       bool overload_failed = false;
-
-                       //
-                       // Special cases: string or type parameter comapred to null
-                       //
                        if (oper == Operator.Equality || oper == Operator.Inequality){
-                               if ((l == TypeManager.string_type && (right is NullLiteral)) ||
-                                   (r == TypeManager.string_type && (left is NullLiteral))){
-                                       Type = TypeManager.bool_type;
-                                       
-                                       return this;
-                               }
-
                                if (l.IsGenericParameter && (right is NullLiteral)) {
                                        if (l.BaseType == TypeManager.value_type) {
                                                Error_OperatorCannotBeApplied ();
                                                return null;
                                        }
 
-                                       left = new BoxedCast (left);
+                                       left = new BoxedCast (left, TypeManager.object_type);
                                        Type = TypeManager.bool_type;
                                        return this;
                                }
@@ -2336,11 +2315,21 @@ namespace Mono.CSharp {
                                                return null;
                                        }
 
-                                       right = new BoxedCast (right);
+                                       right = new BoxedCast (right, TypeManager.object_type);
                                        Type = TypeManager.bool_type;
                                        return this;
                                }
-                               
+
+                               //
+                               // Optimize out call to op_Equality in a few cases.
+                               //
+                               if ((l == TypeManager.null_type && EqualsNullIsReferenceEquals (r)) ||
+                                   (r == TypeManager.null_type && EqualsNullIsReferenceEquals (l))) {
+                                       Type = TypeManager.bool_type;
+                                       
+                                       return this;
+                               }
+
                                // IntPtr equality
                                if (l == TypeManager.intptr_type && r == TypeManager.intptr_type) {
                                        Type = TypeManager.bool_type;
@@ -2353,22 +2342,21 @@ namespace Mono.CSharp {
                        // Do not perform operator overload resolution when both sides are
                        // built-in types
                        //
-                       if (!(TypeManager.IsCLRType (l) && TypeManager.IsCLRType (r))){
+                       Expression left_operators = null, right_operators = null;
+                       if (!(TypeManager.IsPrimitiveType (l) && TypeManager.IsPrimitiveType (r))){
                                //
                                // Step 1: Perform Operator Overload location
                                //
-                               Expression left_expr, right_expr;
-                               
                                string op = oper_names [(int) oper];
                                
                                MethodGroupExpr union;
-                               left_expr = MemberLookup (ec, l, op, MemberTypes.Method, AllBindingFlags, loc);
+                               left_operators = MemberLookup (ec, l, op, MemberTypes.Method, AllBindingFlags, loc);
                                if (r != l){
-                                       right_expr = MemberLookup (
+                                       right_operators = MemberLookup (
                                                ec, r, op, MemberTypes.Method, AllBindingFlags, loc);
-                                       union = Invocation.MakeUnionSet (left_expr, right_expr, loc);
+                                       union = Invocation.MakeUnionSet (left_operators, right_operators, loc);
                                } else
-                                       union = (MethodGroupExpr) left_expr;
+                                       union = (MethodGroupExpr) left_operators;
                                
                                if (union != null) {
                                        ArrayList args = new ArrayList (2);
@@ -2382,8 +2370,6 @@ namespace Mono.CSharp {
                                                MethodInfo mi = (MethodInfo) method;
                                                
                                                return new BinaryMethod (mi.ReturnType, method, args);
-                                       } else {
-                                               overload_failed = true;
                                        }
                                }
                        }
@@ -2452,33 +2438,88 @@ namespace Mono.CSharp {
                                        return this;
                                }
 
-                               //
-                               // operator != (object a, object b)
-                               // operator == (object a, object b)
-                               //
+                               if (l.IsPointer || r.IsPointer) {
+                                       if (l.IsPointer && r.IsPointer) {
+                                               type = TypeManager.bool_type;
+                                               return this;
+                                       }
+
+                                       if (l.IsPointer && r == TypeManager.null_type) {
+                                               right = new EmptyCast (NullPointer.Null, l);
+                                               type = TypeManager.bool_type;
+                                               return this;
+                                       }
+
+                                       if (r.IsPointer && l == TypeManager.null_type) {
+                                               left = new EmptyCast (NullPointer.Null, r);
+                                               type = TypeManager.bool_type;
+                                               return this;
+                                       }
+                               }
+
+                               if (l.IsGenericParameter && r.IsGenericParameter) {
+                                       GenericConstraints l_gc, r_gc;
+
+                                       l_gc = TypeManager.GetTypeParameterConstraints (l);
+                                       r_gc = TypeManager.GetTypeParameterConstraints (r);
+
+                                       if ((l_gc == null) || (r_gc == null) ||
+                                           !(l_gc.HasReferenceTypeConstraint || l_gc.HasClassConstraint) ||
+                                           !(r_gc.HasReferenceTypeConstraint || r_gc.HasClassConstraint)) {
+                                               Error_OperatorCannotBeApplied ();
+                                               return null;
+                                       }
+
+                               }
+
+                               //
+                               // operator != (object a, object b)
+                               // operator == (object a, object b)
+                               //
                                // For this to be used, both arguments have to be reference-types.
                                // Read the rationale on the spec (14.9.6)
                                //
-                               // Also, if at compile time we know that the classes do not inherit
-                               // one from the other, then we catch the error there.
-                               //
                                if (!(l.IsValueType || r.IsValueType)){
                                        type = TypeManager.bool_type;
 
                                        if (l == r)
                                                return this;
                                        
-                                       if (l.IsSubclassOf (r) || r.IsSubclassOf (l))
-                                               return this;
-
                                        //
                                        // Also, a standard conversion must exist from either one
                                        //
-                                       if (!(Convert.ImplicitStandardConversionExists (left, r) ||
-                                             Convert.ImplicitStandardConversionExists (right, l))){
+                                       bool left_to_right =
+                                               Convert.ImplicitStandardConversionExists (ec, left, r);
+                                       bool right_to_left = !left_to_right &&
+                                               Convert.ImplicitStandardConversionExists (ec, right, l);
+
+                                       if (!left_to_right && !right_to_left) {
                                                Error_OperatorCannotBeApplied ();
                                                return null;
                                        }
+
+                                       if (left_to_right && left_operators != null &&
+                                           RootContext.WarningLevel >= 2) {
+                                               ArrayList args = new ArrayList (2);
+                                               args.Add (new Argument (left, Argument.AType.Expression));
+                                               args.Add (new Argument (left, Argument.AType.Expression));
+                                               MethodBase method = Invocation.OverloadResolve (
+                                                       ec, (MethodGroupExpr) left_operators, args, true, Location.Null);
+                                               if (method != null)
+                                                       Warning_UnintendedReferenceComparison (loc, "right", l);
+                                       }
+
+                                       if (right_to_left && right_operators != null &&
+                                           RootContext.WarningLevel >= 2) {
+                                               ArrayList args = new ArrayList (2);
+                                               args.Add (new Argument (right, Argument.AType.Expression));
+                                               args.Add (new Argument (right, Argument.AType.Expression));
+                                               MethodBase method = Invocation.OverloadResolve (
+                                                       ec, (MethodGroupExpr) right_operators, args, true, Location.Null);
+                                               if (method != null)
+                                                       Warning_UnintendedReferenceComparison (loc, "left", r);
+                                       }
+
                                        //
                                        // We are going to have to convert to an object to compare
                                        //
@@ -2507,34 +2548,37 @@ namespace Mono.CSharp {
                        //
                        if (oper == Operator.Addition || oper == Operator.Subtraction) {
                                if (TypeManager.IsDelegateType (l)){
-                                       if (right.eclass == ExprClass.MethodGroup && RootContext.V2){
-                                               Expression tmp = Convert.ImplicitConversionRequired (ec, right, l, loc);
-                                               if (tmp == null)
-                                                       return null;
-                                               right = tmp;
-                                               r = right.Type;
+                                       if (((right.eclass == ExprClass.MethodGroup) ||
+                                            (r == TypeManager.anonymous_method_type))){
+                                               if ((RootContext.Version != LanguageVersion.ISO_1)){
+                                                       Expression tmp = Convert.ImplicitConversionRequired (ec, right, l, loc);
+                                                       if (tmp == null)
+                                                               return null;
+                                                       right = tmp;
+                                                       r = right.Type;
+                                               }
                                        }
                                
                                        if (TypeManager.IsDelegateType (r)){
-                                       MethodInfo method;
-                                       ArrayList args = new ArrayList (2);
+                                               MethodInfo method;
+                                               ArrayList args = new ArrayList (2);
                                        
-                                       args = new ArrayList (2);
-                                       args.Add (new Argument (left, Argument.AType.Expression));
-                                       args.Add (new Argument (right, Argument.AType.Expression));
+                                               args = new ArrayList (2);
+                                               args.Add (new Argument (left, Argument.AType.Expression));
+                                               args.Add (new Argument (right, Argument.AType.Expression));
                                        
-                                       if (oper == Operator.Addition)
-                                               method = TypeManager.delegate_combine_delegate_delegate;
-                                       else
-                                               method = TypeManager.delegate_remove_delegate_delegate;
+                                               if (oper == Operator.Addition)
+                                                       method = TypeManager.delegate_combine_delegate_delegate;
+                                               else
+                                                       method = TypeManager.delegate_remove_delegate_delegate;
 
-                                       if (l != r) {
-                                               Error_OperatorCannotBeApplied ();
-                                               return null;
-                                       }
+                                               if (!TypeManager.IsEqual (l, r)) {
+                                                       Error_OperatorCannotBeApplied ();
+                                                       return null;
+                                               }
 
-                                       return new BinaryDelegate (l, method, args);
-                               }
+                                               return new BinaryDelegate (l, method, args);
+                                       }
                                }
 
                                //
@@ -2562,16 +2606,16 @@ namespace Mono.CSharp {
                                                if (r == l)
                                                        return new PointerArithmetic (
                                                                false, left, right, TypeManager.int64_type,
-                                                               loc);
+                                                               loc).Resolve (ec);
                                        } else {
                                                Expression t = Make32or64 (ec, right);
                                                if (t != null)
-                                                       return new PointerArithmetic (oper == Operator.Addition, left, t, l, loc);
+                                                       return new PointerArithmetic (oper == Operator.Addition, left, t, l, loc).Resolve (ec);
                                        }
                                } else if (r.IsPointer && oper == Operator.Addition){
                                        Expression t = Make32or64 (ec, left);
                                        if (t != null)
-                                               return new PointerArithmetic (true, right, t, r, loc);
+                                               return new PointerArithmetic (true, right, t, r, loc).Resolve (ec);
                                }
                        }
                        
@@ -2656,6 +2700,10 @@ namespace Mono.CSharp {
                                if (oper == Operator.BitwiseAnd ||
                                    oper == Operator.BitwiseOr ||
                                    oper == Operator.ExclusiveOr){
+                                       if (left.Type != right.Type){
+                                               Error_OperatorCannotBeApplied ();
+                                               return null;
+                                       }
                                        type = l;
                                        return this;
                                }
@@ -2700,27 +2748,18 @@ namespace Mono.CSharp {
                        // Pointer comparison
                        //
                        if (l.IsPointer && r.IsPointer){
-                               if (oper == Operator.Equality || oper == Operator.Inequality ||
-                                   oper == Operator.LessThan || oper == Operator.LessThanOrEqual ||
+                               if (oper == Operator.LessThan || oper == Operator.LessThanOrEqual ||
                                    oper == Operator.GreaterThan || oper == Operator.GreaterThanOrEqual){
                                        type = TypeManager.bool_type;
                                        return this;
                                }
                        }
                        
-                       //
-                       // We are dealing with numbers
-                       //
-                       if (overload_failed){
-                               Error_OperatorCannotBeApplied ();
-                               return null;
-                       }
-
                        //
                        // This will leave left or right set to null if there is an error
                        //
                        bool check_user_conv = is_user_defined (l) && is_user_defined (r);
-                       DoNumericPromotions (ec, l, r, check_user_conv);
+                       DoNumericPromotions (ec, l, r, left, right, check_user_conv);
                        if (left == null || right == null){
                                Error_OperatorCannotBeApplied (loc, OperName (oper), l, r);
                                return null;
@@ -2774,31 +2813,161 @@ namespace Mono.CSharp {
                                        return null;
 
                                if (left.eclass == ExprClass.Type) {
-                                       Error (75, "Casting a negative value needs to have the value in parentheses.");
+                                       Error (75, "To cast a negative value, you must enclose the value in parentheses");
                                        return null;
                                }
                        } else
                                left = left.Resolve (ec);
-                       right = right.Resolve (ec);
 
-                       if (left == null || right == null)
+                       if (left == null)
+                               return null;
+
+                       Constant lc = left as Constant;
+                       if (lc != null && lc.Type == TypeManager.bool_type && 
+                               ((oper == Operator.LogicalAnd && (bool)lc.GetValue () == false) ||
+                                (oper == Operator.LogicalOr && (bool)lc.GetValue () == true))) {
+
+                               // TODO: make a sense to resolve unreachable expression as we do for statement
+                               Report.Warning (429, 4, loc, "Unreachable expression code detected");
+                               return left;
+                       }
+
+                       right = right.Resolve (ec);
+                       if (right == null)
                                return null;
 
                        eclass = ExprClass.Value;
 
                        Constant rc = right as Constant;
-                       Constant lc = left as Constant;
 
-                       if (rc != null & lc != null){
+                       if (oper == Operator.BitwiseAnd) {
+                               if (rc != null && rc.IsZeroInteger) {
+                                       return lc is EnumConstant ?
+                                               new EnumConstant (rc, lc.Type):
+                                               rc;
+                               }
+
+                               if (lc != null && lc.IsZeroInteger) {
+                                       return rc is EnumConstant ?
+                                               new EnumConstant (lc, rc.Type):
+                                               lc;
+                               }
+                       }
+
+                       if (rc != null && lc != null){
+                               int prev_e = Report.Errors;
                                Expression e = ConstantFold.BinaryFold (
                                        ec, oper, lc, rc, loc);
-                                       if (e != null)
-                                               return e;
+                               if (e != null || Report.Errors != prev_e)
+                                       return e;
+                       }
+
+                       if (TypeManager.IsNullableType (left.Type) || TypeManager.IsNullableType (right.Type))
+                               return new Nullable.LiftedBinaryOperator (oper, left, right, loc).Resolve (ec);
+
+                       // Check CS0652 warning here (before resolving operator).
+                       if (oper == Operator.Equality ||
+                           oper == Operator.Inequality ||
+                           oper == Operator.LessThanOrEqual ||
+                           oper == Operator.LessThan ||
+                           oper == Operator.GreaterThanOrEqual ||
+                           oper == Operator.GreaterThan){
+                               CheckUselessComparison (left as Constant, right.Type);
+                               CheckUselessComparison (right as Constant, left.Type);
                        }
 
                        return ResolveOperator (ec);
                }
 
+               private void CheckUselessComparison (Constant c, Type type)
+               {
+                       if (c == null || !IsTypeIntegral (type)
+                               || c is StringConstant
+                               || c is BoolConstant
+                               || c is CharConstant
+                               || c is FloatConstant
+                               || c is DoubleConstant
+                               || c is DecimalConstant
+                               )
+                               return;
+
+                       long value = 0;
+
+                       if (c is ULongConstant) {
+                               ulong uvalue = ((ULongConstant) c).Value;
+                               if (uvalue > long.MaxValue) {
+                                       if (type == TypeManager.byte_type ||
+                                           type == TypeManager.sbyte_type ||
+                                           type == TypeManager.short_type ||
+                                           type == TypeManager.ushort_type ||
+                                           type == TypeManager.int32_type ||
+                                           type == TypeManager.uint32_type ||
+                                           type == TypeManager.int64_type)
+                                               WarnUselessComparison (type);
+                                       return;
+                               }
+                               value = (long) uvalue;
+                       }
+                       else if (c is ByteConstant)
+                               value = ((ByteConstant) c).Value;
+                       else if (c is SByteConstant)
+                               value = ((SByteConstant) c).Value;
+                       else if (c is ShortConstant)
+                               value = ((ShortConstant) c).Value;
+                       else if (c is UShortConstant)
+                               value = ((UShortConstant) c).Value;
+                       else if (c is IntConstant)
+                               value = ((IntConstant) c).Value;
+                       else if (c is UIntConstant)
+                               value = ((UIntConstant) c).Value;
+                       else if (c is LongConstant)
+                               value = ((LongConstant) c).Value;
+
+                       if (value != 0) {
+                               if (IsValueOutOfRange (value, type))
+                                       WarnUselessComparison (type);
+                               return;
+                       }
+               }
+
+               private bool IsValueOutOfRange (long value, Type type)
+               {
+                       if (IsTypeUnsigned (type) && value < 0)
+                               return true;
+                       return type == TypeManager.sbyte_type && (value >= 0x80 || value < -0x80) ||
+                               type == TypeManager.byte_type && value >= 0x100 ||
+                               type == TypeManager.short_type && (value >= 0x8000 || value < -0x8000) ||
+                               type == TypeManager.ushort_type && value >= 0x10000 ||
+                               type == TypeManager.int32_type && (value >= 0x80000000 || value < -0x80000000) ||
+                               type == TypeManager.uint32_type && value >= 0x100000000;
+               }
+
+               private static bool IsTypeIntegral (Type type)
+               {
+                       return type == TypeManager.uint64_type ||
+                               type == TypeManager.int64_type ||
+                               type == TypeManager.uint32_type ||
+                               type == TypeManager.int32_type ||
+                               type == TypeManager.ushort_type ||
+                               type == TypeManager.short_type ||
+                               type == TypeManager.sbyte_type ||
+                               type == TypeManager.byte_type;
+               }
+
+               private static bool IsTypeUnsigned (Type type)
+               {
+                       return type == TypeManager.uint64_type ||
+                               type == TypeManager.uint32_type ||
+                               type == TypeManager.ushort_type ||
+                               type == TypeManager.byte_type;
+               }
+
+               private void WarnUselessComparison (Type type)
+               {
+                       Report.Warning (652, 2, loc, "Comparison to integral constant is useless; the constant is outside the range of type `{0}'",
+                               TypeManager.CSharpName (type));
+               }
+
                /// <remarks>
                ///   EmitBranchable is called from Statement.EmitBoolExpression in the
                ///   context of a conditional bool expression.  This function will return
@@ -3163,7 +3332,7 @@ namespace Mono.CSharp {
                        ILGenerator ig = ec.ig;
                        
                        if (Arguments != null) 
-                               Invocation.EmitArguments (ec, method, Arguments);
+                               Invocation.EmitArguments (ec, method, Arguments, false, null);
                        
                        if (method is MethodInfo)
                                ig.Emit (OpCodes.Call, (MethodInfo) method);
@@ -3179,7 +3348,11 @@ namespace Mono.CSharp {
        public class StringConcat : Expression {
                ArrayList operands;
                bool invalid = false;
-               
+               bool emit_conv_done = false;
+               //
+               // Are we also concating objects?
+               //
+               bool is_strings_only = true;
                
                public StringConcat (EmitContext ec, Location loc, Expression left, Expression right)
                {
@@ -3233,14 +3406,13 @@ namespace Mono.CSharp {
                {
                        MethodInfo concat_method = null;
                        
-                       //
-                       // Are we also concating objects?
-                       //
-                       bool is_strings_only = true;
-                       
                        //
                        // Do conversion to arguments; check for strings only
                        //
+                       
+                       // This can get called multiple times, so we have to deal with that.
+                       if (!emit_conv_done) {
+                               emit_conv_done = true;
                        for (int i = 0; i < operands.Count; i ++) {
                                Expression e = (Expression) operands [i];
                                is_strings_only &= e.Type == TypeManager.string_type;
@@ -3254,10 +3426,11 @@ namespace Mono.CSharp {
                                        // method might look at the type of this expression, see it is a
                                        // string and emit a string [] when we want an object [];
                                        
-                                       e = Convert.ImplicitConversion (ec, e, TypeManager.object_type, loc);
+                                               e = new EmptyCast (e, TypeManager.object_type);
                                }
                                operands [i] = new Argument (e, Argument.AType.Expression);
                        }
+                       }
                        
                        //
                        // Find the right method
@@ -3298,7 +3471,7 @@ namespace Mono.CSharp {
                                break;
                        }
                        
-                       Invocation.EmitArguments (ec, concat_method, operands);
+                       Invocation.EmitArguments (ec, concat_method, operands, false, null);
                        ec.ig.Emit (OpCodes.Call, concat_method);
                }
        }
@@ -3327,7 +3500,7 @@ namespace Mono.CSharp {
                {
                        ILGenerator ig = ec.ig;
                        
-                       Invocation.EmitArguments (ec, method, args);
+                       Invocation.EmitArguments (ec, method, args, false, null);
                        
                        ig.Emit (OpCodes.Call, (MethodInfo) method);
                        ig.Emit (OpCodes.Castclass, type);
@@ -3396,11 +3569,17 @@ namespace Mono.CSharp {
                        method = Invocation.OverloadResolve (
                                ec, (MethodGroupExpr) operator_group, arguments, false, loc)
                                as MethodInfo;
-                       if ((method == null) || (method.ReturnType != type)) {
+                       if (method == null) {
                                Error19 ();
                                return null;
                        }
 
+                       if (method.ReturnType != type) {
+                               Report.Error (217, loc, "In order to be applicable as a short circuit operator a user-defined logical operator `{0}' " +
+                                               "must have the same return type as the type of its 2 parameters", TypeManager.CSharpSignature (method));
+                               return null;
+                       }
+
                        op = new StaticCallExpr (method, arguments, loc);
 
                        op_true = GetOperatorTrue (ec, left_temp, loc);
@@ -3419,8 +3598,6 @@ namespace Mono.CSharp {
                        Label false_target = ig.DefineLabel ();
                        Label end_target = ig.DefineLabel ();
 
-                       ig.Emit (OpCodes.Nop);
-
                        left.Emit (ec);
                        left_temp.Store (ec);
 
@@ -3430,8 +3607,6 @@ namespace Mono.CSharp {
                        ig.MarkLabel (false_target);
                        op.Emit (ec);
                        ig.MarkLabel (end_target);
-
-                       ig.Emit (OpCodes.Nop);
                }
        }
 
@@ -3445,7 +3620,6 @@ namespace Mono.CSharp {
                public PointerArithmetic (bool is_addition, Expression l, Expression r, Type t, Location loc)
                {
                        type = t;
-                       eclass = ExprClass.Variable;
                        this.loc = loc;
                        left = l;
                        right = r;
@@ -3454,9 +3628,13 @@ namespace Mono.CSharp {
 
                public override Expression DoResolve (EmitContext ec)
                {
-                       //
-                       // We are born fully resolved
-                       //
+                       eclass = ExprClass.Variable;
+                       
+                       if (left.Type == TypeManager.void_ptr_type) {
+                               Error (242, "The operation in question is undefined on void pointers");
+                               return null;
+                       }
+                       
                        return this;
                }
 
@@ -3464,7 +3642,13 @@ namespace Mono.CSharp {
                {
                        Type op_type = left.Type;
                        ILGenerator ig = ec.ig;
-                       int size = GetTypeSize (TypeManager.GetElementType (op_type));
+                       
+                       // It must be either array or fixed buffer
+                       Type element = TypeManager.HasElementType (op_type) ?
+                               element = TypeManager.GetElementType (op_type) :
+                               element = AttributeTester.GetFixedBuffer (((FieldExpr)left).FieldInfo).ElementType;
+
+                       int size = GetTypeSize (element);
                        Type rtype = right.Type;
                        
                        if (rtype.IsPointer){
@@ -3477,7 +3661,7 @@ namespace Mono.CSharp {
 
                                if (size != 1){
                                        if (size == 0)
-                                               ig.Emit (OpCodes.Sizeof, op_type);
+                                               ig.Emit (OpCodes.Sizeof, element);
                                        else 
                                                IntLiteral.EmitInt (ig, size);
                                        ig.Emit (OpCodes.Div);
@@ -3489,19 +3673,31 @@ namespace Mono.CSharp {
                                //
                                left.Emit (ec);
                                ig.Emit (OpCodes.Conv_I);
-                               right.Emit (ec);
-                               if (size != 1){
-                                       if (size == 0)
-                                               ig.Emit (OpCodes.Sizeof, op_type);
-                                       else 
-                                               IntLiteral.EmitInt (ig, size);
-                                       if (rtype == TypeManager.int64_type)
-                                               ig.Emit (OpCodes.Conv_I8);
-                                       else if (rtype == TypeManager.uint64_type)
-                                               ig.Emit (OpCodes.Conv_U8);
-                                       ig.Emit (OpCodes.Mul);
-                                       ig.Emit (OpCodes.Conv_I);
+
+                               Constant right_const = right as Constant;
+                               if (right_const != null && size != 0) {
+                                       Expression ex = ConstantFold.BinaryFold (ec, Binary.Operator.Multiply, new IntConstant (size), right_const, loc);
+                                       if (ex == null)
+                                               return;
+                                       ex.Emit (ec);
+                               } else {
+                                       right.Emit (ec);
+                                       if (size != 1){
+                                               if (size == 0)
+                                                       ig.Emit (OpCodes.Sizeof, element);
+                                               else 
+                                                       IntLiteral.EmitInt (ig, size);
+                                               if (rtype == TypeManager.int64_type)
+                                                       ig.Emit (OpCodes.Conv_I8);
+                                               else if (rtype == TypeManager.uint64_type)
+                                                       ig.Emit (OpCodes.Conv_U8);
+                                               ig.Emit (OpCodes.Mul);
+                                       }
                                }
+                               
+                               if (rtype == TypeManager.int64_type || rtype == TypeManager.uint64_type)
+                                       ig.Emit (OpCodes.Conv_I);
+                               
                                if (is_add)
                                        ig.Emit (OpCodes.Add);
                                else
@@ -3516,12 +3712,12 @@ namespace Mono.CSharp {
        public class Conditional : Expression {
                Expression expr, trueExpr, falseExpr;
                
-               public Conditional (Expression expr, Expression trueExpr, Expression falseExpr, Location l)
+               public Conditional (Expression expr, Expression trueExpr, Expression falseExpr)
                {
                        this.expr = expr;
                        this.trueExpr = trueExpr;
                        this.falseExpr = falseExpr;
-                       this.loc = l;
+                       this.loc = expr.Location;
                }
 
                public Expression Expr {
@@ -3548,6 +3744,9 @@ namespace Mono.CSharp {
 
                        if (expr == null)
                                return null;
+
+                       if (TypeManager.IsNullableType (expr.Type))
+                               return new Nullable.LiftedConditional (expr, trueExpr, falseExpr, loc).Resolve (ec);
                        
                        if (expr.Type != TypeManager.bool_type){
                                expr = Expression.ResolveBoolean (
@@ -3557,6 +3756,11 @@ namespace Mono.CSharp {
                                        return null;
                        }
                        
+                       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 = ?");
+                       }
+
                        trueExpr = trueExpr.Resolve (ec);
                        falseExpr = falseExpr.Resolve (ec);
 
@@ -3571,14 +3775,6 @@ namespace Mono.CSharp {
                                Type true_type = trueExpr.Type;
                                Type false_type = falseExpr.Type;
 
-                               if (trueExpr is NullLiteral){
-                                       type = false_type;
-                                       return this;
-                               } else if (falseExpr is NullLiteral){
-                                       type = true_type;
-                                       return this;
-                               }
-                               
                                //
                                // First, if an implicit conversion exists from trueExpr
                                // to falseExpr, then the result type is of type falseExpr.Type
@@ -3602,21 +3798,18 @@ namespace Mono.CSharp {
                                        type = true_type;
                                        falseExpr = conv;
                                } else {
-                                       Error (173, "The type of the conditional expression can " +
-                                              "not be computed because there is no implicit conversion" +
-                                              " from `" + TypeManager.CSharpName (trueExpr.Type) + "'" +
-                                              " and `" + TypeManager.CSharpName (falseExpr.Type) + "'");
+                                       Report.Error (173, loc, "Type of conditional expression cannot be determined because there is no implicit conversion between `{0}' and `{1}'",
+                                               trueExpr.GetSignatureForError (), falseExpr.GetSignatureForError ());
                                        return null;
                                }
                        }
 
+                       // Dead code optimalization
                        if (expr is BoolConstant){
                                BoolConstant bc = (BoolConstant) expr;
 
-                               if (bc.Value)
-                                       return trueExpr;
-                               else
-                                       return falseExpr;
+                               Report.Warning (429, 4, bc.Value ? falseExpr.Location : trueExpr.Location, "Unreachable expression code detected");
+                               return bc.Value ? trueExpr : falseExpr;
                        }
 
                        return this;
@@ -3644,8 +3837,10 @@ namespace Mono.CSharp {
        public class LocalVariableReference : Expression, IAssignMethod, IMemoryLocation, IVariable {
                public readonly string Name;
                public readonly Block Block;
-               LocalInfo local_info;
+               public LocalInfo local_info;
                bool is_readonly;
+               bool prepared;
+               LocalTemporary temp;
                
                public LocalVariableReference (Block block, string name, Location l)
                {
@@ -3655,8 +3850,10 @@ namespace Mono.CSharp {
                        eclass = ExprClass.Variable;
                }
 
+               //
                // Setting `is_readonly' to false will allow you to create a writable
                // reference to a read-only variable.  This is used by foreach and using.
+               //
                public LocalVariableReference (Block block, string name, Location l,
                                               LocalInfo local_info, bool is_readonly)
                        : this (block, name, l)
@@ -3666,7 +3863,9 @@ namespace Mono.CSharp {
                }
 
                public VariableInfo VariableInfo {
-                       get { return local_info.VariableInfo; }
+                       get {
+                               return local_info.VariableInfo;
+                       }
                }
 
                public bool IsReadOnly {
@@ -3675,100 +3874,192 @@ namespace Mono.CSharp {
                        }
                }
 
-               protected void DoResolveBase (EmitContext ec)
+               public bool VerifyAssigned (EmitContext ec)
+               {
+                       VariableInfo variable_info = local_info.VariableInfo;
+                       return variable_info == null || variable_info.IsAssigned (ec, loc);
+               }
+
+               protected Expression DoResolveBase (EmitContext ec, Expression lvalue_right_side)
                {
                        if (local_info == null) {
                                local_info = Block.GetLocalInfo (Name);
+
+                               // is out param
+                               if (lvalue_right_side == EmptyExpression.Null)
+                                       local_info.Used = true;
+
                                is_readonly = local_info.ReadOnly;
                        }
 
                        type = local_info.VariableType;
-#if false
-                       if (ec.InAnonymousMethod)
-                               Block.LiftVariable (local_info);
-#endif
-               }
+
+                       VariableInfo variable_info = local_info.VariableInfo;
+                       if (lvalue_right_side != null){
+                               if (is_readonly){
+                                       if (lvalue_right_side is LocalVariableReference || lvalue_right_side == EmptyExpression.Null)
+                                               Report.Error (1657, loc, "Cannot pass `{0}' as a ref or out argument because it is a `{1}'",
+                                                       Name, local_info.GetReadOnlyContext ());
+                                       else
+                                               Report.Error (1656, loc, "Cannot assign to `{0}' because it is a `{1}'",
+                                                       Name, local_info.GetReadOnlyContext ());
+                                       return null;
+                               }
+
+                               if (variable_info != null)
+                                       variable_info.SetAssigned (ec);
+                       }
                
-               protected Expression DoResolve (EmitContext ec, bool is_lvalue)
-               {
                        Expression e = Block.GetConstantExpression (Name);
                        if (e != null) {
                                local_info.Used = true;
                                eclass = ExprClass.Value;
-                               return e;
+                               return e.Resolve (ec);
                        }
 
-                       VariableInfo variable_info = local_info.VariableInfo; 
-                       if ((variable_info != null) && !variable_info.IsAssigned (ec, loc))
+                       if (!VerifyAssigned (ec))
                                return null;
 
-                       if (!is_lvalue)
+                       if (lvalue_right_side == null)
                                local_info.Used = true;
 
-                       if (local_info.LocalBuilder == null)
-                               return ec.RemapLocal (local_info);
+                       if (ec.CurrentAnonymousMethod != null){
+                               //
+                               // If we are referencing a variable from the external block
+                               // flag it for capturing
+                               //
+                               if ((local_info.Block.Toplevel != ec.CurrentBlock.Toplevel) ||
+                                   ec.CurrentAnonymousMethod.IsIterator)
+                               {
+                                       if (local_info.AddressTaken){
+                                               AnonymousMethod.Error_AddressOfCapturedVar (local_info.Name, loc);
+                                               return null;
+                                       }
+                                       ec.CaptureVariable (local_info);
+                               }
+                       }
                        
                        return this;
                }
 
                public override Expression DoResolve (EmitContext ec)
                {
-                       DoResolveBase (ec);
-
-                       return DoResolve (ec, false);
+                       return DoResolveBase (ec, null);
                }
 
                override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
                {
-                       DoResolveBase (ec);
-
-                       VariableInfo variable_info = local_info.VariableInfo; 
-                       if (variable_info != null)
-                               variable_info.SetAssigned (ec);
-
-                       Expression e = DoResolve (ec, true);
+                       Expression ret = DoResolveBase (ec, right_side);
+                       if (ret != null)
+                               CheckObsoleteAttribute (ret.Type);
 
-                       if (e == null)
-                               return null;
-
-                       if (is_readonly){
-                               Error (1604, "cannot assign to `" + Name + "' because it is readonly");
-                               return null;
-                       }
+                       return ret;
+               }
 
-                       CheckObsoleteAttribute (e.Type);
+               public bool VerifyFixed ()
+               {
+                       // A local Variable is always fixed.
+                       return true;
+               }
 
-                       if (local_info.LocalBuilder == null)
-                               return ec.RemapLocalLValue (local_info, right_side);
-                       
-                       return this;
+               public override int GetHashCode()
+               {
+                       return Name.GetHashCode ();
                }
 
-               public bool VerifyFixed (bool is_expression)
+               public override bool Equals (object obj)
                {
-                       return !is_expression || local_info.IsFixed;
+                       LocalVariableReference lvr = obj as LocalVariableReference;
+                       if (lvr == null)
+                               return false;
+
+                       return Name == lvr.Name && Block == lvr.Block;
                }
 
                public override void Emit (EmitContext ec)
                {
                        ILGenerator ig = ec.ig;
 
-                       ig.Emit (OpCodes.Ldloc, local_info.LocalBuilder);
+                       if (local_info.FieldBuilder == null){
+                               //
+                               // A local variable on the local CLR stack
+                               //
+                               ig.Emit (OpCodes.Ldloc, local_info.LocalBuilder);
+                       } else {
+                               //
+                               // A local variable captured by anonymous methods.
+                               //
+                               if (!prepared)
+                                       ec.EmitCapturedVariableInstance (local_info);
+                               
+                               ig.Emit (OpCodes.Ldfld, local_info.FieldBuilder);
+                       }
+               }
+               
+               public void Emit (EmitContext ec, bool leave_copy)
+               {
+                       Emit (ec);
+                       if (leave_copy){
+                               ec.ig.Emit (OpCodes.Dup);
+                               if (local_info.FieldBuilder != null){
+                                       temp = new LocalTemporary (ec, Type);
+                                       temp.Store (ec);
+                               }
+                       }
                }
                
-               public void EmitAssign (EmitContext ec, Expression source)
+               public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
                {
                        ILGenerator ig = ec.ig;
+                       prepared = prepare_for_load;
 
-                       source.Emit (ec);
-                       ig.Emit (OpCodes.Stloc, local_info.LocalBuilder);
+                       if (local_info.FieldBuilder == null){
+                               //
+                               // A local variable on the local CLR stack
+                               //
+                               if (local_info.LocalBuilder == null)
+                                       throw new Exception ("This should not happen: both Field and Local are null");
+
+                               source.Emit (ec);
+                               if (leave_copy)
+                                       ec.ig.Emit (OpCodes.Dup);
+                               ig.Emit (OpCodes.Stloc, local_info.LocalBuilder);
+                       } else {
+                               //
+                               // A local variable captured by anonymous methods or itereators.
+                               //
+                               ec.EmitCapturedVariableInstance (local_info);
+
+                               if (prepare_for_load)
+                                       ig.Emit (OpCodes.Dup);
+                               source.Emit (ec);
+                               if (leave_copy){
+                                       ig.Emit (OpCodes.Dup);
+                                       temp = new LocalTemporary (ec, Type);
+                                       temp.Store (ec);
+                               }
+                               ig.Emit (OpCodes.Stfld, local_info.FieldBuilder);
+                               if (temp != null)
+                                       temp.Emit (ec);
+                       }
                }
                
                public void AddressOf (EmitContext ec, AddressOp mode)
                {
                        ILGenerator ig = ec.ig;
                        
+                       if (local_info.FieldBuilder == null){
+                               //
+                               // A local variable on the local CLR stack
+                               //
                        ig.Emit (OpCodes.Ldloca, local_info.LocalBuilder);
+                       } else {
+                               //
+                               // A local variable captured by anonymous methods or iterators
+                               //
+                               ec.EmitCapturedVariableInstance (local_info);
+                               ig.Emit (OpCodes.Ldflda, local_info.FieldBuilder);
+                       }
                }
 
                public override string ToString ()
@@ -3788,7 +4079,21 @@ namespace Mono.CSharp {
                Block block;
                VariableInfo vi;
                public Parameter.Modifier mod;
-               public bool is_ref, is_out;
+               public bool is_ref, is_out, prepared;
+
+               public bool IsOut {
+                       get {
+                               return is_out;
+                       }
+               }
+
+               public bool IsRef {
+                       get {
+                               return is_ref;
+                       }
+               }
+
+               LocalTemporary temp;
                
                public ParameterReference (Parameters pars, Block block, int idx, string name, Location loc)
                {
@@ -3800,30 +4105,33 @@ namespace Mono.CSharp {
                        eclass = ExprClass.Variable;
                }
 
+               public ParameterReference (InternalParameters pars, Block block, int idx, Location loc)
+                       : this (pars.Parameters, block, idx, pars.ParameterName (idx), loc)
+               { }
+
                public VariableInfo VariableInfo {
                        get { return vi; }
                }
 
-               public bool VerifyFixed (bool is_expression)
+               public bool VerifyFixed ()
                {
-                       return !is_expression || TypeManager.IsValueType (type);
+                       // A parameter is fixed if it's a value parameter (i.e., no modifier like out, ref, param).
+                       return mod == Parameter.Modifier.NONE;
                }
 
                public bool IsAssigned (EmitContext ec, Location loc)
                {
-                       if (!ec.DoFlowAnalysis || !is_out ||
-                           ec.CurrentBranching.IsAssigned (vi))
+                       if (!ec.DoFlowAnalysis || !is_out || ec.CurrentBranching.IsAssigned (vi))
                                return true;
 
-                       Report.Error (165, loc,
-                                     "Use of unassigned parameter `" + name + "'");
+                       Report.Error (269, loc,
+                                     "Use of unassigned out parameter `{0}'", name);
                        return false;
                }
 
                public bool IsFieldAssigned (EmitContext ec, string field_name, Location loc)
                {
-                       if (!ec.DoFlowAnalysis || !is_out ||
-                           ec.CurrentBranching.IsFieldAssigned (vi, field_name))
+                       if (!ec.DoFlowAnalysis || !is_out || ec.CurrentBranching.IsFieldAssigned (vi, field_name))
                                return true;
 
                        Report.Error (170, loc,
@@ -3845,18 +4153,49 @@ namespace Mono.CSharp {
 
                protected void DoResolveBase (EmitContext ec)
                {
-                       type = pars.GetParameterInfo (ec.DeclSpace, idx, out mod);
+                       type = pars.GetParameterInfo (ec, idx, out mod);
                        is_ref = (mod & Parameter.Modifier.ISBYREF) != 0;
                        is_out = (mod & Parameter.Modifier.OUT) != 0;
                        eclass = ExprClass.Variable;
 
                        if (is_out)
                                vi = block.ParameterMap [idx];
-               }
 
-               //
-               // Notice that for ref/out parameters, the type exposed is not the
-               // same type exposed externally.
+                       if (ec.CurrentAnonymousMethod != null){
+                               if (is_ref){
+                                       Report.Error (1628, Location, "Cannot use ref or out parameter `{0}' inside an anonymous method block",
+                                               name);
+                                       return;
+                               }
+
+                               //
+                               // If we are referencing the parameter from the external block
+                               // flag it for capturing
+                               //
+                               //Console.WriteLine ("Is parameter `{0}' local? {1}", name, block.IsLocalParameter (name));
+                               if (!block.Toplevel.IsLocalParameter (name)){
+                                       ec.CaptureParameter (name, type, idx);
+                               }
+                       }
+               }
+
+               public override int GetHashCode()
+               {
+                       return name.GetHashCode ();
+               }
+
+               public override bool Equals (object obj)
+               {
+                       ParameterReference pr = obj as ParameterReference;
+                       if (pr == null)
+                               return false;
+
+                       return name == pr.name && block == pr.block;
+               }
+
+               //
+               // Notice that for ref/out parameters, the type exposed is not the
+               // same type exposed externally.
                //
                // for "ref int a":
                //   externally we expose "int&"
@@ -3870,12 +4209,9 @@ namespace Mono.CSharp {
                {
                        DoResolveBase (ec);
 
-                       if (is_out && ec.DoFlowAnalysis && !IsAssigned (ec, loc))
+                       if (is_out && ec.DoFlowAnalysis && (!ec.OmitStructFlowAnalysis || !vi.TypeInfo.IsStruct) && !IsAssigned (ec, loc))
                                return null;
 
-                       if (ec.RemapToProxy)
-                               return ec.RemapParameter (idx);
-                       
                        return this;
                }
 
@@ -3885,9 +4221,6 @@ namespace Mono.CSharp {
 
                        SetAssigned (ec);
 
-                       if (ec.RemapToProxy)
-                               return ec.RemapParameterLValue (idx, right_side);
-                       
                        return this;
                }
 
@@ -3916,50 +4249,94 @@ namespace Mono.CSharp {
                        ILGenerator ig = ec.ig;
                        int arg_idx = idx;
 
-                       if (!ec.IsStatic)
+                       if (!ec.MethodIsStatic)
                                arg_idx++;
-
+                       
                        EmitLdArg (ig, arg_idx);
+
+                       //
+                       // FIXME: Review for anonymous methods
+                       //
                }
                
                public override void Emit (EmitContext ec)
+               {
+                       Emit (ec, false);
+               }
+               
+               public void Emit (EmitContext ec, bool leave_copy)
                {
                        ILGenerator ig = ec.ig;
-                       
                        int arg_idx = idx;
 
-                       if (!ec.IsStatic)
+                       if (ec.HaveCaptureInfo && ec.IsParameterCaptured (name)){
+                               if (leave_copy)
+                                       throw new InternalErrorException ();
+
+                               ec.EmitParameter (name);
+                               return;
+                       }
+
+                       if (!ec.MethodIsStatic)
                                arg_idx++;
 
                        EmitLdArg (ig, arg_idx);
 
-                       if (!is_ref)
-                               return;
-
-                       //
-                       // If we are a reference, we loaded on the stack a pointer
-                       // Now lets load the real value
-                       //
-                       LoadFromPtr (ig, type);
+                       if (is_ref) {
+                               if (prepared)
+                                       ec.ig.Emit (OpCodes.Dup);
+       
+                               //
+                               // If we are a reference, we loaded on the stack a pointer
+                               // Now lets load the real value
+                               //
+                               LoadFromPtr (ig, type);
+                       }
+                       
+                       if (leave_copy) {
+                               ec.ig.Emit (OpCodes.Dup);
+                               
+                               if (is_ref) {
+                                       temp = new LocalTemporary (ec, type);
+                                       temp.Store (ec);
+                               }
+                       }
                }
-
-               public void EmitAssign (EmitContext ec, Expression source)
+               
+               public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
                {
+                       if (ec.HaveCaptureInfo && ec.IsParameterCaptured (name)){
+                               ec.EmitAssignParameter (name, source, leave_copy, prepare_for_load);
+                               return;
+                       }
+
                        ILGenerator ig = ec.ig;
-                       
                        int arg_idx = idx;
-
-                       if (!ec.IsStatic)
+                       
+                       prepared = prepare_for_load;
+                       
+                       if (!ec.MethodIsStatic)
                                arg_idx++;
 
-                       if (is_ref)
+                       if (is_ref && !prepared)
                                EmitLdArg (ig, arg_idx);
                        
                        source.Emit (ec);
 
-                       if (is_ref)
+                       if (leave_copy)
+                               ec.ig.Emit (OpCodes.Dup);
+                       
+                       if (is_ref) {
+                               if (leave_copy) {
+                                       temp = new LocalTemporary (ec, type);
+                                       temp.Store (ec);
+                               }
+                               
                                StoreFromPtr (ig, type);
-                       else {
+                               
+                               if (temp != null)
+                                       temp.Emit (ec);
+                       } else {
                                if (arg_idx <= 255)
                                        ig.Emit (OpCodes.Starg_S, (byte) arg_idx);
                                else
@@ -3969,9 +4346,14 @@ namespace Mono.CSharp {
 
                public void AddressOf (EmitContext ec, AddressOp mode)
                {
+                       if (ec.HaveCaptureInfo && ec.IsParameterCaptured (name)){
+                               ec.EmitAddressOfParameter (name);
+                               return;
+                       }
+                       
                        int arg_idx = idx;
 
-                       if (!ec.IsStatic)
+                       if (!ec.MethodIsStatic)
                                arg_idx++;
 
                        if (is_ref){
@@ -4009,6 +4391,12 @@ namespace Mono.CSharp {
                        this.ArgType = type;
                }
 
+               public Argument (Expression expr)
+               {
+                       this.Expr = expr;
+                       this.ArgType = AType.Expression;
+               }
+
                public Type Type {
                        get {
                                if (ArgType == AType.Ref || ArgType == AType.Out)
@@ -4018,17 +4406,19 @@ namespace Mono.CSharp {
                        }
                }
 
-               public Parameter.Modifier GetParameterModifier ()
+               public Parameter.Modifier Modifier
                {
-                       switch (ArgType) {
-                       case AType.Out:
-                               return Parameter.Modifier.OUT | Parameter.Modifier.ISBYREF;
+                       get {
+                               switch (ArgType) {
+                                       case AType.Out:
+                                               return Parameter.Modifier.OUT | Parameter.Modifier.ISBYREF;
 
-                       case AType.Ref:
-                               return Parameter.Modifier.REF | Parameter.Modifier.ISBYREF;
+                                       case AType.Ref:
+                                               return Parameter.Modifier.REF | Parameter.Modifier.ISBYREF;
 
-                       default:
-                               return Parameter.Modifier.NONE;
+                                       default:
+                                               return Parameter.Modifier.NONE;
+                               }
                        }
                }
 
@@ -4044,9 +4434,9 @@ namespace Mono.CSharp {
 
                public bool ResolveMethodGroup (EmitContext ec, Location loc)
                {
-                       ConstructedType ctype = Expr as ConstructedType;
-                       if (ctype != null)
-                               Expr = ctype.GetSimpleName (ec);
+                       SimpleName sn = Expr as SimpleName;
+                       if (sn != null)
+                               Expr = sn.GetMethodGroup ();
 
                        // FIXME: csc doesn't report any error if you try to use `ref' or
                        //        `out' in a delegate creation expression.
@@ -4057,19 +4447,41 @@ namespace Mono.CSharp {
                        return true;
                }
                
+               void Error_LValueRequired (Location loc)
+               {
+                       Report.Error (1510, loc, "A ref or out argument must be an assignable variable");
+               }
+
                public bool Resolve (EmitContext ec, Location loc)
                {
+                       bool old_do_flow_analysis = ec.DoFlowAnalysis;
+                       ec.DoFlowAnalysis = true;
+
                        if (ArgType == AType.Ref) {
+                               ec.InRefOutArgumentResolving = true;
                                Expr = Expr.Resolve (ec);
-                               if (Expr == null)
+                               ec.InRefOutArgumentResolving = false;
+                               if (Expr == null) {
+                                       ec.DoFlowAnalysis = old_do_flow_analysis;
                                        return false;
+                               }
 
-                               Expr = Expr.ResolveLValue (ec, Expr);
-                       } else if (ArgType == AType.Out)
-                               Expr = Expr.ResolveLValue (ec, new EmptyExpression ());
+                               Expr = Expr.DoResolveLValue (ec, Expr);
+                               if (Expr == null)
+                                       Error_LValueRequired (loc);
+                       } else if (ArgType == AType.Out) {
+                               ec.InRefOutArgumentResolving = true;
+                               Expr = Expr.DoResolveLValue (ec, EmptyExpression.Null);
+                               ec.InRefOutArgumentResolving = false;
+
+                               if (Expr == null)
+                                       Error_LValueRequired (loc);
+                       }
                        else
                                Expr = Expr.Resolve (ec);
 
+                       ec.DoFlowAnalysis = old_do_flow_analysis;
+
                        if (Expr == null)
                                return false;
 
@@ -4086,8 +4498,10 @@ namespace Mono.CSharp {
 
                                        if (instance.GetType () != typeof (This)){
                                                if (fe.InstanceExpression.Type.IsSubclassOf (TypeManager.mbr_type)){
-                                                       Report.Error (197, loc,
-                                                                     "Can not pass a type that derives from MarshalByRefObject with out or ref");
+                                                       Report.SymbolRelatedToPreviousError (fe.InstanceExpression.Type);
+                                                       Report.Warning (197, 1, loc,
+                                                               "Passing `{0}' as ref or out or taking its address may cause a runtime exception because it is a field of a marshal-by-reference class",
+                                                               fe.GetSignatureForError ());
                                                        return false;
                                                }
                                        }
@@ -4100,14 +4514,10 @@ namespace Mono.CSharp {
                                //
                                if (Expr.eclass == ExprClass.PropertyAccess ||
                                    Expr.eclass == ExprClass.IndexerAccess){
-                                       Report.Error (
-                                               206, loc,
-                                               "A property or indexer can not be passed as an out or ref " +
-                                               "parameter");
+                                       Report.Error (206, loc, "A property or indexer `{0}' may not be passed as an out or ref parameter",
+                                               Expr.GetSignatureForError ());
                                } else {
-                                       Report.Error (
-                                               1510, loc,
-                                               "An lvalue is required as an argument to out or ref");
+                                       Error_LValueRequired (loc);
                                }
                                return false;
                        }
@@ -4132,14 +4542,19 @@ namespace Mono.CSharp {
                                if (Expr is ParameterReference){
                                        ParameterReference pr = (ParameterReference) Expr;
 
-                                       if (pr.is_ref)
+                                       if (pr.IsRef)
                                                pr.EmitLoad (ec);
                                        else {
                                                
                                                pr.AddressOf (ec, mode);
                                        }
                                } else {
-                                       ((IMemoryLocation)Expr).AddressOf (ec, mode);
+                                       if (Expr is IMemoryLocation)
+                                               ((IMemoryLocation) Expr).AddressOf (ec, mode);
+                                       else {
+                                               Error_LValueRequired (Expr.Location);
+                                               return;
+                                       }
                                }
                        } else
                                Expr.Emit (ec);
@@ -4154,15 +4569,7 @@ namespace Mono.CSharp {
 
                Expression expr;
                MethodBase method = null;
-               bool is_base;
                
-               static Hashtable method_parameter_cache;
-
-               static Invocation ()
-               {
-                       method_parameter_cache = new PtrHashtable ();
-               }
-                       
                //
                // arguments is an ArrayList, but we do not want to typecast,
                // as it might be null.
@@ -4170,11 +4577,11 @@ namespace Mono.CSharp {
                // FIXME: only allow expr to be a method invocation or a
                // delegate invocation (7.5.5)
                //
-               public Invocation (Expression expr, ArrayList arguments, Location l)
+               public Invocation (Expression expr, ArrayList arguments)
                {
                        this.expr = expr;
                        Arguments = arguments;
-                       loc = l;
+                       loc = expr.Location;
                }
 
                public Expression Expr {
@@ -4184,199 +4591,105 @@ namespace Mono.CSharp {
                }
 
                /// <summary>
-               ///   Returns the Parameters (a ParameterData interface) for the
-               ///   Method `mb'
-               /// </summary>
-               public static ParameterData GetParameterData (MethodBase mb)
-               {
-                       object pd = method_parameter_cache [mb];
-                       object ip;
-                       
-                       if (pd != null)
-                               return (ParameterData) pd;
-
-                       ip = TypeManager.LookupParametersByBuilder (mb);
-                       if (ip != null){
-                               method_parameter_cache [mb] = ip;
-
-                               return (ParameterData) ip;
-                       } else {
-                               ReflectionParameters rp = new ReflectionParameters (mb);
-                               method_parameter_cache [mb] = rp;
-
-                               return (ParameterData) rp;
-                       }
-               }
-
-               /// <summary>
-               ///   Determines "better conversion" as specified in 7.4.2.3
+               ///   Determines "better conversion" as specified in 14.4.2.3
                ///
-                ///    Returns : 1 if a->p is better
-               ///              0 if a->q or neither is better 
+               ///    Returns : p    if a->p is better,
+               ///              q    if a->q is better,
+               ///              null if neither is better
                /// </summary>
-               static int BetterConversion (EmitContext ec, Argument a, Type p, Type q, Location loc)
+               static Type BetterConversion (EmitContext ec, Argument a, Type p, Type q, Location loc)
                {
-                       Type argument_type = a.Type;
+                       Type argument_type = TypeManager.TypeToCoreType (a.Type);
                        Expression argument_expr = a.Expr;
 
+                       // p = TypeManager.TypeToCoreType (p);
+                       // q = TypeManager.TypeToCoreType (q);
+
                        if (argument_type == null)
                                throw new Exception ("Expression of type " + a.Expr +
                                                      " does not resolve its type");
 
+                       if (p == null || q == null)
+                               throw new InternalErrorException ("BetterConversion Got a null conversion");
+
+                       if (p == q)
+                               return null;
+
+                       if (argument_expr is NullLiteral) {
                        //
-                       // This is a special case since csc behaves this way.
+                               // If the argument is null and one of the types to compare is 'object' and
+                               // the other is a reference type, we prefer the other.
                        //
-                       if (argument_expr is NullLiteral &&
-                            p == TypeManager.string_type &&
-                            q == TypeManager.object_type)
-                               return 1;
-                       else if (argument_expr is NullLiteral &&
-                                 p == TypeManager.object_type &&
-                                 q == TypeManager.string_type)
-                               return 0;
-                       
-                        //
-                        // csc behaves this way so we emulate it. Basically, if the argument
-                        // is null and one of the types to compare is 'object' and the other
-                        // is a reference type, we prefer the other.
-                        //
-                        // I can't find this anywhere in the spec but we can interpret this
-                        // to mean that null can be of any type you wish in such a context
-                        //
-                        if (p != null && q != null) {
-                                if (argument_expr is NullLiteral &&
-                                    !p.IsValueType &&
-                                    q == TypeManager.object_type)
-                                        return 1;
-                                else if (argument_expr is NullLiteral &&
-                                         !q.IsValueType &&
-                                         p == TypeManager.object_type)
-                                        return 0;
-                        }
-                                
-                       if (p == q)
-                               return 0;
+                               // This follows from the usual rules:
+                               //   * There is an implicit conversion from 'null' to type 'object'
+                               //   * There is an implicit conversion from 'null' to any reference type
+                               //   * There is an implicit conversion from any reference type to type 'object'
+                               //   * There is no implicit conversion from type 'object' to other reference types
+                               //  => Conversion of 'null' to a reference type is better than conversion to 'object'
+                               //
+                               //  FIXME: This probably isn't necessary, since the type of a NullLiteral is the 
+                               //         null type. I think it used to be 'object' and thus needed a special 
+                               //         case to avoid the immediately following two checks.
+                               //
+                               if (!p.IsValueType && q == TypeManager.object_type)
+                                       return p;
+                               if (!q.IsValueType && p == TypeManager.object_type)
+                                       return q;
+                       }
                        
                        if (argument_type == p)
-                               return 1;
+                               return p;
 
                        if (argument_type == q)
-                               return 0;
-
-                       //
-                       // Now probe whether an implicit constant expression conversion
-                       // can be used.
-                       //
-                       // An implicit constant expression conversion permits the following
-                       // conversions:
-                       //
-                       //    * A constant-expression of type `int' can be converted to type
-                       //      sbyte, byute, short, ushort, uint, ulong provided the value of
-                       //      of the expression is withing the range of the destination type.
-                       //
-                       //    * A constant-expression of type long can be converted to type
-                       //      ulong, provided the value of the constant expression is not negative
-                       //
-                       // FIXME: Note that this assumes that constant folding has
-                       // taken place.  We dont do constant folding yet.
-                       //
-
-                       if (argument_expr is IntConstant){
-                               IntConstant ei = (IntConstant) argument_expr;
-                               int value = ei.Value;
-
-                               if (p == TypeManager.sbyte_type){
-                                       if (value >= SByte.MinValue && value <= SByte.MaxValue)
-                                               return 1;
-                               } else if (p == TypeManager.byte_type){
-                                       if (q == TypeManager.sbyte_type &&
-                                           value >= SByte.MinValue && value <= SByte.MaxValue)
-                                               return 0;
-                                       else if (Byte.MinValue >= 0 && value <= Byte.MaxValue)
-                                               return 1;
-                               } else if (p == TypeManager.short_type){
-                                       if (value >= Int16.MinValue && value <= Int16.MaxValue)
-                                               return 1;
-                               } else if (p == TypeManager.ushort_type){
-                                       if (q == TypeManager.short_type &&
-                                           value >= Int16.MinValue && value <= Int16.MaxValue)
-                                               return 0;
-                                       else if (value >= UInt16.MinValue && value <= UInt16.MaxValue)
-                                               return 1;
-                               } else if (p == TypeManager.int32_type){
-                                       if (value >= Int32.MinValue && value <= Int32.MaxValue)
-                                               return 1;
-                               } else if (p == TypeManager.uint32_type){
-                                       //
-                                       // we can optimize this case: a positive int32
-                                       // always fits on a uint32
-                                       //
-                                       if (value >= 0)
-                                               return 1;
-                               } else if (p == TypeManager.uint64_type){
-                                       //
-                                       // we can optimize this case: a positive int32
-                                       // always fits on a uint64
-                                       //
-
-                                        //
-                                        // This special case is needed because csc behaves like this.
-                                        // int -> uint is better than int -> ulong!
-                                        //
-                                        if (q == TypeManager.uint32_type)
-                                                return 0;
-                                        
-                                       if (q == TypeManager.int64_type)
-                                               return 0;
-                                       else if (value >= 0)
-                                               return 1;
-                               } else if (p == TypeManager.int64_type){
-                                       return 1;
-                               }
-                       } else if (argument_type == TypeManager.int64_type && argument_expr is LongConstant){
-                               LongConstant lc = (LongConstant) argument_expr;
-                               
-                               if (p == TypeManager.uint64_type){
-                                       if (lc.Value > 0)
-                                               return 1;
-                               }
-                       }
-
-                       if (q == null) {
-                               Expression tmp = Convert.ImplicitConversion (ec, argument_expr, p, loc);
-                               
-                               if (tmp != null)
-                                       return 1;
-                               else
-                                       return 0;
-                       }
+                               return q;
 
                        Expression p_tmp = new EmptyExpression (p);
                        Expression q_tmp = new EmptyExpression (q);
                        
-                       if (Convert.ImplicitConversionExists (ec, p_tmp, q) == true &&
-                           Convert.ImplicitConversionExists (ec, q_tmp, p) == false)
-                               return 1;
+                       bool p_to_q = Convert.ImplicitConversionExists (ec, p_tmp, q);
+                       bool q_to_p = Convert.ImplicitConversionExists (ec, q_tmp, p);
+
+                       if (p_to_q && !q_to_p)
+                               return p;
+
+                       if (q_to_p && !p_to_q)
+                               return q;
 
                        if (p == TypeManager.sbyte_type)
                                if (q == TypeManager.byte_type || q == TypeManager.ushort_type ||
                                    q == TypeManager.uint32_type || q == TypeManager.uint64_type)
-                                       return 1;
+                                       return p;
+                       if (q == TypeManager.sbyte_type)
+                               if (p == TypeManager.byte_type || p == TypeManager.ushort_type ||
+                                   p == TypeManager.uint32_type || p == TypeManager.uint64_type)
+                                       return q;
 
                        if (p == TypeManager.short_type)
                                if (q == TypeManager.ushort_type || q == TypeManager.uint32_type ||
                                    q == TypeManager.uint64_type)
-                                       return 1;
+                                       return p;
+
+                       if (q == TypeManager.short_type)
+                               if (p == TypeManager.ushort_type || p == TypeManager.uint32_type ||
+                                   p == TypeManager.uint64_type)
+                                       return q;
 
                        if (p == TypeManager.int32_type)
                                if (q == TypeManager.uint32_type || q == TypeManager.uint64_type)
-                                       return 1;
+                                       return p;
+
+                       if (q == TypeManager.int32_type)
+                               if (p == TypeManager.uint32_type || p == TypeManager.uint64_type)
+                                       return q;
 
                        if (p == TypeManager.int64_type)
                                if (q == TypeManager.uint64_type)
-                                       return 1;
+                                       return p;
+                       if (q == TypeManager.int64_type)
+                               if (p == TypeManager.uint64_type)
+                                       return q;
 
-                       return 0;
+                       return null;
                }
                
                /// <summary>
@@ -4384,94 +4697,24 @@ namespace Mono.CSharp {
                 ///   and the current best match
                /// </summary>
                /// <remarks>
-               ///    Returns an integer indicating :
-               ///     0 if candidate ain't better
-               ///     1 if candidate is better than the current best match
+               ///    Returns a boolean indicating :
+               ///     false if candidate ain't better
+               ///     true  if candidate is better than the current best match
                /// </remarks>
-               static int BetterFunction (EmitContext ec, ArrayList args,
+               static bool BetterFunction (EmitContext ec, ArrayList args, int argument_count,
                                           MethodBase candidate, bool candidate_params,
-                                           MethodBase best, bool best_params,
-                                          Location loc)
+                                          MethodBase best, bool best_params, Location loc)
                {
-                       ParameterData candidate_pd = GetParameterData (candidate);
-                       ParameterData best_pd;
-                       int argument_count;
+                       ParameterData candidate_pd = TypeManager.GetParameterData (candidate);
+                       ParameterData best_pd = TypeManager.GetParameterData (best);
                
-                       if (args == null)
-                               argument_count = 0;
-                       else
-                               argument_count = args.Count;
-
-                       int cand_count = candidate_pd.Count;
-
-                       //
-                       // If there is no best method, than this one
-                       // is better, however, if we already found a
-                       // best method, we cant tell. This happens
-                       // if we have:
-                       // 
-                       //      interface IFoo {
-                       //              void DoIt ();
-                       //      }
-                       //      
-                       //      interface IBar {
-                       //              void DoIt ();
-                       //      }
-                       //      
-                       //      interface IFooBar : IFoo, IBar {}
-                       //
-                       // We cant tell if IFoo.DoIt is better than IBar.DoIt
-                       //
-                       // However, we have to consider that
-                       // Trim (); is better than Trim (params char[] chars);
-                        //
-                       if (cand_count == 0 && argument_count == 0)
-                               return best == null || best_params ? 1 : 0;
-
-                       if ((candidate_pd.ParameterModifier (cand_count - 1) != Parameter.Modifier.PARAMS) &&
-                           (candidate_pd.ParameterModifier (cand_count - 1) != Parameter.Modifier.ARGLIST))
-                               if (cand_count != argument_count)
-                                       return 0;
-
-                       if (best == null) {
-                               int x = 0;
-
-                               if (argument_count == 0 && cand_count == 1 &&
-                                   candidate_pd.ParameterModifier (cand_count - 1) == Parameter.Modifier.PARAMS)
-                                       return 1;
-                               
-                               for (int j = 0; j < argument_count; ++j) {
-
-                                       Argument a = (Argument) args [j];
-                                       Type t = candidate_pd.ParameterType (j);
-
-                                       if (candidate_pd.ParameterModifier (j) == Parameter.Modifier.PARAMS)
-                                               if (candidate_params)
-                                                       t = TypeManager.GetElementType (t);
-
-                                       x = BetterConversion (ec, a, t, null, loc);
-                                       
-                                       if (x <= 0)
-                                               break;
-                               }
-
-                               if (x > 0)
-                                       return 1;
-                               else
-                                       return 0;
-                       }
-
-                       best_pd = GetParameterData (best);
-
-                       int rating1 = 0, rating2 = 0;
-                       
+                       bool better_at_least_one = false;
+                       bool same = true;
                        for (int j = 0; j < argument_count; ++j) {
-                               int x, y;
-                               
                                Argument a = (Argument) args [j];
 
-                               Type ct = candidate_pd.ParameterType (j);
-                               Type bt = best_pd.ParameterType (j);
+                               Type ct = TypeManager.TypeToCoreType (candidate_pd.ParameterType (j));
+                               Type bt = TypeManager.TypeToCoreType (best_pd.ParameterType (j));
 
                                if (candidate_pd.ParameterModifier (j) == Parameter.Modifier.PARAMS)
                                        if (candidate_params)
@@ -4481,62 +4724,95 @@ namespace Mono.CSharp {
                                        if (best_params)
                                                bt = TypeManager.GetElementType (bt);
 
-                               x = BetterConversion (ec, a, ct, bt, loc);
-                               y = BetterConversion (ec, a, bt, ct, loc);
+                               if (ct.Equals (bt))
+                                       continue;
 
-                               if (x < y)
-                                       return 0;
+                               same = false;
+                               Type better = BetterConversion (ec, a, ct, bt, loc);
+                               // for each argument, the conversion to 'ct' should be no worse than 
+                               // the conversion to 'bt'.
+                               if (better == bt)
+                                       return false;
                                
-                               rating1 += x;
-                               rating2 += y;
+                               // for at least one argument, the conversion to 'ct' should be better than 
+                               // the conversion to 'bt'.
+                               if (better == ct)
+                                       better_at_least_one = true;
                        }
 
-                        //
-                        // If a method (in the normal form) with the
-                        // same signature as the expanded form of the
-                        // current best params method already exists,
-                        // the expanded form is not applicable so we
-                        // force it to select the candidate
-                        //
-                        if (!candidate_params && best_params && cand_count == argument_count)
-                                return 1;
+                       if (better_at_least_one)
+                               return true;
 
-                       if (rating1 > rating2)
-                               return 1;
-                       else
-                               return 0;
+                       if (!same)
+                               return false;
+
+                       //
+                       // If two methods have equal parameter types, but
+                       // only one of them is generic, the non-generic one wins.
+                       //
+                       if (TypeManager.IsGenericMethod (best) && !TypeManager.IsGenericMethod (candidate))
+                               return true;
+                       else if (!TypeManager.IsGenericMethod (best) && TypeManager.IsGenericMethod (candidate))
+                               return false;
+
+                       //
+                       // Note that this is not just an optimization.  This handles the case
+                       // This handles the case
+                       //
+                       //   Add (float f1, float f2, float f3);
+                       //   Add (params decimal [] foo);
+                       //
+                       // The call Add (3, 4, 5) should be ambiguous.  Without this check, the
+                       // first candidate would've chosen as better.
+                       //
+                       //
+                       // This handles the following cases:
+                       //
+                       //   Trim () is better than Trim (params char[] chars)
+                       //   Concat (string s1, string s2, string s3) is better than
+                       //     Concat (string s1, params string [] srest)
+                       //
+                        return !candidate_params && best_params;
                }
 
-               public static string FullMethodDesc (MethodBase mb)
+               static bool IsOverride (MethodBase cand_method, MethodBase base_method)
                {
-                       string ret_type = "";
+                       if (!IsAncestralType (base_method.DeclaringType, cand_method.DeclaringType))
+                               return false;
 
-                        if (mb == null)
-                                return "";
+                       ParameterData cand_pd = TypeManager.GetParameterData (cand_method);
+                       ParameterData base_pd = TypeManager.GetParameterData (base_method);
+               
+                       if (cand_pd.Count != base_pd.Count)
+                               return false;
 
-                       if (mb is MethodInfo)
-                               ret_type = TypeManager.CSharpName (((MethodInfo) mb).ReturnType);
-                       
-                       StringBuilder sb = new StringBuilder (ret_type);
-                       sb.Append (" ");
-                       sb.Append (mb.ReflectedType.ToString ());
-                       sb.Append (".");
-                       sb.Append (mb.Name);
-                       
-                       ParameterData pd = GetParameterData (mb);
+                       for (int j = 0; j < cand_pd.Count; ++j) {
+                               Parameter.Modifier cm = cand_pd.ParameterModifier (j);
+                               Parameter.Modifier bm = base_pd.ParameterModifier (j);
+                               Type ct = TypeManager.TypeToCoreType (cand_pd.ParameterType (j));
+                               Type bt = TypeManager.TypeToCoreType (base_pd.ParameterType (j));
 
-                       int count = pd.Count;
-                       sb.Append (" (");
-                       
-                       for (int i = count; i > 0; ) {
-                               i--;
+                               if (cm != bm || ct != bt)
+                                       return false;
+                       }
+
+                       return true;
+               }
+
+               public static string FullMethodDesc (MethodBase mb)
+               {
+                       if (mb == null)
+                               return "";
 
-                               sb.Append (pd.ParameterDesc (count - i - 1));
-                               if (i != 0)
-                                       sb.Append (", ");
+                       StringBuilder sb;
+                       if (mb is MethodInfo) {
+                               sb = new StringBuilder (TypeManager.CSharpName (((MethodInfo) mb).ReturnType));
+                               sb.Append (" ");
                        }
-                       
-                       sb.Append (")");
+                       else
+                               sb = new StringBuilder ();
+
+                       sb.Append (TypeManager.CSharpSignature (mb));
                        return sb.ToString ();
                }
 
@@ -4585,15 +4861,28 @@ namespace Mono.CSharp {
                        return union;
                }
 
+               public static bool IsParamsMethodApplicable (EmitContext ec, MethodGroupExpr me,
+                                                            ArrayList arguments, int arg_count,
+                                                            ref MethodBase candidate)
+               {
+                       return IsParamsMethodApplicable (
+                               ec, me, arguments, arg_count, false, ref candidate) ||
+                               IsParamsMethodApplicable (
+                                       ec, me, arguments, arg_count, true, ref candidate);
+
+
+               }
+
                static bool IsParamsMethodApplicable (EmitContext ec, MethodGroupExpr me,
-                                                     ArrayList arguments, bool do_varargs,
-                                                     ref MethodBase candidate)
+                                                     ArrayList arguments, int arg_count,
+                                                     bool do_varargs, ref MethodBase candidate)
                {
                        if (!me.HasTypeArguments &&
-                           !InferParamsTypeArguments (ec, arguments, ref candidate))
+                           !TypeManager.InferParamsTypeArguments (ec, arguments, ref candidate))
                                return false;
 
-                       return IsParamsMethodApplicable (ec, arguments, candidate, do_varargs);
+                       return IsParamsMethodApplicable (
+                               ec, arguments, arg_count, candidate, do_varargs);
                }
 
                /// <summary>
@@ -4601,16 +4890,10 @@ namespace Mono.CSharp {
                ///   in its expanded form to the given set of arguments
                /// </summary>
                static bool IsParamsMethodApplicable (EmitContext ec, ArrayList arguments,
-                                                     MethodBase candidate, bool do_varargs)
+                                                     int arg_count, MethodBase candidate,
+                                                     bool do_varargs)
                {
-                       int arg_count;
-                       
-                       if (arguments == null)
-                               arg_count = 0;
-                       else
-                               arg_count = arguments.Count;
-                       
-                       ParameterData pd = GetParameterData (candidate);
+                       ParameterData pd = TypeManager.GetParameterData (candidate);
                        
                        int pd_count = pd.Count;
 
@@ -4643,10 +4926,10 @@ namespace Mono.CSharp {
 
                                Argument a = (Argument) arguments [i];
 
-                               Parameter.Modifier a_mod = a.GetParameterModifier () &
-                                       ~(Parameter.Modifier.OUT | Parameter.Modifier.REF);
+                               Parameter.Modifier a_mod = a.Modifier & 
+                                       (unchecked (~(Parameter.Modifier.OUT | Parameter.Modifier.REF)));
                                Parameter.Modifier p_mod = pd.ParameterModifier (i) &
-                                       ~(Parameter.Modifier.OUT | Parameter.Modifier.REF);
+                                       (unchecked (~(Parameter.Modifier.OUT | Parameter.Modifier.REF)));
 
                                if (a_mod == p_mod) {
 
@@ -4690,31 +4973,25 @@ namespace Mono.CSharp {
                        return true;
                }
 
-               static bool IsApplicable (EmitContext ec, MethodGroupExpr me,
-                                         ArrayList arguments, ref MethodBase candidate)
+               public static bool IsApplicable (EmitContext ec, MethodGroupExpr me,
+                                                ArrayList arguments, int arg_count,
+                                                ref MethodBase candidate)
                {
                        if (!me.HasTypeArguments &&
-                           !InferTypeArguments (ec, arguments, ref candidate))
+                           !TypeManager.InferTypeArguments (ec, arguments, ref candidate))
                                return false;
 
-                       return IsApplicable (ec, arguments, candidate);
+                       return IsApplicable (ec, arguments, arg_count, candidate);
                }
 
                /// <summary>
                ///   Determines if the candidate method is applicable (section 14.4.2.1)
                ///   to the given set of arguments
                /// </summary>
-               static bool IsApplicable (EmitContext ec, ArrayList arguments, MethodBase candidate)
+               static bool IsApplicable (EmitContext ec, ArrayList arguments, int arg_count,
+                                         MethodBase candidate)
                {
-                       int arg_count;
-
-                       if (arguments == null)
-                               arg_count = 0;
-                       else
-                               arg_count = arguments.Count;
-
-
-                       ParameterData pd = GetParameterData (candidate);
+                       ParameterData pd = TypeManager.GetParameterData (candidate);
 
                        if (arg_count != pd.Count)
                                return false;
@@ -4724,16 +5001,15 @@ namespace Mono.CSharp {
 
                                Argument a = (Argument) arguments [i];
 
-                               Parameter.Modifier a_mod = a.GetParameterModifier () &
-                                       ~(Parameter.Modifier.OUT | Parameter.Modifier.REF);
+                               Parameter.Modifier a_mod = a.Modifier &
+                                       unchecked (~(Parameter.Modifier.OUT | Parameter.Modifier.REF));
                                Parameter.Modifier p_mod = pd.ParameterModifier (i) &
-                                       ~(Parameter.Modifier.OUT | Parameter.Modifier.REF);
-
+                                       unchecked (~(Parameter.Modifier.OUT | Parameter.Modifier.REF));
 
                                if (a_mod == p_mod ||
                                    (a_mod == Parameter.Modifier.NONE && p_mod == Parameter.Modifier.PARAMS)) {
                                        if (a_mod == Parameter.Modifier.NONE) {
-                                                if (!Convert.ImplicitConversionExists (ec,
+                                                if (!TypeManager.IsEqual (a.Type, pd.ParameterType (i)) && !Convert.ImplicitConversionExists (ec,
                                                                                        a.Expr,
                                                                                        pd.ParameterType (i)))
                                                        return false;
@@ -4755,6 +5031,13 @@ namespace Mono.CSharp {
                        return true;
                }
                
+               static private bool IsAncestralType (Type first_type, Type second_type)
+               {
+                       return first_type != second_type &&
+                               (second_type.IsSubclassOf (first_type) ||
+                                TypeManager.ImplementsInterface (second_type, first_type));
+               }
+               
                /// <summary>
                ///   Find the Applicable Function Members (7.4.2.1)
                ///
@@ -4776,9 +5059,11 @@ namespace Mono.CSharp {
                                                          Location loc)
                {
                        MethodBase method = null;
+                       bool method_params = false;
                        Type applicable_type = null;
-                       int argument_count;
-                       ArrayList candidates = new ArrayList ();
+                       int arg_count = 0;
+                       ArrayList candidates = new ArrayList (2);
+                       ArrayList candidate_overrides = null;
 
                         //
                         // Used to keep a map between the candidate
@@ -4787,552 +5072,397 @@ namespace Mono.CSharp {
                         //
                         // false is normal form, true is expanded form
                         //
-                        Hashtable candidate_to_form = new PtrHashtable ();
-
+                        Hashtable candidate_to_form = null;
+
+                       if (Arguments != null)
+                               arg_count = Arguments.Count;
+  
+                       if ((me.Name == "Invoke") &&
+                               TypeManager.IsDelegateType (me.DeclaringType)) {
+                               Error_InvokeOnDelegate (loc);
+                               return null;
+                       }
 
-                        //
-                        // First we construct the set of applicable methods
-                        //
-                        // We start at the top of the type hierarchy and
-                        // go down to find applicable methods
-                        //
-                        applicable_type = me.DeclaringType;
-                        
-                        if (me.Name == "Invoke" && TypeManager.IsDelegateType (applicable_type)) {
-                                Error_InvokeOnDelegate (loc);
-                                return null;
-                        }
+                       MethodBase[] methods = me.Methods;
 
-                        bool found_applicable = false;
+                       //
+                       // First we construct the set of applicable methods
+                       //
+                       bool is_sorted = true;
+                       for (int i = 0; i < methods.Length; i++){
+                               Type decl_type = methods [i].DeclaringType;
 
-                       MethodBase[] methods = me.Methods;
+                               //
+                               // If we have already found an applicable method
+                               // we eliminate all base types (Section 14.5.5.1)
+                               //
+                               if ((applicable_type != null) &&
+                                       IsAncestralType (decl_type, applicable_type))
+                                       continue;
 
-                       for (int i = 0; i < methods.Length; i++) {
-                                Type decl_type = methods [i].DeclaringType;
-
-                                //
-                                // If we have already found an applicable method
-                                // we eliminate all base types (Section 14.5.5.1)
-                                //
-                                if (decl_type != applicable_type &&
-                                    (applicable_type.IsSubclassOf (decl_type) ||
-                                     TypeManager.ImplementsInterface (applicable_type, decl_type)) &&
-                                    found_applicable)
+                               //
+                               // Methods marked 'override' don't take part in 'applicable_type'
+                               // computation, nor in the actual overload resolution.
+                               // However, they still need to be emitted instead of a base virtual method.
+                               // We avoid doing the 'applicable' test here, since it'll anyway be applied
+                               // to the base virtual function, and IsOverride is much faster than IsApplicable.
+                               //
+                               if (!me.IsBase && TypeManager.IsOverride (methods [i])) {
+                                       if (candidate_overrides == null)
+                                               candidate_overrides = new ArrayList ();
+                                       candidate_overrides.Add (methods [i]);
                                        continue;
+                               }
 
+                               //
                                // Check if candidate is applicable (section 14.4.2.1)
-                               if (IsApplicable (ec, me, Arguments, ref methods [i])) {
-                                       // Candidate is applicable in normal form
+                               //   Is candidate applicable in normal form?
+                               //
+                               bool is_applicable = IsApplicable (
+                                       ec, me, Arguments, arg_count, ref methods [i]);
+
+                               if (!is_applicable &&
+                                       (IsParamsMethodApplicable (
+                                       ec, me, Arguments, arg_count, ref methods [i]))) {
                                        MethodBase candidate = methods [i];
-                                       candidates.Add (candidate);
-                                       applicable_type = candidate.DeclaringType;
-                                       found_applicable = true;
-                                       candidate_to_form [candidate] = false;
-                               } else if (IsParamsMethodApplicable (
-                                                  ec, me, Arguments,false, ref methods [i])) {
+                                       if (candidate_to_form == null)
+                                               candidate_to_form = new PtrHashtable ();
+                                       candidate_to_form [candidate] = candidate;
                                        // Candidate is applicable in expanded form
-                                       MethodBase candidate = methods [i];
-                                       candidates.Add (candidate);
-                                       applicable_type = candidate.DeclaringType;
-                                       found_applicable = true; 
-                                       candidate_to_form [candidate] = true;
-                               } else if (IsParamsMethodApplicable (
-                                                  ec, me, Arguments,true, ref methods [i])) {
-                                       // Candidate is applicable in expanded form
-                                       MethodBase candidate = methods [i];
-                                       candidates.Add (candidate);
-                                       applicable_type = candidate.DeclaringType;
-                                       found_applicable = true; 
-                                       candidate_to_form [candidate] = true;
+                                       is_applicable = true;
                                }
-                       }
 
-                       if (Arguments == null)
-                               argument_count = 0;
-                       else
-                               argument_count = Arguments.Count;
-
-                        //
-                        // Now we actually find the best method
-                        //
-                       int candidate_top = candidates.Count;
-                       for (int ix = 0; ix < candidate_top; ix++){
-                               MethodBase candidate = (MethodBase) candidates [ix];
-                               
-                                bool cand_params = (bool) candidate_to_form [candidate];
-                                bool method_params = false;
-                               
-                                if (method != null)
-                                        method_params = (bool) candidate_to_form [method];
-                                
-                                int x = BetterFunction (ec, Arguments,
-                                                        candidate, cand_params,
-                                                       method, method_params,
-                                                        loc);
-                                if (x == 0)
+                               if (!is_applicable)
                                         continue;
-                                
-                                method = candidate;
-                        }
 
-                       if (method == null) {
-                               int errors = Report.Errors;
+                               candidates.Add (methods [i]);
 
+                               if (applicable_type == null)
+                                       applicable_type = decl_type;
+                               else if (applicable_type != decl_type) {
+                                       is_sorted = false;
+                                       if (IsAncestralType (applicable_type, decl_type))
+                                               applicable_type = decl_type;
+                               }
+                       }
+
+                       int candidate_top = candidates.Count;
+
+                       if (applicable_type == null) {
                                //
                                // Okay so we have failed to find anything so we
                                // return by providing info about the closest match
                                //
+                               int errors = Report.Errors;
                                for (int i = 0; i < methods.Length; ++i) {
+                                       MethodBase c = (MethodBase) methods [i];
+                                       ParameterData pd = TypeManager.GetParameterData (c);
 
-                                       MethodBase c = methods [i];
-                                       if (c == null)
+                                       if (pd.Count != arg_count)
                                                continue;
 
-                                       ParameterData pd = GetParameterData (c);
-                                       if (pd.Count != argument_count)
+                                       if (!TypeManager.InferTypeArguments (ec, Arguments, ref c))
                                                continue;
 
-                                       if (!InferTypeArguments (ec, Arguments, ref c))
-                                               continue;
+                                       VerifyArgumentsCompat (ec, Arguments, arg_count,
+                                               c, false, null, may_fail, loc);
 
-                                       VerifyArgumentsCompat (ec, Arguments, argument_count,
-                                                              c, false, null, loc);
-                                        break;
-                               }
+                                       if (!may_fail && errors == Report.Errors)
+                                               throw new InternalErrorException (
+                                                       "VerifyArgumentsCompat and IsApplicable do not agree; " +
+                                                       "likely reason: ImplicitConversion and ImplicitConversionExists have gone out of sync");
 
-                               if (Report.Errors > errors)
-                                       return null;
+                                       break;
+                               }
 
-                               string report_name = me.Name;
-                               if (report_name == ".ctor")
-                                       report_name = me.DeclaringType.ToString ();
+                               if (!may_fail && errors == Report.Errors) {
+                                       string report_name = me.Name;
+                                       if (report_name == ".ctor")
+                                               report_name = me.DeclaringType.ToString ();
                                         
-                               for (int i = 0; i < methods.Length; ++i) {
+                                       for (int i = 0; i < methods.Length; ++i) {
+                                               MethodBase c = methods [i];
+                                               ParameterData pd = TypeManager.GetParameterData (c);
 
-                                       MethodBase c = methods [i];
-                                       if (c == null)
-                                               continue;
+                                               if (pd.Count != arg_count)
+                                                       continue;
 
-                                       ParameterData pd = GetParameterData (c);
-                                       if (pd.Count != argument_count)
-                                               continue;
+                                               if (TypeManager.InferTypeArguments (ec, Arguments, ref c))
+                                                       continue;
 
-                                       if (InferTypeArguments (ec, Arguments, ref c))
-                                               continue;
+                                               Report.Error (
+                                                       411, loc, "The type arguments for " +
+                                                       "method `{0}' cannot be infered from " +
+                                                       "the usage. Try specifying the type " +
+                                                       "arguments explicitly.", report_name);
+                                               return null;
+                                       }
 
-                                       Report.Error (411, loc, "The type arguments for " +
-                                                     "method `{0}' cannot be infered from " +
-                                                     "the usage. Try specifying the type " +
-                                                     "arguments explicitly.", report_name);
-                                        break;
+                                       Error_WrongNumArguments (loc, report_name, arg_count);
                                }
-
-                                if (!may_fail && (errors == Report.Errors))
-                                        Error_WrongNumArguments (loc, report_name,
-                                                                argument_count);
                                 
                                return null;
                        }
 
-                       //
-                       // Now check that there are no ambiguities i.e the selected method
-                       // should be better than all the others
-                       //
-                        bool best_params = (bool) candidate_to_form [method];
-
-                       for (int ix = 0; ix < candidate_top; ix++){
-                               MethodBase candidate = (MethodBase) candidates [ix];
-
-                                if (candidate == method)
-                                        continue;
-                                               
+                       if (!is_sorted) {
                                //
-                               // If a normal method is applicable in
-                               // the sense that it has the same
-                               // number of arguments, then the
-                               // expanded params method is never
-                               // applicable so we debar the params
-                               // method.
+                               // At this point, applicable_type is _one_ of the most derived types
+                               // in the set of types containing the methods in this MethodGroup.
+                               // Filter the candidates so that they only contain methods from the
+                               // most derived types.
                                //
-                                // if ((IsParamsMethodApplicable (ec, Arguments, candidate) &&
-//                                      IsApplicable (ec, Arguments, method)))
-//                                         continue;
-                                
-                                bool cand_params = (bool) candidate_to_form [candidate];
-                               int x = BetterFunction (ec, Arguments,
-                                                        method, best_params,
-                                                        candidate, cand_params,
-                                                       loc);
-
-                               if (x != 1) {
-                                       Report.Error (
-                                               121, loc,
-                                               "Ambiguous call when selecting function due to implicit casts");
-                                       return null;
-                               }
-                       }
 
-                       //
-                       // And now check if the arguments are all
-                       // compatible, perform conversions if
-                       // necessary etc. and return if everything is
-                       // all right
-                       //
-                        if (!VerifyArgumentsCompat (ec, Arguments, argument_count, method,
-                                                    best_params, null, loc))
-                               return null;
+                               int finalized = 0; // Number of finalized candidates
 
-                       return method;
-               }
+                               do {
+                                       // Invariant: applicable_type is a most derived type
+                                       
+                                       // We'll try to complete Section 14.5.5.1 for 'applicable_type' by 
+                                       // eliminating all it's base types.  At the same time, we'll also move
+                                       // every unrelated type to the end of the array, and pick the next
+                                       // 'applicable_type'.
+
+                                       Type next_applicable_type = null;
+                                       int j = finalized; // where to put the next finalized candidate
+                                       int k = finalized; // where to put the next undiscarded candidate
+                                       for (int i = finalized; i < candidate_top; ++i) {
+                                               MethodBase candidate = (MethodBase) candidates [i];
+                                               Type decl_type = candidate.DeclaringType;
+
+                                               if (decl_type == applicable_type) {
+                                                       candidates [k++] = candidates [j];
+                                                       candidates [j++] = candidates [i];
+                                                       continue;
+                                               }
 
-                static void Error_WrongNumArguments (Location loc, String name, int arg_count)
-                {
-                        Report.Error (1501, loc,
-                                      "No overload for method `" + name + "' takes `" +
-                                      arg_count + "' arguments");
-                }
+                                               if (IsAncestralType (decl_type, applicable_type))
+                                                       continue;
 
-                static void Error_InvokeOnDelegate (Location loc)
-                {
-                        Report.Error (1533, loc,
-                                      "Invoke cannot be called directly on a delegate");
-                }
-                        
-               static void Error_InvalidArguments (Location loc, int idx, MethodBase method,
-                                                    Type delegate_type, string arg_sig, string par_desc)
-               {
-                       if (delegate_type == null) 
-                               Report.Error (1502, loc,
-                                             "The best overloaded match for method '" +
-                                             FullMethodDesc (method) +
-                                             "' has some invalid arguments");
-                       else
-                               Report.Error (1594, loc,
-                                             "Delegate '" + delegate_type.ToString () +
-                                             "' has some invalid arguments.");
-                       Report.Error (1503, loc,
-                                     String.Format ("Argument {0}: Cannot convert from '{1}' to '{2}'",
-                                                    idx, arg_sig, par_desc));
-               }
-               
-               public static bool VerifyArgumentsCompat (EmitContext ec, ArrayList Arguments,
-                                                         int argument_count,
-                                                         MethodBase method, 
-                                                         bool chose_params_expanded,
-                                                         Type delegate_type,
-                                                         Location loc)
-               {
-                       ParameterData pd = GetParameterData (method);
-                       int pd_count = pd.Count;
-                       
-                       for (int j = 0; j < argument_count; j++) {
-                               Argument a = (Argument) Arguments [j];
-                               Expression a_expr = a.Expr;
-                               Type parameter_type = pd.ParameterType (j);
-                               Parameter.Modifier pm = pd.ParameterModifier (j);
-                               
-                               if (pm == Parameter.Modifier.PARAMS){
-                                       if ((pm & ~Parameter.Modifier.PARAMS) != a.GetParameterModifier ()) {
-                                               if (!Location.IsNull (loc))
-                                                       Error_InvalidArguments (
-                                                               loc, j, method, delegate_type,
-                                                               Argument.FullDesc (a), pd.ParameterDesc (j));
-                                               return false;
-                                       }
+                                               if (next_applicable_type != null &&
+                                                   IsAncestralType (decl_type, next_applicable_type))
+                                                       continue;
 
-                                       if (chose_params_expanded)
-                                               parameter_type = TypeManager.GetElementType (parameter_type);
-                               } else if (pm == Parameter.Modifier.ARGLIST){
-                                       continue;
-                               } else {
-                                       //
-                                       // Check modifiers
-                                       //
-                                       if (pd.ParameterModifier (j) != a.GetParameterModifier ()){
-                                               if (!Location.IsNull (loc))
-                                                       Error_InvalidArguments (
-                                                               loc, j, method, delegate_type,
-                                                               Argument.FullDesc (a), pd.ParameterDesc (j));
-                                               return false;
-                                       }
-                               }
-
-                               //
-                               // Check Type
-                               //
-                               if (a.Type != parameter_type){
-                                       Expression conv;
-                                       
-                                       conv = Convert.ImplicitConversion (ec, a_expr, parameter_type, loc);
+                                               candidates [k++] = candidates [i];
 
-                                       if (conv == null) {
-                                               if (!Location.IsNull (loc)) 
-                                                       Error_InvalidArguments (
-                                                               loc, j, method, delegate_type,
-                                                               Argument.FullDesc (a), pd.ParameterDesc (j));
-                                               return false;
+                                               if (next_applicable_type == null ||
+                                                   IsAncestralType (next_applicable_type, decl_type))
+                                                       next_applicable_type = decl_type;
                                        }
-                                       
-                                       //
-                                       // Update the argument with the implicit conversion
-                                       //
-                                       if (a_expr != conv)
-                                               a.Expr = conv;
-                               }
 
-                               Parameter.Modifier a_mod = a.GetParameterModifier () &
-                                       ~(Parameter.Modifier.OUT | Parameter.Modifier.REF);
-                               Parameter.Modifier p_mod = pd.ParameterModifier (j) &
-                                       ~(Parameter.Modifier.OUT | Parameter.Modifier.REF);
-                               
-                               if (a_mod != p_mod &&
-                                   pd.ParameterModifier (pd_count - 1) != Parameter.Modifier.PARAMS) {
-                                       if (!Location.IsNull (loc)) {
-                                               Report.Error (1502, loc,
-                                                      "The best overloaded match for method '" + FullMethodDesc (method)+
-                                                      "' has some invalid arguments");
-                                               Report.Error (1503, loc,
-                                                      "Argument " + (j+1) +
-                                                      ": Cannot convert from '" + Argument.FullDesc (a) 
-                                                      + "' to '" + pd.ParameterDesc (j) + "'");
-                                       }
-                                       
-                                       return false;
-                               }
+                                       applicable_type = next_applicable_type;
+                                       finalized = j;
+                                       candidate_top = k;
+                               } while (applicable_type != null);
                        }
 
-                       return true;
-               }
+                        //
+                        // Now we actually find the best method
+                        //
 
-               static bool InferType (Type pt, Type at, ref Type[] infered)
-               {
-                       if (pt.IsGenericParameter) {
-                               int pos = pt.GenericParameterPosition;
+                       method = (MethodBase) candidates [0];
+                       method_params = candidate_to_form != null && candidate_to_form.Contains (method);
+                       for (int ix = 1; ix < candidate_top; ix++){
+                               MethodBase candidate = (MethodBase) candidates [ix];
 
-                               if (infered [pos] == null) {
-                                       Type check = at;
-                                       while (check.IsArray)
-                                               check = check.GetElementType ();
+                               if (candidate == method)
+                                       continue;
 
-                                       if (pt.Equals (check))
-                                               return false;
+                               bool cand_params = candidate_to_form != null && candidate_to_form.Contains (candidate);
 
-                                       infered [pos] = at;
-                                       return true;
+                               if (BetterFunction (ec, Arguments, arg_count, 
+                                                   candidate, cand_params,
+                                                   method, method_params, loc)) {
+                                       method = candidate;
+                                       method_params = cand_params;
                                }
-
-                               if (infered [pos] != at)
-                                       return false;
-
-                               return true;
                        }
+                       //
+                       // Now check that there are no ambiguities i.e the selected method
+                       // should be better than all the others
+                       //
+                       MethodBase ambiguous = null;
+                       for (int ix = 0; ix < candidate_top; ix++){
+                               MethodBase candidate = (MethodBase) candidates [ix];
 
-                       if (!pt.ContainsGenericParameters)
-                               return true;
-
-                       if (at.IsArray) {
-                               if (!pt.IsArray ||
-                                   (at.GetArrayRank () != pt.GetArrayRank ()))
-                                       return false;
-
-                               return InferType (pt.GetElementType (), at.GetElementType (),
-                                                 ref infered);
-                       }
-
-                       if (pt.IsArray) {
-                               if (!at.IsArray ||
-                                   (pt.GetArrayRank () != at.GetArrayRank ()))
-                                       return false;
-
-                               return InferType (pt.GetElementType (), at.GetElementType (),
-                                                 ref infered);
-                       }
-
-                       if (!at.IsGenericInstance)
-                               return false;
-
-                       Type[] at_args = at.GetGenericArguments ();
-                       Type[] pt_args = pt.GetGenericArguments ();
-
-                       if (at_args.Length != pt_args.Length)
-                               return false;
-
-                       Type[] infered_types = new Type [at_args.Length];
-
-                       for (int i = 0; i < at_args.Length; i++)
-                               if (!InferType (pt_args [i], at_args [i], ref infered_types))
-                                       return false;
-
-                       for (int i = 0; i < infered_types.Length; i++)
-                               if (infered_types [i] == null)
-                                       return false;
+                                if (candidate == method)
+                                        continue;
 
-                       for (int i = 0; i < infered_types.Length; i++) {
-                               if (infered [i] == null) {
-                                       infered [i] = infered_types [i];
-                                       continue;
+                                bool cand_params = candidate_to_form != null && candidate_to_form.Contains (candidate);
+                               if (!BetterFunction (ec, Arguments, arg_count,
+                                                   method, method_params,
+                                                   candidate, cand_params,
+                                                    loc)) {
+                                       Report.SymbolRelatedToPreviousError (candidate);
+                                       ambiguous = candidate;
                                }
-
-                               if (infered [i] != infered_types [i])
-                                       return false;
                        }
 
-                       return true;
-               }
-
-               static bool InferParamsTypeArguments (EmitContext ec, ArrayList arguments,
-                                                     ref MethodBase method)
-               {
-                       if ((arguments == null) || !TypeManager.IsGenericMethod (method))
-                               return true;
-
-                       int arg_count;
-                       
-                       if (arguments == null)
-                               arg_count = 0;
-                       else
-                               arg_count = arguments.Count;
-                       
-                       ParameterData pd = GetParameterData (method);
-
-                       int pd_count = pd.Count;
-
-                       if (pd_count == 0)
-                               return false;
-                       
-                       if (pd.ParameterModifier (pd_count - 1) != Parameter.Modifier.PARAMS)
-                               return false;
-                       
-                       if (pd_count - 1 > arg_count)
-                               return false;
-                       
-                       if (pd_count == 1 && arg_count == 0)
-                               return true;
-
-                       Type[] method_args = method.GetGenericArguments ();
-                       Type[] infered_types = new Type [method_args.Length];
+                       if (ambiguous != null) {
+                               Report.SymbolRelatedToPreviousError (method);
+                               Report.Error (121, loc, "The call is ambiguous between the following methods or properties: `{0}' and `{1}'",
+                                       TypeManager.CSharpSignature (ambiguous), TypeManager.CSharpSignature (method));
+                               return null;
+                       }
 
                        //
-                       // If we have come this far, the case which
-                       // remains is when the number of parameters is
-                       // less than or equal to the argument count.
+                       // If the method is a virtual function, pick an override closer to the LHS type.
                        //
-                       for (int i = 0; i < pd_count - 1; ++i) {
-                               Argument a = (Argument) arguments [i];
-
-                               if ((a.Expr is NullLiteral) || (a.Expr is MethodGroupExpr))
-                                       continue;
-
-                               Type pt = pd.ParameterType (i);
-                               Type at = a.Type;
-
-                               if (!InferType (pt, at, ref infered_types))
-                                       return false;
-                       }
-
-                       Type element_type = TypeManager.GetElementType (pd.ParameterType (pd_count - 1));
-
-                       for (int i = pd_count - 1; i < arg_count; i++) {
-                               Argument a = (Argument) arguments [i];
-
-                               if ((a.Expr is NullLiteral) || (a.Expr is MethodGroupExpr))
-                                       continue;
+                       if (!me.IsBase && method.IsVirtual) {
+                               if (TypeManager.IsOverride (method))
+                                       throw new InternalErrorException (
+                                               "Should not happen.  An 'override' method took part in overload resolution: " + method);
 
-                               if (!InferType (element_type, a.Type, ref infered_types))
-                                       return false;
+                               if (candidate_overrides != null)
+                                       foreach (MethodBase candidate in candidate_overrides) {
+                                               if (IsOverride (candidate, method))
+                                                       method = candidate;
+                                       }
                        }
 
-                       for (int i = 0; i < infered_types.Length; i++)
-                               if (infered_types [i] == null)
-                                       return false;
-
-                       method = method.BindGenericParameters (infered_types);
-                       return true;
-               }
-
-               public static bool InferTypeArguments (Type[] param_types, Type[] arg_types,
-                                                      ref Type[] infered_types)
-               {
-                       for (int i = 0; i < arg_types.Length; i++) {
-                               if (arg_types [i] == null)
-                                       continue;
+                       //
+                       // And now check if the arguments are all
+                       // compatible, perform conversions if
+                       // necessary etc. and return if everything is
+                       // all right
+                       //
+                        if (!VerifyArgumentsCompat (ec, Arguments, arg_count, method,
+                                                    method_params, null, may_fail, loc))
+                               return null;
 
-                               if (!InferType (param_types [i], arg_types [i],
-                                               ref infered_types))
-                                       return false;
+                       if (method != null) {
+                               MethodBase the_method = method;
+                               if (the_method.Mono_IsInflatedMethod)
+                                       the_method = the_method.GetGenericMethodDefinition ();
+                               IMethodData data = TypeManager.GetMethod (the_method);
+                               if (data != null)
+                                       data.SetMemberIsUsed ();
                        }
-
-                       for (int i = 0; i < infered_types.Length; i++)
-                               if (infered_types [i] == null)
-                                       return false;
-
-                       return true;
+                       return method;
                }
 
-               static bool InferTypeArguments (EmitContext ec, ArrayList arguments,
-                                               ref MethodBase method)
+               public static void Error_WrongNumArguments (Location loc, String name, int arg_count)
                {
-                       if (!TypeManager.IsGenericMethod (method))
-                               return true;
+                       Report.Error (1501, loc, "No overload for method `{0}' takes `{1}' arguments",
+                               name, arg_count);
+               }
 
-                       int arg_count;
-                       if (arguments != null)
-                               arg_count = arguments.Count;
+                static void Error_InvokeOnDelegate (Location loc)
+                {
+                        Report.Error (1533, loc,
+                                      "Invoke cannot be called directly on a delegate");
+                }
+                        
+               static void Error_InvalidArguments (Location loc, int idx, MethodBase method,
+                                                    Type delegate_type, Argument a, ParameterData expected_par)
+               {
+                       if (delegate_type == null) 
+                               Report.Error (1502, loc, "The best overloaded method match for `{0}' has some invalid arguments",
+                                             TypeManager.CSharpSignature (method));
                        else
-                               arg_count = 0;
-
-                       ParameterData pd = GetParameterData (method);
-                       if (arg_count != pd.Count)
-                               return false;
-
-                       Type[] method_args = method.GetGenericArguments ();
-                       Type[] infered_types = new Type [method_args.Length];
-
-                       Type[] param_types = new Type [pd.Count];
-                       Type[] arg_types = new Type [pd.Count];
-
-                       for (int i = 0; i < arg_count; i++) {
-                               param_types [i] = pd.ParameterType (i);
+                               Report.Error (1594, loc, "Delegate `{0}' has some invalid arguments",
+                                       TypeManager.CSharpName (delegate_type));
 
-                               Argument a = (Argument) arguments [i];
-                               if ((a.Expr is NullLiteral) || (a.Expr is MethodGroupExpr))
-                                       continue;
+                       string par_desc = expected_par.ParameterDesc (idx);
 
-                               arg_types [i] = a.Type;
+                       if (a.Modifier != expected_par.ParameterModifier (idx)) {
+                               if ((expected_par.ParameterModifier (idx) & (Parameter.Modifier.REF | Parameter.Modifier.OUT)) == 0)
+                                       Report.Error (1615, loc, "Argument `{0}' should not be passed with the `{1}' keyword",
+                                               idx + 1, Parameter.GetModifierSignature (a.Modifier));
+                               else
+                                       Report.Error (1620, loc, "Argument `{0}' must be passed with the `{1}' keyword",
+                                               idx + 1, Parameter.GetModifierSignature (expected_par.ParameterModifier (idx)));
+                               return;
                        }
 
-                       if (!InferTypeArguments (param_types, arg_types, ref infered_types))
-                               return false;
-
-                       method = method.BindGenericParameters (infered_types);
-                       return true;
+                       Report.Error (1503, loc,
+                                     String.Format ("Argument {0}: Cannot convert from `{1}' to `{2}'",
+                                                    idx + 1, Argument.FullDesc (a), par_desc));
                }
-
-               public static bool InferTypeArguments (EmitContext ec, ParameterData apd,
-                                                      ref MethodBase method)
+               
+               public static bool VerifyArgumentsCompat (EmitContext ec, ArrayList Arguments,
+                                                         int arg_count, MethodBase method, 
+                                                         bool chose_params_expanded,
+                                                         Type delegate_type, bool may_fail,
+                                                         Location loc)
                {
-                       if (!TypeManager.IsGenericMethod (method))
-                               return true;
+                       ParameterData pd = TypeManager.GetParameterData (method);
+                       int pd_count = pd.Count;
+                       
+                       for (int j = 0; j < arg_count; j++) {
+                               Argument a = (Argument) Arguments [j];
+                               Expression a_expr = a.Expr;
+                               Type parameter_type = pd.ParameterType (j);
+                               Parameter.Modifier pm = pd.ParameterModifier (j);
+                               
+                               if (pm == Parameter.Modifier.PARAMS){
+                                       if ((pm & ~Parameter.Modifier.PARAMS) != a.Modifier) {
+                                               if (!may_fail)
+                                                       Error_InvalidArguments (
+                                                               loc, j, method, delegate_type,
+                                                               a, pd);
+                                               return false;
+                                       }
 
-                       ParameterData pd = GetParameterData (method);
-                       if (apd.Count != pd.Count)
-                               return false;
+                                       if (chose_params_expanded)
+                                               parameter_type = TypeManager.GetElementType (parameter_type);
+                               } else if (pm == Parameter.Modifier.ARGLIST){
+                                       continue;
+                               } else {
+                                       //
+                                       // Check modifiers
+                                       //
+                                       if (pd.ParameterModifier (j) != a.Modifier){
+                                               if (!may_fail)
+                                                       Error_InvalidArguments (
+                                                               loc, j, method, delegate_type,
+                                                               a, pd);
+                                               return false;
+                                       }
+                               }
 
-                       Type[] method_args = method.GetGenericArguments ();
-                       Type[] infered_types = new Type [method_args.Length];
+                               //
+                               // Check Type
+                               //
+                               if (!TypeManager.IsEqual (a.Type, parameter_type)){
+                                       Expression conv;
 
-                       Type[] param_types = new Type [pd.Count];
-                       Type[] arg_types = new Type [pd.Count];
+                                       conv = Convert.ImplicitConversion (ec, a_expr, parameter_type, loc);
 
-                       for (int i = 0; i < apd.Count; i++) {
-                               param_types [i] = pd.ParameterType (i);
-                               arg_types [i] = apd.ParameterType (i);
-                       }
+                                       if (conv == null) {
+                                               if (!may_fail)
+                                                       Error_InvalidArguments (loc, j, method, delegate_type, a, pd);
+                                               return false;
+                                       }
+                                       
+                                       //
+                                       // Update the argument with the implicit conversion
+                                       //
+                                       if (a_expr != conv)
+                                               a.Expr = conv;
+                               }
 
-                       if (!InferTypeArguments (param_types, arg_types, ref infered_types))
-                               return false;
+                               if (parameter_type.IsPointer){
+                                       if (!ec.InUnsafe){
+                                               UnsafeError (loc);
+                                               return false;
+                                       }
+                               }
+                               
+                               Parameter.Modifier a_mod = a.Modifier &
+                                       unchecked (~(Parameter.Modifier.OUT | Parameter.Modifier.REF));
+                               Parameter.Modifier p_mod = pd.ParameterModifier (j) &
+                                       unchecked (~(Parameter.Modifier.OUT | Parameter.Modifier.REF));
+                               
+                               if (a_mod != p_mod &&
+                                   pd.ParameterModifier (pd_count - 1) != Parameter.Modifier.PARAMS) {
+                                       if (!may_fail) {
+                                               Invocation.Error_InvalidArguments (loc, j, method, null, a, pd);
+                                       }
+                                       
+                                       return false;
+                               }
+                       }
 
-                       method = method.BindGenericParameters (infered_types);
                        return true;
                }
 
@@ -5342,11 +5472,9 @@ namespace Mono.CSharp {
                        // First, resolve the expression that is used to
                        // trigger the invocation
                        //
-                       if (expr is BaseAccess)
-                               is_base = true;
-
-                       if (expr is ConstructedType)
-                               expr = ((ConstructedType) expr).GetSimpleName (ec);
+                       SimpleName sn = expr as SimpleName;
+                       if (sn != null)
+                               expr = sn.GetMethodGroup ();
 
                        expr = expr.Resolve (ec, ResolveFlags.VariableOrValue | ResolveFlags.MethodGroup);
                        if (expr == null)
@@ -5364,7 +5492,7 @@ namespace Mono.CSharp {
                        }
 
                        if (!(expr is MethodGroupExpr)){
-                               expr.Error_UnexpectedKind (ResolveFlags.MethodGroup);
+                               expr.Error_UnexpectedKind (ResolveFlags.MethodGroup, loc);
                                return null;
                        }
 
@@ -5387,17 +5515,19 @@ namespace Mono.CSharp {
                        MethodInfo mi = method as MethodInfo;
                        if (mi != null) {
                                type = TypeManager.TypeToCoreType (mi.ReturnType);
-                               if (!mi.IsStatic && !mg.IsExplicitImpl && (mg.InstanceExpression == null)) {
-                                       SimpleName.Error_ObjectRefRequired (ec, loc, mi.Name);
-                                       return null;
-                               }
-
                                Expression iexpr = mg.InstanceExpression;
-                               if (mi.IsStatic && (iexpr != null) && !(iexpr is This)) {
-                                       if (mg.IdenticalTypeName)
+                               if (mi.IsStatic) {
+                                       if (iexpr == null || 
+                                           iexpr is This || iexpr is EmptyExpression ||
+                                           mg.IdenticalTypeName) {
                                                mg.InstanceExpression = null;
-                                       else {
-                                               MemberAccess.error176 (loc, mi.Name);
+                                       } else {
+                                               MemberExpr.error176 (loc, TypeManager.CSharpSignature (mi));
+                                               return null;
+                                       }
+                               } else {
+                                       if (iexpr == null || iexpr is EmptyExpression) {
+                                               SimpleName.Error_ObjectRefRequired (ec, loc, TypeManager.CSharpSignature (mi));
                                                return null;
                                        }
                                }
@@ -5413,21 +5543,56 @@ namespace Mono.CSharp {
                        //
                        // Only base will allow this invocation to happen.
                        //
-                       if (is_base && method.IsAbstract){
-                               Report.Error (205, loc, "Cannot call an abstract base member: " +
-                                             FullMethodDesc (method));
+                       if (mg.IsBase && method.IsAbstract){
+                               Error_CannotCallAbstractBase (TypeManager.CSharpSignature (method));
+                               return null;
+                       }
+
+                       if (Arguments == null && method.Name == "Finalize") {
+                               if (mg.IsBase)
+                                       Report.Error (250, loc, "Do not directly call your base class Finalize method. It is called automatically from your destructor");
+                               else
+                                       Report.Error (245, loc, "Destructors and object.Finalize cannot be called directly. Consider calling IDisposable.Dispose if available");
                                return null;
                        }
 
-                       if ((method.Attributes & MethodAttributes.SpecialName) != 0){
-                               if (TypeManager.IsSpecialMethod (method))
-                                       Report.Error (571, loc, method.Name + ": can not call operator or accessor");
+                       if ((method.Attributes & MethodAttributes.SpecialName) != 0 && IsSpecialMethodInvocation (method)) {
+                               return null;
                        }
                        
+                       if (mg.InstanceExpression != null)
+                               mg.InstanceExpression.CheckMarshallByRefAccess (ec.ContainerType);
+
                        eclass = ExprClass.Value;
                        return this;
                }
 
+               bool IsSpecialMethodInvocation (MethodBase method)
+               {
+                       IMethodData md = TypeManager.GetMethod (method);
+                       if (md != null) {
+                               if (!(md is AbstractPropertyEventMethod) && !(md is Operator))
+                                       return false;
+                       } else {
+                               if (!TypeManager.IsSpecialMethod (method))
+                                       return false;
+
+                               int args = TypeManager.GetParameterData (method).Count;
+                               if (method.Name.StartsWith ("get_") && args > 0)
+                                       return false;
+                               else if (method.Name.StartsWith ("set_") && args > 2)
+                                       return false;
+
+                               // TODO: check operators and events as well ?
+                       }
+
+                       Report.SymbolRelatedToPreviousError (method);
+                       Report.Error (571, loc, "`{0}': cannot explicitly call operator or accessor",
+                               TypeManager.CSharpSignature (method, true));
+       
+                       return true;
+               }
+
                // <summary>
                //   Emits the list of arguments as an array
                // </summary>
@@ -5470,14 +5635,24 @@ namespace Mono.CSharp {
                ///   emission of the arguments is known not to contain
                ///   a `params' field (for example in constructors or other routines
                ///   that keep their arguments in this structure)
+               ///   
+               ///   if `dup_args' is true, a copy of the arguments will be left
+               ///   on the stack. If `dup_args' is true, you can specify `this_arg'
+               ///   which will be duplicated before any other args. Only EmitCall
+               ///   should be using this interface.
                /// </summary>
-               public static void EmitArguments (EmitContext ec, MethodBase mb, ArrayList arguments)
+               public static void EmitArguments (EmitContext ec, MethodBase mb, ArrayList arguments, bool dup_args, LocalTemporary this_arg)
                {
                        ParameterData pd;
                        if (mb != null)
-                               pd = GetParameterData (mb);
+                               pd = TypeManager.GetParameterData (mb);
                        else
                                pd = null;
+                       
+                       LocalTemporary [] temps = null;
+                       
+                       if (dup_args)
+                               temps = new LocalTemporary [arguments.Count];
 
                        //
                        // If we are calling a params method with no arguments, special case it
@@ -5514,6 +5689,18 @@ namespace Mono.CSharp {
                                }
                                            
                                a.Emit (ec);
+                               if (dup_args) {
+                                       ec.ig.Emit (OpCodes.Dup);
+                                       (temps [i] = new LocalTemporary (ec, a.Type)).Store (ec);
+                               }
+                       }
+                       
+                       if (dup_args) {
+                               if (this_arg != null)
+                                       this_arg.Emit (ec);
+                               
+                               for (int i = 0; i < top; i ++)
+                                       temps [i].Emit (ec);
                        }
 
                        if (pd != null && pd.Count > top &&
@@ -5528,7 +5715,7 @@ namespace Mono.CSharp {
                static Type[] GetVarargsTypes (EmitContext ec, MethodBase mb,
                                               ArrayList arguments)
                {
-                       ParameterData pd = GetParameterData (mb);
+                       ParameterData pd = TypeManager.GetParameterData (mb);
 
                        if (arguments == null)
                                return new Type [0];
@@ -5577,10 +5764,25 @@ namespace Mono.CSharp {
                public static void EmitCall (EmitContext ec, bool is_base,
                                             bool is_static, Expression instance_expr,
                                             MethodBase method, ArrayList Arguments, Location loc)
+               {
+                       EmitCall (ec, is_base, is_static, instance_expr, method, Arguments, loc, false, false);
+               }
+               
+               // `dup_args' leaves an extra copy of the arguments on the stack
+               // `omit_args' does not leave any arguments at all.
+               // So, basically, you could make one call with `dup_args' set to true,
+               // and then another with `omit_args' set to true, and the two calls
+               // would have the same set of arguments. However, each argument would
+               // only have been evaluated once.
+               public static void EmitCall (EmitContext ec, bool is_base,
+                                            bool is_static, Expression instance_expr,
+                                            MethodBase method, ArrayList Arguments, Location loc,
+                                            bool dup_args, bool omit_args)
                {
                        ILGenerator ig = ec.ig;
                        bool struct_call = false;
                        bool this_call = false;
+                       LocalTemporary this_arg = null;
 
                        Type decl_type = method.DeclaringType;
 
@@ -5603,79 +5805,98 @@ namespace Mono.CSharp {
                                        method = TypeManager.void_array_copyto_array_int;
                        }
 
-                       //
-                       // This checks ObsoleteAttribute on the method and on the declaring type
-                       //
-                       ObsoleteAttribute oa = AttributeTester.GetMethodObsoleteAttribute (method);
-                       if (oa != null)
-                               AttributeTester.Report_ObsoleteMessage (oa, TypeManager.CSharpSignature (method), loc);
-
-                       oa = AttributeTester.GetObsoleteAttribute (method.DeclaringType);
-                       if (oa != null) {
-                               AttributeTester.Report_ObsoleteMessage (oa, method.DeclaringType.FullName, loc);
-                       }
-
+                       if (ec.TestObsoleteMethodUsage) {
+                               //
+                               // This checks ObsoleteAttribute on the method and on the declaring type
+                               //
+                               ObsoleteAttribute oa = AttributeTester.GetMethodObsoleteAttribute (method);
+                               if (oa != null)
+                                       AttributeTester.Report_ObsoleteMessage (oa, TypeManager.CSharpSignature (method), loc);
 
-                       oa = AttributeTester.GetObsoleteAttribute (method.DeclaringType);
-                       if (oa != null) {
-                               AttributeTester.Report_ObsoleteMessage (oa, method.DeclaringType.FullName, loc);
+                               oa = AttributeTester.GetObsoleteAttribute (method.DeclaringType);
+                               if (oa != null) {
+                                       AttributeTester.Report_ObsoleteMessage (oa, method.DeclaringType.FullName, loc);
+                               }
                        }
 
                        if (IsMethodExcluded (method, ec))
                                return;
                        
                        if (!is_static){
-                               if (TypeManager.IsValueType (decl_type))
+                               if (instance_expr == EmptyExpression.Null) {
+                                       SimpleName.Error_ObjectRefRequired (ec, loc, TypeManager.CSharpSignature (method));
+                                       return;
+                               }
+
+                               this_call = instance_expr is This;
+                               if (decl_type.IsValueType || (!this_call && instance_expr.Type.IsValueType))
                                        struct_call = true;
+
                                //
                                // If this is ourselves, push "this"
                                //
-                               if (instance_expr == null){
-                                       this_call = true;
-                                       ig.Emit (OpCodes.Ldarg_0);
-                               } else {
-                                       Type itype = instance_expr.Type;
+                               if (!omit_args) {
+                                       Type t = null;
+                                       if (this_call) {
+                                               ec.EmitThis ();
+                                               t = decl_type;
+                                       } else {
+                                               Type iexpr_type = instance_expr.Type;
 
-                                       //
-                                       // Push the instance expression
-                                       //
-                                       if (TypeManager.IsValueType (itype)){
                                                //
-                                               // Special case: calls to a function declared in a 
-                                               // reference-type with a value-type argument need
-                                               // to have their value boxed.  
-                                               if (decl_type.IsValueType || itype.IsGenericParameter){
-                                                       //
-                                                       // If the expression implements IMemoryLocation, then
-                                                       // we can optimize and use AddressOf on the
-                                                       // return.
+                                               // Push the instance expression
+                                               //
+                                               if (TypeManager.IsValueType (iexpr_type)) {
                                                        //
-                                                       // If not we have to use some temporary storage for
-                                                       // it.
-                                                       if (instance_expr is IMemoryLocation){
-                                                               ((IMemoryLocation)instance_expr).
-                                                                       AddressOf (ec, AddressOp.LoadStore);
-                                                       }
-                                                       else {
+                                                       // Special case: calls to a function declared in a 
+                                                       // reference-type with a value-type argument need
+                                                       // to have their value boxed.
+                                                       if (decl_type.IsValueType ||
+                                                           iexpr_type.IsGenericParameter) {
+                                                               //
+                                                               // If the expression implements IMemoryLocation, then
+                                                               // we can optimize and use AddressOf on the
+                                                               // return.
+                                                               //
+                                                               // If not we have to use some temporary storage for
+                                                               // it.
+                                                               if (instance_expr is IMemoryLocation) {
+                                                                       ((IMemoryLocation)instance_expr).
+                                                                               AddressOf (ec, AddressOp.LoadStore);
+                                                               } else {
+                                                                       LocalTemporary temp = new LocalTemporary (ec, iexpr_type);
+                                                                       instance_expr.Emit (ec);
+                                                                       temp.Store (ec);
+                                                                       temp.AddressOf (ec, AddressOp.Load);
+                                                               }
+
+                                                               // avoid the overhead of doing this all the time.
+                                                               if (dup_args)
+                                                                       t = TypeManager.GetReferenceType (iexpr_type);
+                                                       } else {
                                                                instance_expr.Emit (ec);
-                                                               LocalBuilder temp = ig.DeclareLocal (itype);
-                                                               ig.Emit (OpCodes.Stloc, temp);
-                                                               ig.Emit (OpCodes.Ldloca, temp);
+                                                               ig.Emit (OpCodes.Box, instance_expr.Type);
+                                                               t = TypeManager.object_type;
                                                        }
-                                                       if (itype.IsGenericParameter)
-                                                               ig.Emit (OpCodes.Constrained, itype);
-                                                       else
-                                                               struct_call = true;
                                                } else {
                                                        instance_expr.Emit (ec);
-                                                       ig.Emit (OpCodes.Box, itype);
-                                               } 
-                                       } else
-                                               instance_expr.Emit (ec);
+                                                       t = instance_expr.Type;
+                                               }
+                                       }
+
+                                       if (dup_args) {
+                                               this_arg = new LocalTemporary (ec, t);
+                                               ig.Emit (OpCodes.Dup);
+                                               this_arg.Store (ec);
+                                       }
                                }
                        }
 
-                       EmitArguments (ec, method, Arguments);
+                       if (!omit_args)
+                               EmitArguments (ec, method, Arguments, dup_args, this_arg);
+
+                       if ((instance_expr != null) && (instance_expr.Type.IsGenericParameter))
+                               ig.Emit (OpCodes.Constrained, instance_expr.Type);
 
                        OpCode call_op;
                        if (is_static || struct_call || is_base || (this_call && !method.IsVirtual))
@@ -5695,9 +5916,9 @@ namespace Mono.CSharp {
                        // and DoFoo is not virtual, you can omit the callvirt,
                        // because you don't need the null checking behavior.
                        //
-                               if (method is MethodInfo)
+                       if (method is MethodInfo)
                                ig.Emit (call_op, (MethodInfo) method);
-                               else
+                       else
                                ig.Emit (call_op, (ConstructorInfo) method);
                }
                
@@ -5705,7 +5926,7 @@ namespace Mono.CSharp {
                {
                        MethodGroupExpr mg = (MethodGroupExpr) this.expr;
 
-                       EmitCall (ec, is_base, method.IsStatic, mg.InstanceExpression, method, Arguments, loc);
+                       EmitCall (ec, mg.IsBase, method.IsStatic, mg.InstanceExpression, method, Arguments, loc);
                }
                
                public override void EmitStatement (EmitContext ec)
@@ -5728,11 +5949,11 @@ namespace Mono.CSharp {
                Expression expr;
                Expression argument;
 
-               public InvocationOrCast (Expression expr, Expression argument, Location loc)
+               public InvocationOrCast (Expression expr, Expression argument)
                {
                        this.expr = expr;
                        this.argument = argument;
-                       this.loc = loc;
+                       this.loc = expr.Location;
                }
 
                public override Expression DoResolve (EmitContext ec)
@@ -5740,9 +5961,9 @@ namespace Mono.CSharp {
                        //
                        // First try to resolve it as a cast.
                        //
-                       type = ec.DeclSpace.ResolveType (expr, true, loc);
-                       if (type != null) {
-                               Cast cast = new Cast (new TypeExpression (type, loc), argument, loc);
+                       TypeExpr te = expr.ResolveAsTypeStep (ec) as TypeExpr;
+                       if ((te != null) && (te.eclass == ExprClass.Type)) {
+                               Cast cast = new Cast (te, argument, loc);
                                return cast.Resolve (ec);
                        }
 
@@ -5787,8 +6008,8 @@ namespace Mono.CSharp {
                        //
                        // First try to resolve it as a cast.
                        //
-                       type = ec.DeclSpace.ResolveType (expr, true, loc);
-                       if (type != null) {
+                       TypeExpr te = expr.ResolveAsTypeStep (ec) as TypeExpr;
+                       if ((te != null) && (te.eclass == ExprClass.Type)) {
                                error201 ();
                                return null;
                        }
@@ -5874,7 +6095,7 @@ namespace Mono.CSharp {
                        value_target = value;
                        value_target_set = true;
                        if (!(value_target is IMemoryLocation)){
-                               Error_UnexpectedKind ("variable");
+                               Error_UnexpectedKind (null, "variable", loc);
                                return false;
                        }
                        return true;
@@ -5907,6 +6128,42 @@ namespace Mono.CSharp {
 //                     value_target = MyEmptyExpression;
                }
 
+
+               /// <summary>
+               /// Converts complex core type syntax like 'new int ()' to simple constant
+               /// </summary>
+               public static Constant Constantify (Type t)
+               {
+                       if (t == TypeManager.int32_type)
+                               return new IntConstant (0);
+                       if (t == TypeManager.uint32_type)
+                               return new UIntConstant (0);
+                       if (t == TypeManager.int64_type)
+                               return new LongConstant (0);
+                       if (t == TypeManager.uint64_type)
+                               return new ULongConstant (0);
+                       if (t == TypeManager.float_type)
+                               return new FloatConstant (0);
+                       if (t == TypeManager.double_type)
+                               return new DoubleConstant (0);
+                       if (t == TypeManager.short_type)
+                               return new ShortConstant (0);
+                       if (t == TypeManager.ushort_type)
+                               return new UShortConstant (0);
+                       if (t == TypeManager.sbyte_type)
+                               return new SByteConstant (0);
+                       if (t == TypeManager.byte_type)
+                               return new ByteConstant (0);
+                       if (t == TypeManager.char_type)
+                               return new CharConstant ('\0');
+                       if (t == TypeManager.bool_type)
+                               return new BoolConstant (false);
+                       if (t == TypeManager.decimal_type)
+                               return new DecimalConstant (0);
+
+                       return null;
+               }
+
                public override Expression DoResolve (EmitContext ec)
                {
                        //
@@ -5922,26 +6179,35 @@ namespace Mono.CSharp {
                                        return RequestedType;
                                return this;
                        }
-                       
-                       type = ec.DeclSpace.ResolveType (RequestedType, false, loc);
-                       
+
+                       TypeExpr texpr = RequestedType.ResolveAsTypeTerminal (ec);
+                       if (texpr == null)
+                               return null;
+
+                       if (Arguments == null) {
+                               Expression c = Constantify (type);
+                               if (c != null)
+                                       return c;
+                       }
+
+                       type = texpr.Type;
                        if (type == null)
                                return null;
                        
                        CheckObsoleteAttribute (type);
 
-                       bool IsDelegate = TypeManager.IsDelegateType (type);
-                       
-                       if (IsDelegate){
+                       if (TypeManager.IsDelegateType (type)) {
                                RequestedType = (new NewDelegate (type, Arguments, loc)).Resolve (ec);
                                if (RequestedType != null)
-                                       if (!(RequestedType is NewDelegate))
+                                       if (!(RequestedType is DelegateCreation))
                                                throw new Exception ("NewDelegate.Resolve returned a non NewDelegate: " + RequestedType.GetType ());
                                return RequestedType;
                        }
 
                        if (type.IsGenericParameter) {
-                               if (!TypeManager.HasConstructorConstraint (type)) {
+                               GenericConstraints gc = TypeManager.GetTypeParameterConstraints (type);
+
+                               if ((gc == null) || (!gc.HasConstructorConstraint && !gc.IsValueType)) {
                                        Error (304, String.Format (
                                                       "Cannot create an instance of the " +
                                                       "variable type '{0}' because it " +
@@ -5961,11 +6227,20 @@ namespace Mono.CSharp {
                                is_type_parameter = true;
                                eclass = ExprClass.Value;
                                return this;
-                       } else if (type.IsInterface || type.IsAbstract){
-                               Error (144, "It is not possible to create instances of interfaces or abstract classes");
+                       }
+
+                       if (type.IsAbstract && type.IsSealed) {
+                               Report.SymbolRelatedToPreviousError (type);
+                               Report.Error (712, loc, "Cannot create an instance of the static class `{0}'", TypeManager.CSharpName (type));
                                return null;
                        }
-                       
+
+                       if (type.IsInterface || type.IsAbstract){
+                               Report.SymbolRelatedToPreviousError (type);
+                               Report.Error (144, loc, "Cannot create an instance of the abstract class or interface `{0}'", TypeManager.CSharpName (type));
+                               return null;
+                       }
+
                        bool is_struct = type.IsValueType;
                        eclass = ExprClass.Value;
 
@@ -5975,43 +6250,32 @@ namespace Mono.CSharp {
                        //
                        if (is_struct && Arguments == null)
                                return this;
-                       
-                       Expression ml;
-                       ml = MemberLookupFinal (ec, type, type, ".ctor",
-                                               // For member-lookup, treat 'new Foo (bar)' as call to 'foo.ctor (bar)', where 'foo' is of type 'Foo'.
-                                               MemberTypes.Constructor,
-                                               AllBindingFlags | BindingFlags.DeclaredOnly, loc);
+
+                       Expression ml = MemberLookupFinal (ec, type, type, ".ctor",
+                               MemberTypes.Constructor, AllBindingFlags | BindingFlags.DeclaredOnly, loc);
 
                        if (ml == null)
                                return null;
-                       
-                       if (! (ml is MethodGroupExpr)){
-                               if (!is_struct){
-                                       ml.Error_UnexpectedKind ("method group");
-                                       return null;
-                               }
+
+                       MethodGroupExpr mg = ml as MethodGroupExpr;
+
+                       if (mg == null) {
+                               ml.Error_UnexpectedKind (ec, "method group", loc);
+                               return null;
                        }
 
-                       if (ml != null) {
-                               if (Arguments != null){
-                                       foreach (Argument a in Arguments){
-                                               if (!a.Resolve (ec, loc))
-                                                       return null;
-                                       }
+                       if (Arguments != null){
+                               foreach (Argument a in Arguments){
+                                       if (!a.Resolve (ec, loc))
+                                               return null;
                                }
-
-                               method = Invocation.OverloadResolve (
-                                       ec, (MethodGroupExpr) ml, Arguments, false, loc);
-                               
                        }
 
-                       if (method == null) { 
-                                if (!is_struct || Arguments.Count > 0) {
-                                       Error (1501, String.Format (
-                                           "New invocation: Can not find a constructor in `{0}' for this argument list",
-                                           TypeManager.CSharpName (type)));
-                                       return null;
-                                }
+                       method = Invocation.OverloadResolve (ec, mg, Arguments, false, loc);
+                       if (method == null) {
+                               if (almostMatchedMembers.Count != 0)
+                                       MemberLookupFailed (ec, type, type, ".ctor", null, true, loc);
+                               return null;
                        }
 
                        return this;
@@ -6055,7 +6319,7 @@ namespace Mono.CSharp {
                //
                bool DoEmit (EmitContext ec, bool need_value_on_stack)
                {
-                       bool is_value_type = type.IsValueType;
+                       bool is_value_type = TypeManager.IsValueType (type);
                        ILGenerator ig = ec.ig;
 
                        if (is_value_type){
@@ -6072,7 +6336,7 @@ namespace Mono.CSharp {
                        }
 
                        if (method != null)
-                               Invocation.EmitArguments (ec, method, Arguments);
+                               Invocation.EmitArguments (ec, method, Arguments, false, null);
 
                        if (is_value_type){
                                if (method == null)
@@ -6128,7 +6392,7 @@ namespace Mono.CSharp {
                        IMemoryLocation ml = (IMemoryLocation) value_target;
                        ml.AddressOf (ec, AddressOp.Store);
                        if (method != null)
-                               Invocation.EmitArguments (ec, method, Arguments);
+                               Invocation.EmitArguments (ec, method, Arguments, false, null);
 
                        if (method == null)
                                ec.ig.Emit (OpCodes.Initobj, type);
@@ -6230,7 +6494,7 @@ namespace Mono.CSharp {
 
                void Error_IncorrectArrayInitializer ()
                {
-                       Error (178, "Incorrectly structured array initializer");
+                       Error (178, "Invalid rank specifier: expected `,' or `]'");
                }
                
                public bool CheckIndices (EmitContext ec, ArrayList probe, int idx, bool specified_dims)
@@ -6257,9 +6521,11 @@ namespace Mono.CSharp {
                        }
 
                        int child_bounds = -1;
-                       foreach (object o in probe) {
+                       for (int i = 0; i < probe.Count; ++i) {
+                               object o = probe [i];
                                if (o is ArrayList) {
-                                       int current_bounds = ((ArrayList) o).Count;
+                                       ArrayList sub_probe = o as ArrayList;
+                                       int current_bounds = sub_probe.Count;
                                        
                                        if (child_bounds == -1) 
                                                child_bounds = current_bounds;
@@ -6269,11 +6535,11 @@ namespace Mono.CSharp {
                                                return false;
                                        }
                                        if (specified_dims && (idx + 1 >= arguments.Count)){
-                                               Error (623, "Array initializers can only be used in a variable or field initializer, try using the new expression");
+                                               Error (623, "Array initializers can only be used in a variable or field initializer. Try using a new expression instead");
                                                return false;
                                        }
                                        
-                                       bool ret = CheckIndices (ec, (ArrayList) o, idx + 1, specified_dims);
+                                       bool ret = CheckIndices (ec, sub_probe, idx + 1, specified_dims);
                                        if (!ret)
                                                return false;
                                } else {
@@ -6284,8 +6550,9 @@ namespace Mono.CSharp {
                                        
                                        Expression tmp = (Expression) o;
                                        tmp = tmp.Resolve (ec);
+                                       probe [i] = tmp;
                                        if (tmp == null)
-                                               continue;
+                                               return false;
 
                                        // Console.WriteLine ("I got: " + tmp);
                                        // Handle initialization from vars, fields etc.
@@ -6380,58 +6647,6 @@ namespace Mono.CSharp {
                        }
                }
 
-               void Error_NegativeArrayIndex ()
-               {
-                       Error (284, "Can not create array with a negative size");
-               }
-               
-               //
-               // Converts `source' to an int, uint, long or ulong.
-               //
-               Expression ExpressionToArrayArgument (EmitContext ec, Expression source)
-               {
-                       Expression target;
-                       
-                       bool old_checked = ec.CheckState;
-                       ec.CheckState = true;
-                       
-                       target = Convert.ImplicitConversion (ec, source, TypeManager.int32_type, loc);
-                       if (target == null){
-                               target = Convert.ImplicitConversion (ec, source, TypeManager.uint32_type, loc);
-                               if (target == null){
-                                       target = Convert.ImplicitConversion (ec, source, TypeManager.int64_type, loc);
-                                       if (target == null){
-                                               target = Convert.ImplicitConversion (ec, source, TypeManager.uint64_type, loc);
-                                               if (target == null)
-                                                       Convert.Error_CannotImplicitConversion (loc, source.Type, TypeManager.int32_type);
-                                       }
-                               }
-                       } 
-                       ec.CheckState = old_checked;
-
-                       //
-                       // Only positive constants are allowed at compile time
-                       //
-                       if (target is Constant){
-                               if (target is IntConstant){
-                                       if (((IntConstant) target).Value < 0){
-                                               Error_NegativeArrayIndex ();
-                                               return null;
-                                       }
-                               }
-
-                               if (target is LongConstant){
-                                       if (((LongConstant) target).Value < 0){
-                                               Error_NegativeArrayIndex ();
-                                               return null;
-                                       }
-                               }
-                               
-                       }
-
-                       return target;
-               }
-
                //
                // Creates the type of the array
                //
@@ -6453,16 +6668,19 @@ namespace Mono.CSharp {
                        //
                        // Lookup the type
                        //
-                       Expression array_type_expr;
+                       TypeExpr array_type_expr;
                        array_type_expr = new ComposedCast (requested_base_type, array_qualifier.ToString (), loc);
-                       type = ec.DeclSpace.ResolveType (array_type_expr, false, loc);
-
-                       if (type == null)
+                       array_type_expr = array_type_expr.ResolveAsTypeTerminal (ec);
+                       if (array_type_expr == null)
                                return false;
 
-                       underlying_type = type;
-                       if (underlying_type.IsArray)
-                               underlying_type = TypeManager.GetElementType (underlying_type);
+                       type = array_type_expr.Type;
+
+                       if (!type.IsArray) {
+                               Error (622, "Can only use array initializer expressions to assign to array types. Try using a new expression instead.");
+                               return false;
+                       }
+                       underlying_type = TypeManager.GetElementType (type);
                        dimensions = type.GetArrayRank ();
 
                        return true;
@@ -6497,8 +6715,13 @@ namespace Mono.CSharp {
                                        a.Expr = real_arg;
                                }
                        }
-                       
-                       array_element_type = TypeManager.GetElementType (type);
+                       
+                       array_element_type = TypeManager.GetElementType (type);
+
+                       if (array_element_type.IsAbstract && array_element_type.IsSealed) {
+                               Report.Error (719, loc, "`{0}': array elements cannot be of static type", TypeManager.CSharpName (array_element_type));
+                               return null;
+                       }
 
                        if (arg_count == 1) {
                                is_one_dimensional = true;
@@ -6515,7 +6738,7 @@ namespace Mono.CSharp {
                                                   AllBindingFlags, loc);
                                
                                if (!(ml is MethodGroupExpr)) {
-                                       ml.Error_UnexpectedKind ("method group");
+                                       ml.Error_UnexpectedKind (ec, "method group", loc);
                                        return null;
                                }
                                
@@ -6783,7 +7006,7 @@ namespace Mono.CSharp {
                                        if (e is StringConstant || e is DecimalConstant || !(e is Constant) ||
                                            num_automatic_initializers <= max_automatic_initializers) {
                                                Type etype = e.Type;
-                                               
+
                                                ig.Emit (OpCodes.Dup);
 
                                                for (int idx = 0; idx < dims; idx++) 
@@ -6794,7 +7017,7 @@ namespace Mono.CSharp {
                                                // address of it, so we can store it.
                                                //
                                                if ((dims == 1) && 
-                                                   etype.IsSubclassOf (TypeManager.value_type) &&
+                                                   TypeManager.IsValueType (etype) &&
                                                    (!TypeManager.IsBuiltinOrEnum (etype) ||
                                                     etype == TypeManager.decimal_type)) {
                                                        if (e is New){
@@ -6812,12 +7035,20 @@ namespace Mono.CSharp {
 
                                                e.Emit (ec);
 
-                                                if (dims == 1)
-                                                        ArrayAccess.EmitStoreOpcode (ig, array_element_type);
-                                                else 
+                                               if (dims == 1) {
+                                                       bool is_stobj, has_type_arg;
+                                                       OpCode op = ArrayAccess.GetStoreOpcode (
+                                                               etype, out is_stobj,
+                                                               out has_type_arg);
+                                                       if (is_stobj)
+                                                               ig.Emit (OpCodes.Stobj, etype);
+                                                       else if (has_type_arg)
+                                                               ig.Emit (op, etype);
+                                                       else
+                                                               ig.Emit (op);
+                                               } else 
                                                         ig.Emit (OpCodes.Call, set);
-                                                
-                                        }
+                                       }
                                }
                                
                                //
@@ -6898,23 +7129,13 @@ namespace Mono.CSharp {
                                if (e is NullLiteral)
                                        v = null;
                                else {
-                                       if (!Attribute.GetAttributeArgumentExpression (e, Location, out v))
+                                       if (!Attribute.GetAttributeArgumentExpression (e, Location, array_element_type, out v))
                                                return null;
                                }
                                ret [i++] = v;
                        }
                        return ret;
                }
-
-               public Expression TurnIntoConstant ()
-               {
-                       //
-                       // Should use something like the above attribute thing.
-                       // It should return a subclass of Constant that just returns
-                       // the computed value of the array
-                       //
-                       throw new Exception ("Does not support yet Turning array into a Constant");
-               }
        }
        
        /// <summary>
@@ -6940,12 +7161,10 @@ namespace Mono.CSharp {
                        get { return variable_info; }
                }
 
-               public bool VerifyFixed (bool is_expression)
+               public bool VerifyFixed ()
                {
-                       if ((variable_info == null) || (variable_info.LocalInfo == null))
-                               return false;
-                       else
-                               return variable_info.LocalInfo.IsFixed;
+                       // Treat 'this' as a value parameter for the purpose of fixed variable determination.
+                       return true;
                }
 
                public bool ResolveBase (EmitContext ec)
@@ -6953,18 +7172,21 @@ namespace Mono.CSharp {
                        eclass = ExprClass.Variable;
 
                        if (ec.TypeContainer.CurrentType != null)
-                               type = ec.TypeContainer.CurrentType.ResolveType (ec);
+                               type = ec.TypeContainer.CurrentType;
                        else
                                type = ec.ContainerType;
 
                        if (ec.IsStatic) {
-                               Error (26, "Keyword this not valid in static code");
+                               Error (26, "Keyword `this' is not valid in a static property, static method, or static field initializer");
                                return false;
                        }
 
-                       if ((block != null) && (block.ThisVariable != null))
-                               variable_info = block.ThisVariable.VariableInfo;
+                       if (block != null && block.Toplevel.ThisVariable != null)
+                               variable_info = block.Toplevel.ThisVariable.VariableInfo;
 
+                       if (ec.CurrentAnonymousMethod != null)
+                               ec.CaptureThis ();
+                       
                        return true;
                }
 
@@ -6973,16 +7195,14 @@ namespace Mono.CSharp {
                        if (!ResolveBase (ec))
                                return null;
 
-                       if ((variable_info != null) && !variable_info.IsAssigned (ec)) {
-                               Error (188, "The this object cannot be used before all " +
-                                      "of its fields are assigned to");
+                       if ((variable_info != null) && !(type.IsValueType && ec.OmitStructFlowAnalysis) && !variable_info.IsAssigned (ec)) {
+                               Error (188, "The `this' object cannot be used before all of its fields are assigned to");
                                variable_info.SetAssigned (ec);
                                return this;
                        }
 
                        if (ec.IsFieldInitializer) {
-                               Error (27, "Keyword `this' can't be used outside a constructor, " +
-                                      "a method or a property.");
+                               Error (27, "Keyword `this' is not available in the current context");
                                return null;
                        }
 
@@ -6998,35 +7218,57 @@ namespace Mono.CSharp {
                                variable_info.SetAssigned (ec);
                        
                        if (ec.TypeContainer is Class){
-                               Error (1604, "Cannot assign to `this'");
+                               Error (1604, "Cannot assign to 'this' because it is read-only");
                                return null;
                        }
 
                        return this;
                }
 
-               public override void Emit (EmitContext ec)
+               public void Emit (EmitContext ec, bool leave_copy)
                {
-                       ILGenerator ig = ec.ig;
-
-                       ec.EmitThis ();
-                       if (ec.TypeContainer is Struct)
-                               ig.Emit (OpCodes.Ldobj, type);
+                       Emit (ec);
+                       if (leave_copy)
+                               ec.ig.Emit (OpCodes.Dup);
                }
-
-               public void EmitAssign (EmitContext ec, Expression source)
+               
+               public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
                {
                        ILGenerator ig = ec.ig;
                        
                        if (ec.TypeContainer is Struct){
                                ec.EmitThis ();
                                source.Emit (ec);
+                               if (leave_copy)
+                                       ec.ig.Emit (OpCodes.Dup);
                                ig.Emit (OpCodes.Stobj, type);
                        } else {
-                               source.Emit (ec);
-                               ig.Emit (OpCodes.Starg, 0);
+                               throw new Exception ("how did you get here");
                        }
                }
+               
+               public override void Emit (EmitContext ec)
+               {
+                       ILGenerator ig = ec.ig;
+
+                       ec.EmitThis ();
+                       if (ec.TypeContainer is Struct)
+                               ig.Emit (OpCodes.Ldobj, type);
+               }
+
+               public override int GetHashCode()
+               {
+                       return block.GetHashCode ();
+               }
+
+               public override bool Equals (object obj)
+               {
+                       This t = obj as This;
+                       if (t == null)
+                               return false;
+
+                       return block == t.block;
+               }
 
                public void AddressOf (EmitContext ec, AddressOp mode)
                {
@@ -7065,7 +7307,7 @@ namespace Mono.CSharp {
                        if (!ResolveBase (ec))
                                return null;
 
-                       if (ec.IsFieldInitializer || !ec.CurrentBlock.HasVarargs) {
+                       if (ec.IsFieldInitializer || !ec.CurrentBlock.Toplevel.HasVarargs) {
                                Error (190, "The __arglist construct is valid only within " +
                                       "a variable argument method.");
                                return null;
@@ -7149,7 +7391,7 @@ namespace Mono.CSharp {
        ///   Implements the typeof operator
        /// </summary>
        public class TypeOf : Expression {
-               public readonly Expression QueriedType;
+               public Expression QueriedType;
                protected Type typearg;
                
                public TypeOf (Expression queried_type, Location l)
@@ -7160,21 +7402,27 @@ namespace Mono.CSharp {
 
                public override Expression DoResolve (EmitContext ec)
                {
-                       typearg = ec.DeclSpace.ResolveType (QueriedType, false, loc);
-
-                       if (typearg == null)
+                       TypeExpr texpr = QueriedType.ResolveAsTypeTerminal (ec);
+                       if (texpr == null)
                                return null;
 
+                       typearg = texpr.Type;
+
                        if (typearg == TypeManager.void_type) {
-                               Error (673, "System.Void cannot be used from C# - " +
-                                      "use typeof (void) to get the void type object");
+                               Error (673, "System.Void cannot be used from C#. Use typeof (void) to get the void type object");
                                return null;
                        }
 
+                       if (typearg.IsPointer && !ec.InUnsafe){
+                               UnsafeError (loc);
+                               return null;
+                       }
                        CheckObsoleteAttribute (typearg);
 
                        type = TypeManager.type_type;
-                       eclass = ExprClass.Type;
+                       // Even though what is returned is a type object, it's treated as a value by the compiler.
+                       // In particular, 'typeof (Foo).X' is something totally different from 'Foo.X'.
+                       eclass = ExprClass.Value;
                        return this;
                }
 
@@ -7202,7 +7450,8 @@ namespace Mono.CSharp {
                {
                        type = TypeManager.type_type;
                        typearg = TypeManager.void_type;
-                       eclass = ExprClass.Type;
+                       // See description in TypeOf.
+                       eclass = ExprClass.Value;
                        return this;
                }
        }
@@ -7222,30 +7471,31 @@ namespace Mono.CSharp {
 
                public override Expression DoResolve (EmitContext ec)
                {
-                       if (!ec.InUnsafe) {
-                               Report.Error (
-                                       233, loc, "Sizeof may only be used in an unsafe context " +
-                                       "(consider using System.Runtime.InteropServices.Marshal.Sizeof");
-                               return null;
-                       }
-                               
-                       QueriedType = ec.DeclSpace.ResolveTypeExpr (QueriedType, false, loc);
-                       if (QueriedType == null || QueriedType.Type == null)
+                       TypeExpr texpr = QueriedType.ResolveAsTypeTerminal (ec);
+                       if (texpr == null)
                                return null;
 
-                       if (QueriedType is TypeParameterExpr){
-                               ((TypeParameterExpr)QueriedType).Error_CannotUseAsUnmanagedType (loc);
+                       if (texpr is TypeParameterExpr){
+                               ((TypeParameterExpr)texpr).Error_CannotUseAsUnmanagedType (loc);
                                return null;
                        }
 
-                       type_queried = QueriedType.Type;
-                       if (type_queried == null)
+                       type_queried = texpr.Type;
+
+                       int size_of = GetTypeSize (type_queried);
+                       if (size_of > 0) {
+                               return new IntConstant (size_of);
+                       }
+
+                       if (!ec.InUnsafe) {
+                               Report.Error (233, loc, "`{0}' does not have a predefined size, therefore sizeof can only be used in an unsafe context (consider using System.Runtime.InteropServices.Marshal.SizeOf)",
+                                        TypeManager.CSharpName (type_queried));
                                return null;
+                       }
 
                        CheckObsoleteAttribute (type_queried);
 
-                       if (!TypeManager.IsUnmanagedType (type_queried)){
-                               Report.Error (208, loc, "Cannot take the size of an unmanaged type (" + TypeManager.CSharpName (type_queried) + ")");
+                       if (!TypeManager.VerifyUnManaged (type_queried, loc)){
                                return null;
                        }
                        
@@ -7266,241 +7516,117 @@ namespace Mono.CSharp {
        }
 
        /// <summary>
-       ///   Implements the member access expression
+       ///   Implements the qualified-alias-member (::) expression.
        /// </summary>
-       public class MemberAccess : Expression {
-               public string Identifier;
-               protected Expression expr;
-               protected TypeArguments args;
-               
-               public MemberAccess (Expression expr, string id, Location l)
+       public class QualifiedAliasMember : Expression
+       {
+               string alias, identifier;
+
+               public QualifiedAliasMember (string alias, string identifier, Location l)
                {
-                       this.expr = expr;
-                       Identifier = id;
+                       this.alias = alias;
+                       this.identifier = identifier;
                        loc = l;
                }
 
-               public MemberAccess (Expression expr, string id, TypeArguments args,
-                                    Location l)
-                       : this (expr, id, l)
+               public override FullNamedExpression ResolveAsTypeStep (EmitContext ec, bool silent)
                {
-                       this.args = args;
-               }
+                       if (alias == "global")
+                               return new MemberAccess (Namespace.Root, identifier, loc).ResolveAsTypeStep (ec, silent);
 
-               public Expression Expr {
-                       get {
-                               return expr;
+                       int errors = Report.Errors;
+                       FullNamedExpression fne = ec.DeclSpace.NamespaceEntry.LookupAlias (alias);
+                       if (fne == null) {
+                               if (errors == Report.Errors)
+                                       Report.Error (432, loc, "Alias `{0}' not found", alias);
+                               return null;
                        }
+                       if (fne.eclass != ExprClass.Namespace) {
+                               if (!silent)
+                                       Report.Error (431, loc, "`{0}' cannot be used with '::' since it denotes a type", alias);
+                               return null;
+                       }
+                       return new MemberAccess (fne, identifier, loc).ResolveAsTypeStep (ec, silent);
                }
 
-               public static void error176 (Location loc, string name)
-               {
-                       Report.Error (176, loc, "Static member `" +
-                                     name + "' cannot be accessed " +
-                                     "with an instance reference, qualify with a " +
-                                     "type name instead");
-               }
-
-               public static bool IdenticalNameAndTypeName (EmitContext ec, Expression left_original, Expression left, Location loc)
-               {
-                       SimpleName sn = left_original as SimpleName;
-                       if (sn == null || left == null || left.Type.Name != sn.Name)
-                               return false;
-
-                       return RootContext.LookupType (ec.DeclSpace, sn.Name, true, loc) != null;
-               }
-               
-               public static Expression ResolveMemberAccess (EmitContext ec, Expression member_lookup,
-                                                             Expression left, Location loc,
-                                                             Expression left_original)
+               public override Expression DoResolve (EmitContext ec)
                {
-                       bool left_is_type, left_is_explicit;
-
-                       // If `left' is null, then we're called from SimpleNameResolve and this is
-                       // a member in the currently defining class.
-                       if (left == null) {
-                               left_is_type = ec.IsStatic || ec.IsFieldInitializer;
-                               left_is_explicit = false;
-
-                               // Implicitly default to `this' unless we're static.
-                               if (!ec.IsStatic && !ec.IsFieldInitializer && !ec.InEnumContext)
-                                       left = ec.GetThis (loc);
+                       FullNamedExpression fne;
+                       if (alias == "global") {
+                               fne = Namespace.Root;
                        } else {
-                               left_is_type = left is TypeExpr;
-                               left_is_explicit = true;
-                       }
-
-                       if (member_lookup is FieldExpr){
-                               FieldExpr fe = (FieldExpr) member_lookup;
-                               FieldInfo fi = fe.FieldInfo.Mono_GetGenericFieldDefinition ();
-                               Type decl_type = fi.DeclaringType;
-
-                               if (fi is FieldBuilder) {
-                                       Const c = TypeManager.LookupConstant ((FieldBuilder) fi);
-                                       
-                                       if (c != null) {
-                                               object o;
-                                               if (!c.LookupConstantValue (out o))
-                                                       return null;
-
-                                               object real_value = ((Constant) c.Expr).GetValue ();
-
-                                               return Constantify (real_value, fi.FieldType);
-                                       }
-                               }
-
-                               if (fi.IsLiteral) {
-                                       Type t = fi.FieldType;
-                                       
-                                       object o;
-
-                                       if (fi is FieldBuilder)
-                                               o = TypeManager.GetValue ((FieldBuilder) fi);
-                                       else
-                                               o = fi.GetValue (fi);
-                                       
-                                       if (decl_type.IsSubclassOf (TypeManager.enum_type)) {
-                                               if (left_is_explicit && !left_is_type &&
-                                                   !IdenticalNameAndTypeName (ec, left_original, member_lookup, loc)) {
-                                                       error176 (loc, fe.FieldInfo.Name);
-                                                       return null;
-                                               }                                       
-                                               
-                                               Expression enum_member = MemberLookup (
-                                                       ec, decl_type, "value__", MemberTypes.Field,
-                                                       AllBindingFlags, loc); 
-
-                                               Enum en = TypeManager.LookupEnum (decl_type);
-
-                                               Constant c;
-                                               if (en != null)
-                                                       c = Constantify (o, en.UnderlyingType);
-                                               else 
-                                                       c = Constantify (o, enum_member.Type);
-                                               
-                                               return new EnumConstant (c, decl_type);
-                                       }
-                                       
-                                       Expression exp = Constantify (o, t);
-
-                                       if (left_is_explicit && !left_is_type) {
-                                               error176 (loc, fe.FieldInfo.Name);
-                                               return null;
-                                       }
-                                       
-                                       return exp;
-                               }
-
-                               if (fi.FieldType.IsPointer && !ec.InUnsafe){
-                                       UnsafeError (loc);
+                               int errors = Report.Errors;
+                               fne = ec.DeclSpace.NamespaceEntry.LookupAlias (alias);
+                               if (fne == null) {
+                                       if (errors == Report.Errors)
+                                               Report.Error (432, loc, "Alias `{0}' not found", alias);
                                        return null;
                                }
                        }
 
-                       if (member_lookup is EventExpr) {
-                               EventExpr ee = (EventExpr) member_lookup;
-                               
-                               //
-                               // If the event is local to this class, we transform ourselves into
-                               // a FieldExpr
-                               //
-
-                               if (ee.EventInfo.DeclaringType == ec.ContainerType ||
-                                   TypeManager.IsNestedChildOf(ec.ContainerType, ee.EventInfo.DeclaringType)) {
-                                       MemberInfo mi = GetFieldFromEvent (ee);
-
-                                       if (mi == null) {
-                                               //
-                                               // If this happens, then we have an event with its own
-                                               // accessors and private field etc so there's no need
-                                               // to transform ourselves.
-                                               //
-                                               ee.InstanceExpression = left;
-                                               return ee;
-                                       }
-
-                                       Expression ml = ExprClassFromMemberInfo (ec, mi, loc);
-                                       
-                                       if (ml == null) {
-                                               Report.Error (-200, loc, "Internal error!!");
-                                               return null;
-                                       }
-
-                                       if (!left_is_explicit)
-                                               left = null;
-                                       
-                                       ee.InstanceExpression = left;
+                       Expression retval = new MemberAccess (fne, identifier, loc).DoResolve (ec);
+                       if (retval == null)
+                               return null;
 
-                                       return ResolveMemberAccess (ec, ml, left, loc, left_original);
-                               }
+                       if (!(retval is FullNamedExpression)) {
+                               Report.Error (687, loc, "The expression `{0}::{1}' did not resolve to a namespace or a type", alias, identifier);
+                               return null;
                        }
 
-                       if (member_lookup is IMemberExpr) {
-                               IMemberExpr me = (IMemberExpr) member_lookup;
-                               MethodGroupExpr mg = me as MethodGroupExpr;
-
-                               if (left_is_type){
-                                       if ((mg != null) && left_is_explicit && left.Type.IsInterface)
-                                               mg.IsExplicitImpl = left_is_explicit;
-
-                                       if (!me.IsStatic){
-                                               if ((ec.IsFieldInitializer || ec.IsStatic) &&
-                                                   IdenticalNameAndTypeName (ec, left_original, member_lookup, loc))
-                                                       return member_lookup;
-
-                                               SimpleName.Error_ObjectRefRequired (ec, loc, me.Name);
-                                               return null;
-                                       }
-
-                               } else {
-                                       if (!me.IsInstance){
-                                               if (IdenticalNameAndTypeName (ec, left_original, left, loc))
-                                                       return member_lookup;
-
-                                               if (left_is_explicit) {
-                                                       error176 (loc, me.Name);
-                                                       return null;
-                                               }
-                                       }
+                       // We defer this check till the end to match the behaviour of CSC
+                       if (fne.eclass != ExprClass.Namespace) {
+                               Report.Error (431, loc, "`{0}' cannot be used with '::' since it denotes a type", alias);
+                               return null;
+                       }
+                       return retval;
+               }
 
-                                       //
-                                       // Since we can not check for instance objects in SimpleName,
-                                       // becaue of the rule that allows types and variables to share
-                                       // the name (as long as they can be de-ambiguated later, see 
-                                       // IdenticalNameAndTypeName), we have to check whether left 
-                                       // is an instance variable in a static context
-                                       //
-                                       // However, if the left-hand value is explicitly given, then
-                                       // it is already our instance expression, so we aren't in
-                                       // static context.
-                                       //
+               public override void Emit (EmitContext ec)
+               {
+                       throw new InternalErrorException ("QualifiedAliasMember found in resolved tree");
+               }
 
-                                       if (ec.IsStatic && !left_is_explicit && left is IMemberExpr){
-                                               IMemberExpr mexp = (IMemberExpr) left;
 
-                                               if (!mexp.IsStatic){
-                                                       SimpleName.Error_ObjectRefRequired (ec, loc, mexp.Name);
-                                                       return null;
-                                               }
-                                       }
+               public override string ToString ()
+               {
+                       return alias + "::" + identifier;
+               }
 
-                                       if ((mg != null) && IdenticalNameAndTypeName (ec, left_original, left, loc))
-                                               mg.IdenticalTypeName = true;
+               public override string GetSignatureForError ()
+               {
+                       return ToString ();
+               }
+       }
 
-                                       me.InstanceExpression = left;
-                               }
+       /// <summary>
+       ///   Implements the member access expression
+       /// </summary>
+       public class MemberAccess : Expression {
+               public readonly string Identifier;  // TODO: LocatedToken
+               Expression expr;
+               TypeArguments args;
+               
+               public MemberAccess (Expression expr, string id, Location l)
+               {
+                       this.expr = expr;
+                       Identifier = id;
+                       loc = l;
+               }
 
-                               return member_lookup;
-                       }
+               public MemberAccess (Expression expr, string id, TypeArguments args,
+                                    Location l)
+                       : this (expr, id, l)
+               {
+                       this.args = args;
+               }
 
-                       Console.WriteLine ("Left is: " + left);
-                       Report.Error (-100, loc, "Support for [" + member_lookup + "] is not present yet");
-                       Environment.Exit (1);
-                       return null;
+               public Expression Expr {
+                       get { return expr; }
                }
-               
-               public virtual Expression DoResolve (EmitContext ec, Expression right_side,
-                                                    ResolveFlags flags)
+
+               // TODO: this method has very poor performace for Enum fields and
+               // probably for other constants as well
+               Expression DoResolve (EmitContext ec, Expression right_side)
                {
                        if (type != null)
                                throw new Exception ();
@@ -7512,117 +7638,75 @@ namespace Mono.CSharp {
                        // definite assignment check on the actual field and not on the whole struct.
                        //
 
-                       Expression original = expr;
-                       expr = expr.Resolve (ec, flags | ResolveFlags.Intermediate | ResolveFlags.DisableFlowAnalysis);
-                       if (expr == null)
-                               return null;
-
-                       if (expr is SimpleName){
-                               SimpleName child_expr = (SimpleName) expr;
+                       SimpleName original = expr as SimpleName;
+                       Expression new_expr = expr.Resolve (ec,
+                               ResolveFlags.VariableOrValue | ResolveFlags.Type |
+                               ResolveFlags.Intermediate | ResolveFlags.DisableStructFlowAnalysis);
 
-                               Expression new_expr = new SimpleName (child_expr.Name, Identifier, loc);
+                       if (new_expr == null)
+                               return null;
 
-                               return new_expr.Resolve (ec, flags);
+                       if (new_expr is Namespace) {
+                               Namespace ns = (Namespace) new_expr;
+                               string lookup_id = MemberName.MakeName (Identifier, args);
+                               FullNamedExpression retval = ns.Lookup (ec.DeclSpace, lookup_id, loc);
+                               if ((retval != null) && (args != null))
+                                       retval = new ConstructedType (retval, args, loc).ResolveAsTypeStep (ec);
+                               if (retval == null)
+                                       Report.Error (234, loc, "The type or namespace name `{0}' does not exist in the namespace `{1}'. Are you missing an assembly reference?",
+                                               Identifier, ns.FullName);
+                               return retval;
                        }
-                                       
-                       //
-                       // TODO: I mailed Ravi about this, and apparently we can get rid
-                       // of this and put it in the right place.
-                       // 
-                       // Handle enums here when they are in transit.
-                       // Note that we cannot afford to hit MemberLookup in this case because
-                       // it will fail to find any members at all
-                       //
-
-                       Type expr_type;
-                       if (expr is TypeExpr){
-                               expr_type = ((TypeExpr) expr).ResolveType (ec);
-
-                               if (!ec.DeclSpace.CheckAccessLevel (expr_type)){
-                                       Report.Error_T (122, loc, expr_type);
-                                       return null;
-                               }
-
-                               if (expr_type == TypeManager.enum_type || expr_type.IsSubclassOf (TypeManager.enum_type)){
-                                       Enum en = TypeManager.LookupEnum (expr_type);
 
-                                       if (en != null) {
-                                               object value = en.LookupEnumValue (ec, Identifier, loc);
-                                               
-                                               if (value != null){
-                                                       ObsoleteAttribute oa = en.GetObsoleteAttribute (ec, Identifier);
-                                                       if (oa != null) {
-                                                               AttributeTester.Report_ObsoleteMessage (oa, en.GetSignatureForError (), Location);
-                                                       }
-
-                                                       Constant c = Constantify (value, en.UnderlyingType);
-                                                       return new EnumConstant (c, expr_type);
-                                               }
-                                       } else {
-                                               CheckObsoleteAttribute (expr_type);
-
-                                               FieldInfo fi = expr_type.GetField (Identifier);
-                                               if (fi != null) {
-                                                       ObsoleteAttribute oa = AttributeTester.GetMemberObsoleteAttribute (fi);
-                                                       if (oa != null)
-                                                               AttributeTester.Report_ObsoleteMessage (oa, TypeManager.GetFullNameSignature (fi), Location);
-                                               }
-                                       }
-                               }
-                       } else
-                               expr_type = expr.Type;
-                       
+                       Type expr_type = new_expr.Type;
                        if (expr_type.IsPointer){
                                Error (23, "The `.' operator can not be applied to pointer operands (" +
                                       TypeManager.CSharpName (expr_type) + ")");
                                return null;
                        }
 
-                       int errors = Report.Errors;
-
                        Expression member_lookup;
                        member_lookup = MemberLookup (
                                ec, expr_type, expr_type, Identifier, loc);
                        if ((member_lookup == null) && (args != null)) {
-                               string lookup_id = Identifier + "!" + args.Count;
+                               string lookup_id = MemberName.MakeName (Identifier, args);
                                member_lookup = MemberLookup (
                                        ec, expr_type, expr_type, lookup_id, loc);
                        }
                        if (member_lookup == null) {
                                MemberLookupFailed (
-                                       ec, expr_type, expr_type, Identifier, null, loc);
+                                       ec, expr_type, expr_type, Identifier, null, true, loc);
                                return null;
                        }
 
                        if (member_lookup is TypeExpr) {
-                               if (!(expr is TypeExpr) && !(expr is SimpleName)) {
-                                       Error (572, "Can't reference type `" + Identifier + "' through an expression; try `" +
-                                              member_lookup.Type + "' instead");
+                               if (!(new_expr is TypeExpr) && 
+                                   (original == null || !original.IdenticalNameAndTypeName (ec, new_expr, loc))) {
+                                       Report.Error (572, loc, "`{0}': cannot reference a type through an expression; try `{1}' instead",
+                                               Identifier, member_lookup.GetSignatureForError ());
                                        return null;
                                }
 
-                               return member_lookup;
-                       }
-
-                       if (args != null) {
-                               string full_name = expr_type + "." + Identifier;
+                               ConstructedType ct = new_expr as ConstructedType;
+                               if (ct != null) {
+                                       //
+                                       // When looking up a nested type in a generic instance
+                                       // via reflection, we always get a generic type definition
+                                       // and not a generic instance - so we have to do this here.
+                                       //
+                                       // See gtest-172-lib.cs and gtest-172.cs for an example.
+                                       //
+                                       ct = new ConstructedType (
+                                               member_lookup.Type, ct.TypeArguments, loc);
 
-                               if (member_lookup is FieldExpr) {
-                                       Report.Error (307, loc, "The field `{0}' cannot " +
-                                                     "be used with type arguments", full_name);
-                                       return null;
-                               } else if (member_lookup is EventExpr) {
-                                       Report.Error (307, loc, "The event `{0}' cannot " +
-                                                     "be used with type arguments", full_name);
-                                       return null;
-                               } else if (member_lookup is PropertyExpr) {
-                                       Report.Error (307, loc, "The property `{0}' cannot " +
-                                                     "be used with type arguments", full_name);
-                                       return null;
+                                       return ct.ResolveAsTypeStep (ec);
                                }
+
+                               return member_lookup;
                        }
-                       
-                       member_lookup = ResolveMemberAccess (ec, member_lookup, expr, loc, original);
+
+                       MemberExpr me = (MemberExpr) member_lookup;
+                       member_lookup = me.ResolveMemberAccess (ec, new_expr, loc, original);
                        if (member_lookup == null)
                                return null;
 
@@ -7634,63 +7718,66 @@ namespace Mono.CSharp {
                                return mg.ResolveGeneric (ec, args);
                        }
 
+                       if (original != null && !TypeManager.IsValueType (expr_type)) {
+                               me = member_lookup as MemberExpr;
+                               if (me != null && me.IsInstance) {
+                                       LocalVariableReference var = new_expr as LocalVariableReference;
+                                       if (var != null && !var.VerifyAssigned (ec))
+                                               return null;
+                               }
+                       }
+
                        // The following DoResolve/DoResolveLValue will do the definite assignment
                        // check.
 
                        if (right_side != null)
-                               member_lookup = member_lookup.DoResolveLValue (ec, right_side);
+                               return member_lookup.DoResolveLValue (ec, right_side);
                        else
-                               member_lookup = member_lookup.DoResolve (ec);
-
-                       return member_lookup;
+                               return member_lookup.DoResolve (ec);
                }
 
                public override Expression DoResolve (EmitContext ec)
                {
-                       return DoResolve (ec, null, ResolveFlags.VariableOrValue |
-                                         ResolveFlags.SimpleName | ResolveFlags.Type);
+                       return DoResolve (ec, null);
                }
 
                public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
                {
-                       return DoResolve (ec, right_side, ResolveFlags.VariableOrValue |
-                                         ResolveFlags.SimpleName | ResolveFlags.Type);
+                       return DoResolve (ec, right_side);
                }
 
-               public override Expression ResolveAsTypeStep (EmitContext ec)
+               public override FullNamedExpression ResolveAsTypeStep (EmitContext ec, bool silent)
                {
-                       string fname = null;
-                       MemberAccess full_expr = this;
-                       while (full_expr != null) {
-                               if (fname != null)
-                                       fname = String.Concat (full_expr.Identifier, ".", fname);
-                               else
-                                       fname = full_expr.Identifier;
-
-                               if (full_expr.Expr is SimpleName) {
-                                       string full_name = String.Concat (((SimpleName) full_expr.Expr).Name, ".", fname);
-                                       Type fully_qualified = ec.DeclSpace.FindType (loc, full_name);
-                                       if (fully_qualified != null)
-                                               return new TypeExpression (fully_qualified, loc);
-                               }
-
-                               full_expr = full_expr.Expr as MemberAccess;
-                       }
+                       return ResolveNamespaceOrType (ec, silent);
+               }
 
-                       Expression new_expr = expr.ResolveAsTypeStep (ec);
+               public FullNamedExpression ResolveNamespaceOrType (EmitContext ec, bool silent)
+               {
+                       FullNamedExpression new_expr = expr.ResolveAsTypeStep (ec, silent);
 
-                       if (new_expr == null)
+                       if (new_expr == null) {
+                               Report.Error (234, "No such name or typespace {0}", expr);
                                return null;
+                       }
 
-                       if (new_expr is SimpleName){
-                               SimpleName child_expr = (SimpleName) new_expr;
-                               
-                               new_expr = new SimpleName (child_expr.Name, Identifier, loc);
+                       string lookup_id = MemberName.MakeName (Identifier, args);
 
-                               return new_expr.ResolveAsTypeStep (ec);
+                       if (new_expr is Namespace) {
+                               Namespace ns = (Namespace) new_expr;
+                               FullNamedExpression retval = ns.Lookup (ec.DeclSpace, lookup_id, loc);
+                               if ((retval != null) && (args != null))
+                                       retval = new ConstructedType (retval, args, loc).ResolveAsTypeStep (ec);
+                               if (!silent && retval == null)
+                                       Report.Error (234, loc, "The type or namespace name `{0}' does not exist in the namespace `{1}'. Are you missing an assembly reference?",
+                                               Identifier, ns.FullName);
+                               return retval;
                        }
 
-                       Type expr_type = ((TypeExpr) new_expr).ResolveType (ec);
+                       TypeExpr tnew_expr = new_expr.ResolveAsTypeTerminal (ec);
+                       if (tnew_expr == null)
+                               return null;
+
+                       Type expr_type = tnew_expr.Type;
 
                        if (expr_type.IsPointer){
                                Error (23, "The `.' operator can not be applied to pointer operands (" +
@@ -7698,25 +7785,30 @@ namespace Mono.CSharp {
                                return null;
                        }
 
-                       Expression member_lookup;
-                       string lookup_id;
-                       if (args != null)
-                               lookup_id = Identifier + "!" + args.Count;
-                       else
-                               lookup_id = Identifier;
-                       member_lookup = MemberLookupFinal (
-                               ec, expr_type, expr_type, lookup_id, loc);
-                       if (member_lookup == null)
+                       Expression member_lookup = MemberLookup (
+                               ec, ec.ContainerType, expr_type, expr_type, lookup_id,
+                               MemberTypes.NestedType, BindingFlags.Public | BindingFlags.NonPublic, loc);
+                       if (member_lookup == null) {
+                               int errors = Report.Errors;
+                               MemberLookupFailed (ec, expr_type, expr_type, lookup_id, null, false, loc);
+
+                               if (!silent && errors == Report.Errors) {
+                                       Report.Error (426, loc, "The nested type `{0}' does not exist in the type `{1}'",
+                                               Identifier, new_expr.GetSignatureForError ());
+                               }
                                return null;
+                       }
 
-                       TypeExpr texpr = member_lookup as TypeExpr;
-                       if (texpr == null)
+                       if (!(member_lookup is TypeExpr)) {
+                               new_expr.Error_UnexpectedKind (ec, "type", loc);
                                return null;
+                       }
 
-                       Type t = texpr.ResolveType (ec);
-                       if (t == null)
+                       TypeExpr texpr = member_lookup.ResolveAsTypeTerminal (ec);
+                       if (texpr == null)
                                return null;
 
+                       TypeArguments the_args = args;
                        if (TypeManager.HasGenericArguments (expr_type)) {
                                Type[] decl_args = TypeManager.GetTypeArguments (expr_type);
 
@@ -7727,11 +7819,11 @@ namespace Mono.CSharp {
                                if (args != null)
                                        new_args.Add (args);
 
-                               args = new_args;
+                               the_args = new_args;
                        }
 
-                       if (args != null) {
-                               ConstructedType ctype = new ConstructedType (targs, loc);
+                       if (the_args != null) {
+                               ConstructedType ctype = new ConstructedType (texpr.Type, the_args, loc);
                                return ctype.ResolveAsTypeStep (ec);
                        }
 
@@ -7745,10 +7837,12 @@ namespace Mono.CSharp {
 
                public override string ToString ()
                {
-                       if (args != null)
-                               return expr + "." + Identifier + "!" + args.Count;
-                       else
-                               return expr + "." + Identifier;
+                       return expr + "." + MemberName.MakeName (Identifier, args);
+               }
+
+               public override string GetSignatureForError ()
+               {
+                       return expr.GetSignatureForError () + "." + Identifier;
                }
        }
 
@@ -7860,11 +7954,11 @@ namespace Mono.CSharp {
                public ArrayList  Arguments;
                public Expression Expr;
                
-               public ElementAccess (Expression e, ArrayList e_list, Location l)
+               public ElementAccess (Expression e, ArrayList e_list)
                {
                        Expr = e;
 
-                       loc  = l;
+                       loc  = e.Location;
                        
                        if (e_list == null)
                                return;
@@ -7893,22 +7987,22 @@ namespace Mono.CSharp {
                        return true;
                }
 
-               Expression MakePointerAccess ()
+               Expression MakePointerAccess (EmitContext ec, Type t)
                {
-                       Type t = Expr.Type;
-
                        if (t == TypeManager.void_ptr_type){
-                               Error (242, "The array index operation is not valid for void pointers");
+                               Error (242, "The array index operation is not valid on void pointers");
                                return null;
                        }
                        if (Arguments.Count != 1){
-                               Error (196, "A pointer must be indexed by a single value");
+                               Error (196, "A pointer must be indexed by only one value");
                                return null;
                        }
                        Expression p;
 
-                       p = new PointerArithmetic (true, Expr, ((Argument)Arguments [0]).Expr, t, loc);
-                       return new Indirection (p, loc);
+                       p = new PointerArithmetic (true, Expr, ((Argument)Arguments [0]).Expr, t, loc).Resolve (ec);
+                       if (p == null)
+                               return null;
+                       return new Indirection (p, loc).Resolve (ec);
                }
                
                public override Expression DoResolve (EmitContext ec)
@@ -7925,16 +8019,23 @@ namespace Mono.CSharp {
                        Type t = Expr.Type;
 
                        if (t == TypeManager.array_type){
-                               Report.Error (21, loc, "Cannot use indexer on System.Array");
+                               Report.Error (21, loc, "Cannot apply indexing with [] to an expression of type `System.Array'");
                                return null;
                        }
                        
                        if (t.IsArray)
                                return (new ArrayAccess (this, loc)).Resolve (ec);
-                       else if (t.IsPointer)
-                               return MakePointerAccess ();
-                       else
-                               return (new IndexerAccess (this, loc)).Resolve (ec);
+                       if (t.IsPointer)
+                               return MakePointerAccess (ec, Expr.Type);
+
+                       FieldExpr fe = Expr as FieldExpr;
+                       if (fe != null) {
+                               IFixedBuffer ff = AttributeTester.GetFixedBuffer (fe.FieldInfo);
+                               if (ff != null) {
+                                       return MakePointerAccess (ec, ff.ElementType);
+                               }
+                       }
+                       return (new IndexerAccess (this, loc)).Resolve (ec);
                }
 
                public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
@@ -7944,11 +8045,29 @@ namespace Mono.CSharp {
 
                        Type t = Expr.Type;
                        if (t.IsArray)
-                               return (new ArrayAccess (this, loc)).ResolveLValue (ec, right_side);
-                       else if (t.IsPointer)
-                               return MakePointerAccess ();
-                       else
-                               return (new IndexerAccess (this, loc)).ResolveLValue (ec, right_side);
+                               return (new ArrayAccess (this, loc)).DoResolveLValue (ec, right_side);
+
+                       if (t.IsPointer)
+                               return MakePointerAccess (ec, Expr.Type);
+
+                       FieldExpr fe = Expr as FieldExpr;
+                       if (fe != null) {
+                               IFixedBuffer ff = AttributeTester.GetFixedBuffer (fe.FieldInfo);
+                               if (ff != null) {
+                                       if (!(fe.InstanceExpression is LocalVariableReference) && 
+                                               !(fe.InstanceExpression is This)) {
+                                               Report.Error (1708, loc, "Fixed size buffers can only be accessed through locals or fields");
+                                               return null;
+                                       }
+// TODO: not sure whether it is correct
+//                                     if (!ec.InFixedInitializer) {
+//                                             Error (1666, "You cannot use fixed sized buffers contained in unfixed expressions. Try using the fixed statement");
+//                                             return null;
+//                                     }
+                                       return MakePointerAccess (ec, ff.ElementType);
+                               }
+                       }
+                       return (new IndexerAccess (this, loc)).DoResolveLValue (ec, right_side);
                }
                
                public override void Emit (EmitContext ec)
@@ -7966,7 +8085,8 @@ namespace Mono.CSharp {
                //
                ElementAccess ea;
 
-               LocalTemporary [] cached_locations;
+               LocalTemporary temp;
+               bool prepared;
                
                public ArrayAccess (ElementAccess ea_data, Location l)
                {
@@ -7975,6 +8095,11 @@ namespace Mono.CSharp {
                        loc = l;
                }
 
+               public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
+               {
+                       return DoResolve (ec);
+               }
+
                public override Expression DoResolve (EmitContext ec)
                {
 #if false
@@ -7990,10 +8115,8 @@ namespace Mono.CSharp {
 
                        Type t = ea.Expr.Type;
                        if (t.GetArrayRank () != ea.Arguments.Count){
-                               ea.Error (22,
-                                         "Incorrect number of indexes for array " +
-                                         " expected: " + t.GetArrayRank () + " got: " +
-                                         ea.Arguments.Count);
+                               Report.Error (22, ea.Location, "Wrong number of indexes `{0}' inside [], expected `{1}'",
+                                         ea.Arguments.Count, t.GetArrayRank ());
                                return null;
                        }
 
@@ -8009,8 +8132,13 @@ namespace Mono.CSharp {
                                if (argtype == TypeManager.int32_type ||
                                    argtype == TypeManager.uint32_type ||
                                    argtype == TypeManager.int64_type ||
-                                   argtype == TypeManager.uint64_type)
+                                   argtype == TypeManager.uint64_type) {
+                                       Constant c = a.Expr as Constant;
+                                       if (c != null && c.IsNegative) {
+                                               Report.Warning (251, 2, ea.Location, "Indexing an array with a negative index (array indices always start at zero)");
+                                       }
                                        continue;
+                               }
 
                                //
                                // Mhm.  This is strage, because the Argument.Type is not the same as
@@ -8063,24 +8191,12 @@ namespace Mono.CSharp {
                                ig.Emit (OpCodes.Ldobj, type);
                        } else if (type.IsGenericParameter)
                                ig.Emit (OpCodes.Ldelem_Any, type);
+                       else if (type.IsPointer)
+                               ig.Emit (OpCodes.Ldelem_I);
                        else
                                ig.Emit (OpCodes.Ldelem_Ref);
                }
 
-               /// <summary>
-               ///    Emits the right opcode to store an object of Type `t'
-               ///    from an array of T.  
-               /// </summary>
-               static public void EmitStoreOpcode (ILGenerator ig, Type t)
-               {
-                       bool is_stobj, has_type_arg;
-                       OpCode op = GetStoreOpcode (t, out is_stobj, out has_type_arg);
-                       if (has_type_arg)
-                               ig.Emit (op, t);
-                       else
-                               ig.Emit (op);
-               }
-
                /// <summary>
                ///    Returns the right opcode to store an object of Type `t'
                ///    from an array of T.  
@@ -8090,7 +8206,7 @@ namespace Mono.CSharp {
                        //Console.WriteLine (new System.Diagnostics.StackTrace ());
                        has_type_arg = false; is_stobj = false;
                        t = TypeManager.TypeToCoreType (t);
-                       if (TypeManager.IsEnumType (t) && t != TypeManager.enum_type)
+                       if (TypeManager.IsEnumType (t))
                                t = TypeManager.EnumToUnderlying (t);
                        if (t == TypeManager.byte_type || t == TypeManager.sbyte_type ||
                            t == TypeManager.bool_type)
@@ -8117,7 +8233,9 @@ namespace Mono.CSharp {
                        } else if (t.IsGenericParameter) {
                                has_type_arg = true;
                                return OpCodes.Stelem_Any;
-                       } else
+                       } else if (t.IsPointer)
+                               return OpCodes.Stelem_I;
+                       else
                                return OpCodes.Stelem_Ref;
                }
 
@@ -8177,101 +8295,114 @@ namespace Mono.CSharp {
                {
                        ILGenerator ig = ec.ig;
                        
-                       if (cached_locations == null){
-                               ea.Expr.Emit (ec);
-                               foreach (Argument a in ea.Arguments){
-                                       Type argtype = a.Expr.Type;
-                                       
-                                       a.Expr.Emit (ec);
-                                       
-                                       if (argtype == TypeManager.int64_type)
-                                               ig.Emit (OpCodes.Conv_Ovf_I);
-                                       else if (argtype == TypeManager.uint64_type)
-                                               ig.Emit (OpCodes.Conv_Ovf_I_Un);
-                               }
-                               return;
-                       }
-
-                       if (cached_locations [0] == null){
-                               cached_locations [0] = new LocalTemporary (ec, ea.Expr.Type);
-                               ea.Expr.Emit (ec);
-                               ig.Emit (OpCodes.Dup);
-                               cached_locations [0].Store (ec);
+                       ea.Expr.Emit (ec);
+                       foreach (Argument a in ea.Arguments){
+                               Type argtype = a.Expr.Type;
                                
-                               int j = 1;
+                               a.Expr.Emit (ec);
                                
-                               foreach (Argument a in ea.Arguments){
-                                       Type argtype = a.Expr.Type;
-                                       
-                                       cached_locations [j] = new LocalTemporary (ec, TypeManager.intptr_type /* a.Expr.Type */);
-                                       a.Expr.Emit (ec);
-                                       if (argtype == TypeManager.int64_type)
-                                               ig.Emit (OpCodes.Conv_Ovf_I);
-                                       else if (argtype == TypeManager.uint64_type)
-                                               ig.Emit (OpCodes.Conv_Ovf_I_Un);
-
-                                       ig.Emit (OpCodes.Dup);
-                                       cached_locations [j].Store (ec);
-                                       j++;
-                               }
-                               return;
+                               if (argtype == TypeManager.int64_type)
+                                       ig.Emit (OpCodes.Conv_Ovf_I);
+                               else if (argtype == TypeManager.uint64_type)
+                                       ig.Emit (OpCodes.Conv_Ovf_I_Un);
                        }
-
-                       foreach (LocalTemporary lt in cached_locations)
-                               lt.Emit (ec);
                }
 
-               public new void CacheTemporaries (EmitContext ec)
-               {
-                       cached_locations = new LocalTemporary [ea.Arguments.Count + 1];
-               }
-               
-               public override void Emit (EmitContext ec)
+               public void Emit (EmitContext ec, bool leave_copy)
                {
                        int rank = ea.Expr.Type.GetArrayRank ();
                        ILGenerator ig = ec.ig;
 
-                       LoadArrayAndArguments (ec);
-                       
-                       if (rank == 1)
-                               EmitLoadOpcode (ig, type);
-                       else {
-                               MethodInfo method;
+                       if (!prepared) {
+                               LoadArrayAndArguments (ec);
                                
-                               method = FetchGetMethod ();
-                               ig.Emit (OpCodes.Call, method);
+                               if (rank == 1)
+                                       EmitLoadOpcode (ig, type);
+                               else {
+                                       MethodInfo method;
+                                       
+                                       method = FetchGetMethod ();
+                                       ig.Emit (OpCodes.Call, method);
+                               }
+                       } else
+                               LoadFromPtr (ec.ig, this.type);
+                       
+                       if (leave_copy) {
+                               ec.ig.Emit (OpCodes.Dup);
+                               temp = new LocalTemporary (ec, this.type);
+                               temp.Store (ec);
                        }
                }
+               
+               public override void Emit (EmitContext ec)
+               {
+                       Emit (ec, false);
+               }
 
-               public void EmitAssign (EmitContext ec, Expression source)
+               public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
                {
                        int rank = ea.Expr.Type.GetArrayRank ();
                        ILGenerator ig = ec.ig;
                        Type t = source.Type;
+                       prepared = prepare_for_load;
 
-                       LoadArrayAndArguments (ec);
-
-                       //
-                       // The stobj opcode used by value types will need
-                       // an address on the stack, not really an array/array
-                       // pair
-                       //
-                       if (rank == 1){
-                               if (t == TypeManager.enum_type || t == TypeManager.decimal_type ||
-                                   (t.IsSubclassOf (TypeManager.value_type) && !TypeManager.IsEnumType (t) && !TypeManager.IsBuiltinType (t)))
-                                       ig.Emit (OpCodes.Ldelema, t);
+                       if (prepare_for_load) {
+                               AddressOf (ec, AddressOp.LoadStore);
+                               ec.ig.Emit (OpCodes.Dup);
+                               source.Emit (ec);
+                               if (leave_copy) {
+                                       ec.ig.Emit (OpCodes.Dup);
+                                       temp = new LocalTemporary (ec, this.type);
+                                       temp.Store (ec);
+                               }
+                               StoreFromPtr (ec.ig, t);
+                               
+                               if (temp != null)
+                                       temp.Emit (ec);
+                               
+                               return;
                        }
                        
-                       source.Emit (ec);
+                       LoadArrayAndArguments (ec);
 
-                       if (rank == 1)
-                               EmitStoreOpcode (ig, t);
-                       else {
+                       if (rank == 1) {
+                               bool is_stobj, has_type_arg;
+                               OpCode op = GetStoreOpcode (t, out is_stobj, out has_type_arg);
+
+                               //
+                               // The stobj opcode used by value types will need
+                               // an address on the stack, not really an array/array
+                               // pair
+                               //
+                               if (is_stobj)
+                                       ig.Emit (OpCodes.Ldelema, t);
+                               
+                               source.Emit (ec);
+                               if (leave_copy) {
+                                       ec.ig.Emit (OpCodes.Dup);
+                                       temp = new LocalTemporary (ec, this.type);
+                                       temp.Store (ec);
+                               }
+                               
+                               if (is_stobj)
+                                       ig.Emit (OpCodes.Stobj, t);
+                               else if (has_type_arg)
+                                       ig.Emit (op, t);
+                               else
+                                       ig.Emit (op);
+                       } else {
                                ModuleBuilder mb = CodeGen.Module.Builder;
                                int arg_count = ea.Arguments.Count;
                                Type [] args = new Type [arg_count + 1];
                                MethodInfo set;
                                
+                               source.Emit (ec);
+                               if (leave_copy) {
+                                       ec.ig.Emit (OpCodes.Dup);
+                                       temp = new LocalTemporary (ec, this.type);
+                                       temp.Store (ec);
+                               }
+                               
                                for (int i = 0; i < arg_count; i++){
                                        //args [i++] = a.Type;
                                        args [i] = TypeManager.int32_type;
@@ -8287,6 +8418,9 @@ namespace Mono.CSharp {
                                
                                ig.Emit (OpCodes.Call, set);
                        }
+                       
+                       if (temp != null)
+                               temp.Emit (ec);
                }
 
                public void AddressOf (EmitContext ec, AddressOp mode)
@@ -8303,20 +8437,35 @@ namespace Mono.CSharp {
                                ig.Emit (OpCodes.Call, address);
                        }
                }
-       }
 
+               public void EmitGetLength (EmitContext ec, int dim)
+               {
+                       int rank = ea.Expr.Type.GetArrayRank ();
+                       ILGenerator ig = ec.ig;
+
+                       ea.Expr.Emit (ec);
+                       if (rank == 1) {
+                               ig.Emit (OpCodes.Ldlen);
+                               ig.Emit (OpCodes.Conv_I4);
+                       } else {
+                               IntLiteral.EmitInt (ig, dim);
+                               ig.Emit (OpCodes.Callvirt, TypeManager.int_getlength_int);
+                       }
+               }
+       }
        
        class Indexers {
-               public ArrayList Properties;
-               static Hashtable map;
+               // note that the ArrayList itself in mutable.  We just can't assign to 'Properties' again.
+               public readonly ArrayList Properties;
+               static Indexers empty;
 
                public struct Indexer {
-                       public readonly Type Type;
+                       public readonly PropertyInfo PropertyInfo;
                        public readonly MethodInfo Getter, Setter;
 
-                       public Indexer (Type type, MethodInfo get, MethodInfo set)
+                       public Indexer (PropertyInfo property_info, MethodInfo get, MethodInfo set)
                        {
-                               this.Type = type;
+                               this.PropertyInfo = property_info;
                                this.Getter = get;
                                this.Setter = set;
                        }
@@ -8324,22 +8473,33 @@ namespace Mono.CSharp {
 
                static Indexers ()
                {
-                       map = new Hashtable ();
+                       empty = new Indexers (null);
                }
 
-               Indexers ()
+               Indexers (ArrayList array)
                {
-                       Properties = new ArrayList ();
+                       Properties = array;
                }
-                               
-               void Append (MemberInfo [] mi)
+
+               static void Append (ref Indexers ix, Type caller_type, MemberInfo [] mi)
                {
+                       bool dummy;
+                       if (mi == null)
+                               return;
                        foreach (PropertyInfo property in mi){
                                MethodInfo get, set;
                                
                                get = property.GetGetMethod (true);
                                set = property.GetSetMethod (true);
-                               Properties.Add (new Indexer (property.PropertyType, get, set));
+                               if (get != null && !Expression.IsAccessorAccessible (caller_type, get, out dummy))
+                                       get = null;
+                               if (set != null && !Expression.IsAccessorAccessible (caller_type, set, out dummy))
+                                       set = null;
+                               if (get != null || set != null) {
+                                       if (ix == empty)
+                                               ix = new Indexers (new ArrayList ());
+                                       ix.Properties.Add (new Indexer (property, get, set));
+                               }
                        }
                }
 
@@ -8347,52 +8507,27 @@ namespace Mono.CSharp {
                {
                        string p_name = TypeManager.IndexerPropertyName (lookup_type);
 
-                       MemberInfo [] mi = TypeManager.MemberLookup (
+                       return TypeManager.MemberLookup (
                                caller_type, caller_type, lookup_type, MemberTypes.Property,
                                BindingFlags.Public | BindingFlags.Instance |
                                BindingFlags.DeclaredOnly, p_name, null);
-
-                       if (mi == null || mi.Length == 0)
-                               return null;
-
-                       return mi;
                }
                
                static public Indexers GetIndexersForType (Type caller_type, Type lookup_type, Location loc) 
                {
-                       Indexers ix = (Indexers) map [lookup_type];
-
-                       if (ix != null)
-                               return ix;
+                       Indexers ix = empty;
 
                        Type copy = lookup_type;
                        while (copy != TypeManager.object_type && copy != null){
-                               MemberInfo [] mi = GetIndexersForTypeOrInterface (caller_type, copy);
-
-                               if (mi != null){
-                                       if (ix == null)
-                                               ix = new Indexers ();
-
-                                       ix.Append (mi);
-                               }
-                                       
+                               Append (ref ix, caller_type, GetIndexersForTypeOrInterface (caller_type, copy));
                                copy = copy.BaseType;
                        }
 
-                       if (!lookup_type.IsInterface)
-                               return ix;
-
-                       TypeExpr [] ifaces = TypeManager.GetInterfaces (lookup_type);
-                       if (ifaces != null) {
-                               foreach (TypeExpr iface in ifaces) {
-                                       Type itype = iface.Type;
-                                       MemberInfo [] mi = GetIndexersForTypeOrInterface (caller_type, itype);
-                                       if (mi != null){
-                                               if (ix == null)
-                                                       ix = new Indexers ();
-                                       
-                                               ix.Append (mi);
-                                       }
+                       if (lookup_type.IsInterface) {
+                               Type [] ifaces = TypeManager.GetInterfaces (lookup_type);
+                               if (ifaces != null) {
+                                       foreach (Type itype in ifaces)
+                                               Append (ref ix, caller_type, GetIndexersForTypeOrInterface (caller_type, itype));
                                }
                        }
 
@@ -8454,15 +8589,12 @@ namespace Mono.CSharp {
                        bool found_any = false, found_any_getters = false;
                        Type lookup_type = indexer_type;
 
-                       Indexers ilist;
-                       ilist = Indexers.GetIndexersForType (current_type, lookup_type, loc);
-                       if (ilist != null) {
+                       Indexers ilist = Indexers.GetIndexersForType (current_type, lookup_type, loc);
+                       if (ilist.Properties != null) {
                                found_any = true;
-                               if (ilist.Properties != null) {
-                                       foreach (Indexers.Indexer ix in ilist.Properties) {
-                                               if (ix.Getter != null)
-                                                       AllGetters.Add(ix.Getter);
-                                       }
+                               foreach (Indexers.Indexer ix in ilist.Properties) {
+                                       if (ix.Getter != null)
+                                               AllGetters.Add (ix.Getter);
                                }
                        }
 
@@ -8474,21 +8606,19 @@ namespace Mono.CSharp {
                        }
 
                        if (!found_any) {
-                               Report.Error (21, loc,
-                                             "Type `" + TypeManager.CSharpName (indexer_type) +
-                                             "' does not have any indexers defined");
+                               Report.Error (21, loc, "Cannot apply indexing with [] to an expression of type `{0}'",
+                                             TypeManager.CSharpName (indexer_type));
                                return null;
                        }
 
                        if (!found_any_getters) {
-                               Error (154, "indexer can not be used in this context, because " +
-                                      "it lacks a `get' accessor");
+                               Report.Error (154, loc, "The property or indexer `{0}' cannot be used in this context because it lacks the `get' accessor",
+                                             "XXXXXXXX");
                                return null;
                        }
 
                        if (get == null) {
-                               Error (1501, "No Overload for method `this' takes `" +
-                                      arguments.Count + "' arguments");
+                               Invocation.Error_WrongNumArguments (loc, "this", arguments.Count);
                                return null;
                        }
 
@@ -8496,7 +8626,7 @@ namespace Mono.CSharp {
                        // Only base will allow this invocation to happen.
                        //
                        if (get.IsAbstract && this is BaseIndexerAccess){
-                               Report.Error (205, loc, "Cannot call an abstract base indexer: " + Invocation.FullMethodDesc (get));
+                               Error_CannotCallAbstractBase (TypeManager.CSharpSignature (get));
                                return null;
                        }
 
@@ -8505,6 +8635,8 @@ namespace Mono.CSharp {
                                UnsafeError (loc);
                                return null;
                        }
+
+                       instance_expr.CheckMarshallByRefAccess (ec.ContainerType);
                        
                        eclass = ExprClass.IndexerAccess;
                        return this;
@@ -8519,13 +8651,11 @@ namespace Mono.CSharp {
                        bool found_any = false, found_any_setters = false;
 
                        Indexers ilist = Indexers.GetIndexersForType (current_type, indexer_type, loc);
-                       if (ilist != null) {
+                       if (ilist.Properties != null) {
                                found_any = true;
-                               if (ilist.Properties != null) {
-                                       foreach (Indexers.Indexer ix in ilist.Properties) {
-                                               if (ix.Setter != null)
-                                                       AllSetters.Add(ix.Setter);
-                                       }
+                               foreach (Indexers.Indexer ix in ilist.Properties) {
+                                       if (ix.Setter != null)
+                                               AllSetters.Add (ix.Setter);
                                }
                        }
                        if (AllSetters.Count > 0) {
@@ -8538,9 +8668,8 @@ namespace Mono.CSharp {
                        }
 
                        if (!found_any) {
-                               Report.Error (21, loc,
-                                             "Type `" + TypeManager.CSharpName (indexer_type) +
-                                             "' does not have any indexers defined");
+                               Report.Error (21, loc, "Cannot apply indexing with [] to an expression of type `{0}'",
+                                             TypeManager.CSharpName (indexer_type));
                                return null;
                        }
 
@@ -8551,8 +8680,7 @@ namespace Mono.CSharp {
                        }
 
                        if (set == null) {
-                               Error (1501, "No Overload for method `this' takes `" +
-                                      arguments.Count + "' arguments");
+                               Invocation.Error_WrongNumArguments (loc, "this", arguments.Count);
                                return null;
                        }
 
@@ -8560,7 +8688,7 @@ namespace Mono.CSharp {
                        // Only base will allow this invocation to happen.
                        //
                        if (set.IsAbstract && this is BaseIndexerAccess){
-                               Report.Error (205, loc, "Cannot call an abstract base indexer: " + Invocation.FullMethodDesc (set));
+                               Error_CannotCallAbstractBase (TypeManager.CSharpSignature (set));
                                return null;
                        }
 
@@ -8570,28 +8698,64 @@ namespace Mono.CSharp {
                        type = TypeManager.void_type;   // default value
                        foreach (Indexers.Indexer ix in ilist.Properties){
                                if (ix.Setter == set){
-                                       type = ix.Type;
+                                       type = ix.PropertyInfo.PropertyType;
                                        break;
                                }
                        }
-                       
+
+                       instance_expr.CheckMarshallByRefAccess (ec.ContainerType);
+
                        eclass = ExprClass.IndexerAccess;
                        return this;
                }
                
-               public override void Emit (EmitContext ec)
+               bool prepared = false;
+               LocalTemporary temp;
+               
+               public void Emit (EmitContext ec, bool leave_copy)
                {
-                       Invocation.EmitCall (ec, is_base_indexer, false, instance_expr, get, arguments, loc);
+                       Invocation.EmitCall (ec, is_base_indexer, false, instance_expr, get, arguments, loc, prepared, false);
+                       if (leave_copy) {
+                               ec.ig.Emit (OpCodes.Dup);
+                               temp = new LocalTemporary (ec, Type);
+                               temp.Store (ec);
+                       }
                }
-
+               
                //
                // source is ignored, because we already have a copy of it from the
                // LValue resolution and we have already constructed a pre-cached
                // version of the arguments (ea.set_arguments);
                //
-               public void EmitAssign (EmitContext ec, Expression source)
+               public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
+               {
+                       prepared = prepare_for_load;
+                       Argument a = (Argument) set_arguments [set_arguments.Count - 1];
+                       
+                       if (prepared) {
+                               source.Emit (ec);
+                               if (leave_copy) {
+                                       ec.ig.Emit (OpCodes.Dup);
+                                       temp = new LocalTemporary (ec, Type);
+                                       temp.Store (ec);
+                               }
+                       } else if (leave_copy) {
+                               temp = new LocalTemporary (ec, Type);
+                               source.Emit (ec);
+                               temp.Store (ec);
+                               a.Expr = temp;
+                       }
+                       
+                       Invocation.EmitCall (ec, is_base_indexer, false, instance_expr, set, set_arguments, loc, false, prepared);
+                       
+                       if (temp != null)
+                               temp.Emit (ec);
+               }
+               
+               
+               public override void Emit (EmitContext ec)
                {
-                       Invocation.EmitCall (ec, is_base_indexer, false, instance_expr, set, set_arguments, loc);
+                       Emit (ec, false);
                }
        }
 
@@ -8643,15 +8807,14 @@ namespace Mono.CSharp {
                        Expression member_lookup;
                        Type current_type = ec.ContainerType;
                        Type base_type = current_type.BaseType;
-                       Expression e;
 
                        if (ec.IsStatic){
-                               Error (1511, "Keyword base is not allowed in static method");
+                               Error (1511, "Keyword `base' is not available in a static method");
                                return null;
                        }
 
                        if (ec.IsFieldInitializer){
-                               Error (1512, "Keyword base is not available in the current context");
+                               Error (1512, "Keyword `base' is not available in the current context");
                                return null;
                        }
                        
@@ -8659,8 +8822,7 @@ namespace Mono.CSharp {
                                                      member, AllMemberTypes, AllBindingFlags,
                                                      loc);
                        if (member_lookup == null) {
-                               MemberLookupFailed (
-                                       ec, base_type, base_type, member, null, loc);
+                               MemberLookupFailed (ec, base_type, base_type, member, null, true, loc);
                                return null;
                        }
 
@@ -8670,15 +8832,20 @@ namespace Mono.CSharp {
                                left = new TypeExpression (base_type, loc);
                        else
                                left = ec.GetThis (loc);
+
+                       MemberExpr me = (MemberExpr) member_lookup;
                        
-                       e = MemberAccess.ResolveMemberAccess (ec, member_lookup, left, loc, null);
+                       Expression e = me.ResolveMemberAccess (ec, left, loc, null);
 
-                       if (e is PropertyExpr){
+                       if (e is PropertyExpr) {
                                PropertyExpr pe = (PropertyExpr) e;
 
                                pe.IsBase = true;
                        }
 
+                       if (e is MethodGroupExpr)
+                               ((MethodGroupExpr) e).IsBase = true;
+
                        return e;
                }
 
@@ -8727,6 +8894,26 @@ namespace Mono.CSharp {
        ///   is needed (the `New' class).
        /// </summary>
        public class EmptyExpression : Expression {
+               public static readonly EmptyExpression Null = new EmptyExpression ();
+
+               static EmptyExpression temp = new EmptyExpression ();
+               public static EmptyExpression Grab ()
+               {
+                       if (temp == null)
+                               throw new InternalErrorException ("Nested Grab");
+                       EmptyExpression retval = temp;
+                       temp = null;
+                       return retval;
+               }
+
+               public static void Release (EmptyExpression e)
+               {
+                       if (temp != null)
+                               throw new InternalErrorException ("Already released");
+                       temp = e;
+               }
+
+               // TODO: should be protected
                public EmptyExpression ()
                {
                        type = TypeManager.object_type;
@@ -8775,6 +8962,12 @@ namespace Mono.CSharp {
                        loc = l;
                }
 
+               public Expression Source {
+                       get {
+                               return source;
+                       }
+               }
+                       
                public override Expression DoResolve (EmitContext ec)
                {
                        //
@@ -8807,6 +9000,11 @@ namespace Mono.CSharp {
                Expression left;
                string dim;
                
+               public ComposedCast (Expression left, string dim)
+                       : this (left, dim, left.Location)
+               {
+               }
+
                public ComposedCast (Expression left, string dim, Location l)
                {
                        this.left = left;
@@ -8814,81 +9012,60 @@ namespace Mono.CSharp {
                        loc = l;
                }
 
-               public override TypeExpr DoResolveAsTypeStep (EmitContext ec)
+               public Expression RemoveNullable ()
+               {
+                       if (dim.EndsWith ("?")) {
+                               dim = dim.Substring (0, dim.Length - 1);
+                               if (dim == "")
+                                       return left;
+                       }
+
+                       return this;
+               }
+
+               protected override TypeExpr DoResolveAsTypeStep (EmitContext ec)
                {
-                       Type ltype = ec.DeclSpace.ResolveType (left, false, loc);
-                       if (ltype == null)
+                       TypeExpr lexpr = left.ResolveAsTypeTerminal (ec);
+                       if (lexpr == null)
                                return null;
 
+                       Type ltype = lexpr.Type;
+
                        if ((ltype == TypeManager.void_type) && (dim != "*")) {
                                Report.Error (1547, Location,
                                              "Keyword 'void' cannot be used in this context");
                                return null;
                        }
 
-                       int pos = 0;
-                       while ((pos < dim.Length) && (dim [pos] == '[')) {
-                               pos++;
-
-                               if (dim [pos] == ']') {
-                                       ltype = ltype.MakeArrayType ();
-                                       pos++;
-
-                                       if (pos < dim.Length)
-                                               continue;
-
-                                       type = ltype;
-                                       eclass = ExprClass.Type;
-                                       return this;
-                               }
-
-                               int rank = 0;
-                               while (dim [pos] == ',') {
-                                       pos++; rank++;
-                               }
-
-                               if ((dim [pos] != ']') || (pos != dim.Length-1))
-                                       return null;
-                                               
-                               type = ltype.MakeArrayType (rank + 1);
-                               eclass = ExprClass.Type;
-                               return this;
+                       if ((dim.Length > 0) && (dim [0] == '?')) {
+                               TypeExpr nullable = new NullableType (left, loc);
+                               if (dim.Length > 1)
+                                       nullable = new ComposedCast (nullable, dim.Substring (1), loc);
+                               return nullable.ResolveAsTypeTerminal (ec);
                        }
 
-                       //
-                       // ltype.Fullname is already fully qualified, so we can skip
-                       // a lot of probes, and go directly to TypeManager.LookupType
-                       //
-                       string fname = ltype.FullName != null ? ltype.FullName : ltype.Name;
-                       string cname = fname + dim;
-                       type = TypeManager.LookupTypeDirect (cname);
-                       if (type == null){
-                               //
-                               // For arrays of enumerations we are having a problem
-                               // with the direct lookup.  Need to investigate.
-                               //
-                               // For now, fall back to the full lookup in that case.
-                               //
-                               TypeExpr texpr = RootContext.LookupType (
-                                       ec.DeclSpace, cname, false, loc);
+                       if (dim == "*" && !TypeManager.VerifyUnManaged (ltype, loc)) {
+                               return null;
+                       }
 
-                               if (texpr == null)
-                                       return null;
+                       if (dim != "")
+                               type = TypeManager.GetConstructedType (ltype, dim);
+                       else
+                               type = ltype;
 
-                               type = texpr.ResolveType (ec);
-                               if (type == null)
-                                       return null;
+                       if (type == null) {
+                               throw new InternalErrorException ("Couldn't create computed type " + ltype + dim);
                        }
 
-                       if (!ec.ResolvingTypeTree){
-                               //
-                               // If the above flag is set, this is being invoked from the ResolveType function.
-                               // Upper layers take care of the type validity in this context.
-                               //
                        if (!ec.InUnsafe && type.IsPointer){
                                UnsafeError (loc);
                                return null;
                        }
+
+                       if (type.IsArray && (type.GetElementType () == TypeManager.arg_iterator_type ||
+                               type.GetElementType () == TypeManager.typed_reference_type)) {
+                               Report.Error (611, loc, "Array elements cannot be of type `{0}'", TypeManager.CSharpName (type.GetElementType ()));
+                               return null;
                        }
                        
                        eclass = ExprClass.Type;
@@ -8900,33 +9077,29 @@ namespace Mono.CSharp {
                                return left + dim;
                        }
                }
+
+               public override string FullName {
+                       get {
+                               return type.FullName;
+                       }
+               }
        }
 
-       //
-       // This class is used to represent the address of an array, used
-       // only by the Fixed statement, this is like the C "&a [0]" construct.
-       //
-       public class ArrayPtr : Expression {
+       public class FixedBufferPtr: Expression {
                Expression array;
-               
-               public ArrayPtr (Expression array, Location l)
-               {
-                       Type array_type = TypeManager.GetElementType (array.Type);
 
+               public FixedBufferPtr (Expression array, Type array_type, Location l)
+               {
                        this.array = array;
+                       this.loc = l;
 
                        type = TypeManager.GetPointerType (array_type);
                        eclass = ExprClass.Value;
-                       loc = l;
                }
 
-               public override void Emit (EmitContext ec)
+               public override void Emit(EmitContext ec)
                {
-                       ILGenerator ig = ec.ig;
-                       
                        array.Emit (ec);
-                       IntLiteral.EmitInt (ig, 0);
-                       ig.Emit (OpCodes.Ldelema, TypeManager.GetElementType (array.Type));
                }
 
                public override Expression DoResolve (EmitContext ec)
@@ -8938,6 +9111,31 @@ namespace Mono.CSharp {
                }
        }
 
+
+       //
+       // This class is used to represent the address of an array, used
+       // only by the Fixed statement, this generates "&a [0]" construct
+       // for fixed (char *pa = a)
+       //
+       public class ArrayPtr : FixedBufferPtr {
+               Type array_type;
+               
+               public ArrayPtr (Expression array, Type array_type, Location l):
+                       base (array, array_type, l)
+               {
+                       this.array_type = array_type;
+               }
+
+               public override void Emit (EmitContext ec)
+               {
+                       base.Emit (ec);
+                       
+                       ILGenerator ig = ec.ig;
+                       IntLiteral.EmitInt (ig, 0);
+                       ig.Emit (OpCodes.Ldelema, array_type);
+               }
+       }
+
        //
        // Used by the fixed statement
        //
@@ -8998,18 +9196,23 @@ namespace Mono.CSharp {
                                        return null;
                        }
 
-                       if (ec.CurrentBranching.InCatch () ||
-                           ec.CurrentBranching.InFinally (true)) {
-                               Error (255,
-                                             "stackalloc can not be used in a catch or finally block");
+                       Constant c = count as Constant;
+                       if (c != null && c.IsNegative) {
+                               Report.Error (247, loc, "Cannot use a negative size with stackalloc");
                                return null;
                        }
 
-                       otype = ec.DeclSpace.ResolveType (t, false, loc);
+                       if (ec.InCatch || ec.InFinally) {
+                               Error (255, "Cannot use stackalloc in finally or catch");
+                               return null;
+                       }
 
-                       if (otype == null)
+                       TypeExpr texpr = t.ResolveAsTypeTerminal (ec);
+                       if (texpr == null)
                                return null;
 
+                       otype = texpr.Type;
+
                        if (!TypeManager.VerifyUnManaged (otype, loc))
                                return null;