**** Merged r40457-r40460 from MCS ****
[mono.git] / mcs / gmcs / expression.cs
old mode 100755 (executable)
new mode 100644 (file)
index f4a4654..9a5c6b8
@@ -217,6 +217,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;
                }
 
@@ -237,7 +241,7 @@ namespace Mono.CSharp {
                                
                        case Operator.UnaryNegation:
                                result = TryReduceNegative (e);
-                               return true;
+                               return result != null;
                                
                        case Operator.LogicalNot:
                                if (expr_type != TypeManager.bool_type) {
@@ -323,11 +327,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;
                        
@@ -353,18 +368,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) {
@@ -428,17 +431,29 @@ namespace Mono.CSharp {
                                }
 
                                IVariable variable = Expr as IVariable;
-                               if (!ec.InFixedInitializer && ((variable == null) || !variable.VerifyFixed (false))) {
+                               bool is_fixed = variable != null && variable.VerifyFixed (false);
+
+                               if (!ec.InFixedInitializer && !is_fixed) {
                                        Error (212, "You can only take the address of an unfixed expression inside " +
                                               "of a fixed statement initializer");
                                        return null;
                                }
 
-                               if (ec.InFixedInitializer && ((variable != null) && variable.VerifyFixed (false))) {
+                               if (ec.InFixedInitializer && is_fixed) {
                                        Error (213, "You can not fix 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))
@@ -568,6 +583,9 @@ namespace Mono.CSharp {
                        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);
                }
@@ -645,7 +663,7 @@ 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 prepared;
@@ -719,6 +737,21 @@ namespace Mono.CSharp {
                {
                        return "*(" + expr + ")";
                }
+
+               #region IVariable Members
+
+               public VariableInfo VariableInfo {
+                       get {
+                               return null;
+                       }
+               }
+
+               public bool VerifyFixed (bool is_expression)
+               {
+                       return true;
+               }
+
+               #endregion
        }
        
        /// <summary>
@@ -880,6 +913,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);
                }
 
@@ -975,7 +1012,6 @@ namespace Mono.CSharp {
                        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)
                {
@@ -1031,10 +1067,10 @@ namespace Mono.CSharp {
 
                public override Expression DoResolve (EmitContext ec)
                {
-                       TypeExpr texpr = ProbeType.ResolveAsTypeTerminal (ec, false);
+                       TypeExpr texpr = ProbeType.ResolveAsTypeTerminal (ec);
                        if (texpr == null)
                                return null;
-                       probe_type = texpr.ResolveType (ec);
+                       probe_type = texpr.Type;
 
                        CheckObsoleteAttribute (probe_type);
 
@@ -1153,6 +1189,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
                                //
@@ -1165,15 +1204,15 @@ namespace Mono.CSharp {
                                warning_never_matches = true;
                        }
                        
-                               if (warning_always_matches)
+                       if (warning_always_matches)
                                Warning (183, "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))
+                       else if (warning_never_matches){
+                               if (!(probe_type.IsInterface || expr.Type.IsInterface))
                                        Warning (184, "The given expression is never of the provided ('{0}') type", TypeManager.CSharpName (probe_type));
                        }
 
                        return this;
-               }                               
+               }
        }
 
        /// <summary>
@@ -1231,6 +1270,9 @@ namespace Mono.CSharp {
                        }
 
                        if (Convert.ExplicitReferenceConversionExists (etype, probe_type)){
+                               if (etype.IsGenericParameter)
+                                       expr = new BoxedCast (expr, etype);
+
                                do_isinst = true;
                                return this;
                        }
@@ -1768,11 +1810,11 @@ namespace Mono.CSharp {
                        if (expr == null)
                                return null;
 
-                       TypeExpr target = target_type.ResolveAsTypeTerminal (ec, false);
+                       TypeExpr target = target_type.ResolveAsTypeTerminal (ec);
                        if (target == null)
                                return null;
-
-                       type = target.ResolveType (ec);
+                       
+                       type = target.Type;
 
                        CheckObsoleteAttribute (type);
 
@@ -2236,8 +2278,8 @@ namespace Mono.CSharp {
                        // Special cases: string or type parameter comapred to null
                        //
                        if (oper == Operator.Equality || oper == Operator.Inequality){
-                               if ((!TypeManager.IsValueType (l) && (right is NullLiteral)) ||
-                                   (!TypeManager.IsValueType (r) && (left is NullLiteral))) {
+                               if ((!TypeManager.IsValueType (l) && r == TypeManager.null_type) ||
+                                   (!TypeManager.IsValueType (r) && l == TypeManager.null_type)) {
                                        Type = TypeManager.bool_type;
                                        
                                        return this;
@@ -2374,6 +2416,15 @@ namespace Mono.CSharp {
                                        return this;
                                }
 
+                               bool left_is_null = left is NullLiteral;
+                               bool right_is_null = right is NullLiteral;
+                               if (left_is_null || right_is_null) {
+                                       if (oper == Operator.Equality)
+                                               return new BoolLiteral (left_is_null == right_is_null);
+                                       else
+                                               return new BoolLiteral (left_is_null != right_is_null);
+                               }
+
                                //
                                // operator != (object a, object b)
                                // operator == (object a, object b)
@@ -2453,7 +2504,7 @@ namespace Mono.CSharp {
                                                else
                                                        method = TypeManager.delegate_remove_delegate_delegate;
 
-                                               if (l != r) {
+                                               if (!TypeManager.IsEqual (l, r)) {
                                                        Error_OperatorCannotBeApplied ();
                                                        return null;
                                                }
@@ -2696,16 +2747,27 @@ namespace Mono.CSharp {
                                }
                        } 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){
                                Expression e = ConstantFold.BinaryFold (
                                        ec, oper, lc, rc, loc);
@@ -2713,6 +2775,9 @@ namespace Mono.CSharp {
                                                return e;
                        }
 
+                       if (TypeManager.IsNullableType (left.Type) || TypeManager.IsNullableType (right.Type))
+                               return new Nullable.LiftedBinaryOperator (oper, left, right, loc).Resolve (ec);
+
                        return ResolveOperator (ec);
                }
 
@@ -3096,7 +3161,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)
                {
@@ -3150,14 +3219,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;
@@ -3171,10 +3239,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
@@ -3406,17 +3475,26 @@ namespace Mono.CSharp {
                                //
                                left.Emit (ec);
                                ig.Emit (OpCodes.Conv_I);
-                               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);
+
+                               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)
@@ -3468,6 +3546,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 (
@@ -3483,9 +3564,6 @@ namespace Mono.CSharp {
                        if (trueExpr == null || falseExpr == null)
                                return null;
 
-                       if ((trueExpr is NullLiteral) && (falseExpr is NullLiteral))
-                               return trueExpr;
-
                        eclass = ExprClass.Value;
                        if (trueExpr.Type == falseExpr.Type)
                                type = trueExpr.Type;
@@ -3525,13 +3603,12 @@ namespace Mono.CSharp {
                                }
                        }
 
+                       // 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;
@@ -3600,6 +3677,11 @@ namespace Mono.CSharp {
                {
                        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;
                        }
 
@@ -3614,8 +3696,8 @@ namespace Mono.CSharp {
                                
                                if (variable_info != null)
                                        variable_info.SetAssigned (ec);
-                       }
-
+               }
+               
                        Expression e = Block.GetConstantExpression (Name);
                        if (e != null) {
                                local_info.Used = true;
@@ -3635,11 +3717,14 @@ namespace Mono.CSharp {
                                // flag it for capturing
                                //
                                if (local_info.Block.Toplevel != ec.CurrentBlock.Toplevel){
+                                       if (local_info.AddressTaken){
+                                               AnonymousMethod.Error_AddressOfCapturedVar (local_info.Name, loc);
+                                               return null;
+                                       }
                                        ec.CaptureVariable (local_info);
-                                       //Console.WriteLine ("Capturing at " + loc);
                                }
                        }
-
+                       
                        return this;
                }
 
@@ -3650,7 +3735,11 @@ namespace Mono.CSharp {
 
                override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
                {
-                       return DoResolveBase (ec, right_side);
+                       Expression ret = DoResolveBase (ec, right_side);
+                       if (ret != null)
+                               CheckObsoleteAttribute (ret.Type);
+
+                       return ret;
                }
 
                public bool VerifyFixed (bool is_expression)
@@ -4150,8 +4239,9 @@ 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.Error (197, loc, "Cannot pass '{0}' as ref or out or take its address because it is a member of a marshal-by-reference class",
+                                                               fe.Name);
                                                        return false;
                                                }
                                        }
@@ -4203,7 +4293,14 @@ namespace Mono.CSharp {
                                                pr.AddressOf (ec, mode);
                                        }
                                } else {
-                                       ((IMemoryLocation)Expr).AddressOf (ec, mode);
+                                       if (Expr is IMemoryLocation)
+                                               ((IMemoryLocation) Expr).AddressOf (ec, mode);
+                                       else {
+                                               Report.Error (
+                                                       1510, Expr.Location,
+                                                       "An lvalue is required as an argument to out or ref");
+                                               return;
+                                       }
                                }
                        } else
                                Expr.Emit (ec);
@@ -4219,13 +4316,6 @@ namespace Mono.CSharp {
                Expression expr;
                MethodBase method = null;
                
-               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.
@@ -4246,31 +4336,6 @@ 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
                ///
@@ -4297,10 +4362,10 @@ namespace Mono.CSharp {
                                return null;
 
                        if (argument_expr is NullLiteral) {
-                               //
+                       //
                                // 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.
-                               //
+                       //
                                // 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
@@ -4308,16 +4373,16 @@ namespace Mono.CSharp {
                                //   * 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 'System.Null'.
-                               //         I think it used to be 'object' and thus needed a special case to avoid the
-                               //         immediately following two checks.
+                               //  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 p;
 
@@ -4326,7 +4391,7 @@ namespace Mono.CSharp {
 
                        Expression p_tmp = new EmptyExpression (p);
                        Expression q_tmp = new EmptyExpression (q);
-
+                       
                        bool p_to_q = Convert.ImplicitConversionExists (ec, p_tmp, q);
                        bool q_to_p = Convert.ImplicitConversionExists (ec, q_tmp, p);
 
@@ -4383,46 +4448,14 @@ namespace Mono.CSharp {
                ///     true  if candidate is better than the current best match
                /// </remarks>
                static bool BetterFunction (EmitContext ec, ArrayList args, int argument_count,
-                                           MethodBase candidate, bool candidate_params,
-                                           MethodBase best, bool best_params, Location loc)
+                                          MethodBase candidate, bool candidate_params,
+                                          MethodBase best, bool best_params, Location loc)
                {
-                       ParameterData candidate_pd = GetParameterData (candidate);
-                       ParameterData best_pd = GetParameterData (best);
+                       ParameterData candidate_pd = TypeManager.GetParameterData (candidate);
+                       ParameterData best_pd = TypeManager.GetParameterData (best);
                
-                       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 !candidate_params && best_params;
-
-                       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 false;
-
                        bool better_at_least_one = false;
-                       bool is_equal = true;
-
+                       bool same = true;
                        for (int j = 0; j < argument_count; ++j) {
                                Argument a = (Argument) args [j];
 
@@ -4437,9 +4470,10 @@ namespace Mono.CSharp {
                                        if (best_params)
                                                bt = TypeManager.GetElementType (bt);
 
-                               if (!ct.Equals (bt))
-                                       is_equal = false;
+                               if (ct.Equals (bt))
+                                       continue;
 
+                               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'.
@@ -4452,28 +4486,48 @@ namespace Mono.CSharp {
                                        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 true;
+                       if (better_at_least_one)
+                               return true;
+
+                       if (!same)
+                               return false;
 
                        //
                        // If two methods have equal parameter types, but
                        // only one of them is generic, the non-generic one wins.
                        //
-                       if (is_equal) {
-                               if (TypeManager.IsGenericMethod (best) && !TypeManager.IsGenericMethod (candidate))
-                                       return true;
-                               else if (!TypeManager.IsGenericMethod (best) && TypeManager.IsGenericMethod (candidate))
-                                       return false;
+                       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
+                       //
+                       //   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.
+                       //
+                       if (candidate_params == best_params) {
+                               //
+                               // We need to handle the case of a virtual function and its override.
+                               // The override is ignored during 'applicable_type' calculation.  However,
+                               // it should be chosen over the base virtual function, especially when handling
+                               // value types.
+                               //
+                               return IsAncestralType (best.DeclaringType, candidate.DeclaringType);
                        }
 
-                       return better_at_least_one;
+                       //
+                       // 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)
@@ -4492,7 +4546,7 @@ namespace Mono.CSharp {
                        sb.Append (".");
                        sb.Append (mb.Name);
                        
-                       ParameterData pd = GetParameterData (mb);
+                       ParameterData pd = TypeManager.GetParameterData (mb);
 
                        int count = pd.Count;
                        sb.Append (" (");
@@ -4571,7 +4625,7 @@ namespace Mono.CSharp {
                                                      bool do_varargs, ref MethodBase candidate)
                {
                        if (!me.HasTypeArguments &&
-                           !InferParamsTypeArguments (ec, arguments, ref candidate))
+                           !TypeManager.InferParamsTypeArguments (ec, arguments, ref candidate))
                                return false;
 
                        return IsParamsMethodApplicable (
@@ -4586,7 +4640,7 @@ namespace Mono.CSharp {
                                                      int arg_count, MethodBase candidate,
                                                      bool do_varargs)
                {
-                       ParameterData pd = GetParameterData (candidate);
+                       ParameterData pd = TypeManager.GetParameterData (candidate);
                        
                        int pd_count = pd.Count;
 
@@ -4671,7 +4725,7 @@ namespace Mono.CSharp {
                                          ref MethodBase candidate)
                {
                        if (!me.HasTypeArguments &&
-                           !InferTypeArguments (ec, arguments, ref candidate))
+                           !TypeManager.InferTypeArguments (ec, arguments, ref candidate))
                                return false;
 
                        return IsApplicable (ec, arguments, arg_count, candidate);
@@ -4684,7 +4738,7 @@ namespace Mono.CSharp {
                static bool IsApplicable (EmitContext ec, ArrayList arguments, int arg_count,
                                          MethodBase candidate)
                {
-                       ParameterData pd = GetParameterData (candidate);
+                       ParameterData pd = TypeManager.GetParameterData (candidate);
 
                        if (arg_count != pd.Count)
                                return false;
@@ -4816,6 +4870,15 @@ namespace Mono.CSharp {
 
                                candidates.Add (methods [i]);
 
+                               //
+                               // Methods marked 'override' don't take part in 'applicable_type'
+                               // computation.
+                               //
+                               if (!me.IsBase &&
+                                   methods [i].IsVirtual &&
+                                   (methods [i].Attributes & MethodAttributes.NewSlot) == 0)
+                                       continue;
+
                                if (applicable_type == null)
                                        applicable_type = decl_type;
                                else if (applicable_type != decl_type) {
@@ -4827,19 +4890,19 @@ namespace Mono.CSharp {
 
                        int candidate_top = candidates.Count;
 
-                       if (candidate_top == 0) {
+                       if (applicable_type == null) {
                                //
                                // Okay so we have failed to find anything so we
                                // return by providing info about the closest match
                                //
                                for (int i = 0; i < methods.Length; ++i) {
                                        MethodBase c = (MethodBase) methods [i];
-                                       ParameterData pd = GetParameterData (c);
+                                       ParameterData pd = TypeManager.GetParameterData (c);
 
                                        if (pd.Count != arg_count)
                                                continue;
 
-                                       if (!InferTypeArguments (ec, Arguments, ref c))
+                                       if (!TypeManager.InferTypeArguments (ec, Arguments, ref c))
                                                continue;
 
                                        VerifyArgumentsCompat (ec, Arguments, arg_count,
@@ -4854,12 +4917,12 @@ namespace Mono.CSharp {
                                         
                                        for (int i = 0; i < methods.Length; ++i) {
                                                MethodBase c = methods [i];
-                                               ParameterData pd = GetParameterData (c);
+                                               ParameterData pd = TypeManager.GetParameterData (c);
 
                                                if (pd.Count != arg_count)
                                                        continue;
 
-                                               if (InferTypeArguments (ec, Arguments, ref c))
+                                               if (TypeManager.InferTypeArguments (ec, Arguments, ref c))
                                                        continue;
 
                                                Report.Error (
@@ -4867,7 +4930,7 @@ namespace Mono.CSharp {
                                                        "method `{0}' cannot be infered from " +
                                                        "the usage. Try specifying the type " +
                                                        "arguments explicitly.", report_name);
-                                               break;
+                                               return null;
                                        }
 
                                        Error_WrongNumArguments (
@@ -4900,11 +4963,12 @@ namespace Mono.CSharp {
                                        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) {
-                                               Type decl_type = ((MethodBase) candidates[i]).DeclaringType;
+                                               MethodBase candidate = (MethodBase) candidates [i];
+                                               Type decl_type = candidate.DeclaringType;
 
                                                if (decl_type == applicable_type) {
-                                                       candidates[k++] = candidates[j];
-                                                       candidates[j++] = candidates[i];
+                                                       candidates [k++] = candidates [j];
+                                                       candidates [j++] = candidates [i];
                                                        continue;
                                                }
 
@@ -4915,7 +4979,18 @@ namespace Mono.CSharp {
                                                    IsAncestralType (decl_type, next_applicable_type))
                                                        continue;
 
-                                               candidates[k++] = candidates[i];
+                                               candidates [k++] = candidates [i];
+
+#if false
+                                               //
+                                               // Methods marked 'override' don't take part in 'applicable_type'
+                                               // computation.
+                                               //
+                                               if (!me.IsBase &&
+                                                   candidate.IsVirtual &&
+                                                   (candidate.Attributes & MethodAttributes.NewSlot) == 0)
+                                                       continue;
+#endif
 
                                                if (next_applicable_type == null ||
                                                    IsAncestralType (next_applicable_type, decl_type))
@@ -4932,10 +5007,14 @@ namespace Mono.CSharp {
                         // Now we actually find the best method
                         //
 
-                       method = (MethodBase) candidates[0];
+                       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 (candidate == method)
+                                       continue;
+
                                bool cand_params = candidate_to_form != null && candidate_to_form.Contains (candidate);
 
                                if (BetterFunction (ec, Arguments, arg_count, 
@@ -5022,7 +5101,7 @@ namespace Mono.CSharp {
                                                          Type delegate_type, bool may_fail,
                                                          Location loc)
                {
-                       ParameterData pd = GetParameterData (method);
+                       ParameterData pd = TypeManager.GetParameterData (method);
                        int pd_count = pd.Count;
                        
                        for (int j = 0; j < arg_count; j++) {
@@ -5080,6 +5159,13 @@ namespace Mono.CSharp {
                                                a.Expr = conv;
                                }
 
+                               if (parameter_type.IsPointer){
+                                       if (!ec.InUnsafe){
+                                               UnsafeError (loc);
+                                               return false;
+                                       }
+                               }
+                               
                                Parameter.Modifier a_mod = a.GetParameterModifier () &
                                        unchecked (~(Parameter.Modifier.OUT | Parameter.Modifier.REF));
                                Parameter.Modifier p_mod = pd.ParameterModifier (j) &
@@ -5104,241 +5190,6 @@ namespace Mono.CSharp {
                        return true;
                }
 
-               static bool InferType (Type pt, Type at, ref Type[] infered)
-               {
-                       if (pt.IsGenericParameter && (pt.DeclaringMethod != null)) {
-                               int pos = pt.GenericParameterPosition;
-
-                               if (infered [pos] == null) {
-                                       Type check = at;
-                                       while (check.IsArray)
-                                               check = check.GetElementType ();
-
-                                       if (pt == check)
-                                               return false;
-
-                                       infered [pos] = at;
-                                       return true;
-                               }
-
-                               if (infered [pos] != at)
-                                       return false;
-
-                               return true;
-                       }
-
-                       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;
-
-                       for (int i = 0; i < infered_types.Length; i++) {
-                               if (infered [i] == null) {
-                                       infered [i] = infered_types [i];
-                                       continue;
-                               }
-
-                               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 we have come this far, the case which
-                       // remains is when the number of parameters is
-                       // less than or equal to the argument count.
-                       //
-                       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 (!InferType (element_type, a.Type, ref infered_types))
-                                       return false;
-                       }
-
-                       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)
-               {
-                       if (infered_types == null)
-                               return false;
-
-                       for (int i = 0; i < arg_types.Length; i++) {
-                               if (arg_types [i] == null)
-                                       continue;
-
-                               if (!InferType (param_types [i], arg_types [i],
-                                               ref infered_types))
-                                       return false;
-                       }
-
-                       for (int i = 0; i < infered_types.Length; i++)
-                               if (infered_types [i] == null)
-                                       return false;
-
-                       return true;
-               }
-
-               static bool InferTypeArguments (EmitContext ec, ArrayList arguments,
-                                               ref MethodBase method)
-               {
-                       if (!TypeManager.IsGenericMethod (method))
-                               return true;
-
-                       int arg_count;
-                       if (arguments != null)
-                               arg_count = arguments.Count;
-                       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);
-
-                               Argument a = (Argument) arguments [i];
-                               if ((a.Expr is NullLiteral) || (a.Expr is MethodGroupExpr))
-                                       continue;
-
-                               arg_types [i] = a.Type;
-                       }
-
-                       if (!InferTypeArguments (param_types, arg_types, ref infered_types))
-                               return false;
-
-                       method = method.BindGenericParameters (infered_types);
-                       return true;
-               }
-
-               public static bool InferTypeArguments (EmitContext ec, ParameterData apd,
-                                                      ref MethodBase method)
-               {
-                       if (!TypeManager.IsGenericMethod (method))
-                               return true;
-
-                       ParameterData pd = GetParameterData (method);
-                       if (apd.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 < apd.Count; i++) {
-                               param_types [i] = pd.ParameterType (i);
-                               arg_types [i] = apd.ParameterType (i);
-                       }
-
-                       if (!InferTypeArguments (param_types, arg_types, ref infered_types))
-                               return false;
-
-                       method = method.BindGenericParameters (infered_types);
-                       return true;
-               }
-
                public override Expression DoResolve (EmitContext ec)
                {
                        //
@@ -5434,6 +5285,9 @@ namespace Mono.CSharp {
                                }
                        }
                        
+                       if (mg.InstanceExpression != null)
+                               mg.InstanceExpression.CheckMarshallByRefAccess (ec.ContainerType);
+
                        eclass = ExprClass.Value;
                        return this;
                }
@@ -5490,7 +5344,7 @@ namespace Mono.CSharp {
                {
                        ParameterData pd;
                        if (mb != null)
-                               pd = GetParameterData (mb);
+                               pd = TypeManager.GetParameterData (mb);
                        else
                                pd = null;
                        
@@ -5560,7 +5414,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];
@@ -5801,8 +5655,8 @@ namespace Mono.CSharp {
                        //
                        // First try to resolve it as a cast.
                        //
-                       TypeExpr te = expr.ResolveAsTypeTerminal (ec, true);
-                       if (te != null) {
+                       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);
                        }
@@ -5848,8 +5702,8 @@ namespace Mono.CSharp {
                        //
                        // First try to resolve it as a cast.
                        //
-                       TypeExpr te = expr.ResolveAsTypeTerminal (ec, true);
-                       if (te != null) {
+                       TypeExpr te = expr.ResolveAsTypeStep (ec) as TypeExpr;
+                       if ((te != null) && (te.eclass == ExprClass.Type)) {
                                error201 ();
                                return null;
                        }
@@ -5984,11 +5838,11 @@ namespace Mono.CSharp {
                                return this;
                        }
                        
-                       TypeExpr texpr = RequestedType.ResolveAsTypeTerminal (ec, false);
+                       TypeExpr texpr = RequestedType.ResolveAsTypeTerminal (ec);
                        if (texpr == null)
                                return null;
-
-                       type = texpr.ResolveType (ec);
+                       
+                       type = texpr.Type;
                        if (type == null)
                                return null;
                        
@@ -5999,7 +5853,7 @@ namespace Mono.CSharp {
                        if (IsDelegate){
                                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;
                        }
@@ -6072,11 +5926,16 @@ namespace Mono.CSharp {
                                }
 
                                method = Invocation.OverloadResolve (
-                                       ec, (MethodGroupExpr) ml, Arguments, false, loc);
+                                       ec, (MethodGroupExpr) ml, Arguments, true, loc);
                                
                        }
 
-                       if (method == null) { 
+                       if (method == null) {
+                               if (almostMatchedMembers.Count != 0) {
+                                       MemberLookupFailed (ec, type, type, ".ctor", null, loc);
+                                       return null;
+                               }
+
                                 if (!is_struct || Arguments.Count > 0) {
                                        Error (1501, String.Format (
                                            "New invocation: Can not find a constructor in `{0}' for this argument list",
@@ -6521,12 +6380,12 @@ namespace Mono.CSharp {
                        //
                        TypeExpr array_type_expr;
                        array_type_expr = new ComposedCast (requested_base_type, array_qualifier.ToString (), loc);
-                       array_type_expr = array_type_expr.ResolveAsTypeTerminal (ec, false);
+                       array_type_expr = array_type_expr.ResolveAsTypeTerminal (ec);
                        if (array_type_expr == null)
                                return false;
 
-                       type = array_type_expr.ResolveType (ec);
-                       
+                       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;
@@ -6867,8 +6726,7 @@ namespace Mono.CSharp {
                                                // If we are dealing with a struct, get the
                                                // address of it, so we can store it.
                                                //
-                                               if ((dims == 1) && 
-                                                   etype.IsSubclassOf (TypeManager.value_type) &&
+                                               if ((dims == 1) && etype.IsValueType &&
                                                    (!TypeManager.IsBuiltinOrEnum (etype) ||
                                                     etype == TypeManager.decimal_type)) {
                                                        if (e is New){
@@ -7025,7 +6883,7 @@ 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;
 
@@ -7037,6 +6895,9 @@ namespace Mono.CSharp {
                        if ((block != null) && (block.ThisVariable != null))
                                variable_info = block.ThisVariable.VariableInfo;
 
+                       if (ec.CurrentAnonymousMethod != null)
+                               ec.CaptureThis ();
+                       
                        return true;
                }
 
@@ -7240,11 +7101,11 @@ namespace Mono.CSharp {
 
                public override Expression DoResolve (EmitContext ec)
                {
-                       TypeExpr texpr = QueriedType.ResolveAsTypeTerminal (ec, false);
+                       TypeExpr texpr = QueriedType.ResolveAsTypeTerminal (ec);
                        if (texpr == null)
                                return null;
 
-                       typearg = texpr.ResolveType (ec);
+                       typearg = texpr.Type;
 
                        if (typearg == TypeManager.void_type) {
                                Error (673, "System.Void cannot be used from C# - " +
@@ -7314,7 +7175,7 @@ namespace Mono.CSharp {
                                return null;
                        }
                                
-                       TypeExpr texpr = QueriedType.ResolveAsTypeTerminal (ec, false);
+                       TypeExpr texpr = QueriedType.ResolveAsTypeTerminal (ec);
                        if (texpr == null)
                                return null;
 
@@ -7323,7 +7184,7 @@ namespace Mono.CSharp {
                                return null;
                        }
 
-                       type_queried = texpr.ResolveType (ec);
+                       type_queried = texpr.Type;
 
                        CheckObsoleteAttribute (type_queried);
 
@@ -7390,9 +7251,11 @@ namespace Mono.CSharp {
                        if (sn == null || left == null || left.Type.Name != sn.Name)
                                return false;
 
-                       return RootContext.LookupType (ec.DeclSpace, sn.Name, true, loc) != null;
+                       return ec.DeclSpace.LookupType (sn.Name, true, loc) != null;
                }
                
+               // TODO: possible optimalization
+               // Cache resolved constant result in FieldBuilder <-> expresion map
                public static Expression ResolveMemberAccess (EmitContext ec, Expression member_lookup,
                                                              Expression left, Location loc,
                                                              Expression left_original)
@@ -7418,7 +7281,10 @@ namespace Mono.CSharp {
                                FieldInfo fi = fe.FieldInfo.Mono_GetGenericFieldDefinition ();
                                Type decl_type = fi.DeclaringType;
 
-                               if (fi is FieldBuilder) {
+                               bool is_emitted = fi is FieldBuilder;
+                               Type t = fi.FieldType;
+
+                               if (is_emitted) {
                                        Const c = TypeManager.LookupConstant ((FieldBuilder) fi);
                                        
                                        if (c != null) {
@@ -7428,16 +7294,29 @@ namespace Mono.CSharp {
 
                                                object real_value = ((Constant) c.Expr).GetValue ();
 
-                                               return Constantify (real_value, fi.FieldType);
+                                               Expression exp = Constantify (real_value, t);
+
+                                               if (left_is_explicit && !left_is_type && !IdenticalNameAndTypeName (ec, left_original, left, loc)) {
+                                                       Report.SymbolRelatedToPreviousError (c);
+                                                       error176 (loc, c.GetSignatureForError ());
+                                                       return null;
+                                               }
+                                       
+                                               return exp;
                                        }
                                }
 
+                               // IsInitOnly is because of MS compatibility, I don't know why but they emit decimal constant as InitOnly
+                               if (fi.IsInitOnly && !is_emitted && t == TypeManager.decimal_type) {
+                                       object[] attrs = fi.GetCustomAttributes (TypeManager.decimal_constant_attribute_type, false);
+                                       if (attrs.Length == 1)
+                                               return new DecimalConstant (((System.Runtime.CompilerServices.DecimalConstantAttribute) attrs [0]).Value);
+                               }
+
                                if (fi.IsLiteral) {
-                                       Type t = fi.FieldType;
-                                       
                                        object o;
 
-                                       if (fi is FieldBuilder)
+                                       if (is_emitted)
                                                o = TypeManager.GetValue ((FieldBuilder) fi);
                                        else
                                                o = fi.GetValue (fi);
@@ -7474,7 +7353,7 @@ namespace Mono.CSharp {
                                        return exp;
                                }
 
-                               if (fi.FieldType.IsPointer && !ec.InUnsafe){
+                               if (t.IsPointer && !ec.InUnsafe){
                                        UnsafeError (loc);
                                        return null;
                                }
@@ -7600,17 +7479,15 @@ namespace Mono.CSharp {
                        if (expr == null)
                                return null;
 
-                       if (expr is SimpleName){
-                               SimpleName child_expr = (SimpleName) expr;
-                               string fqname = DeclSpace.MakeFQN (child_expr.Name, Identifier);
-
-                               Expression new_expr;
-                               if (args != null)
-                                       new_expr = new ConstructedType (fqname, args, loc);
-                               else
-                                       new_expr = new SimpleName (fqname, loc);
-
-                               return new_expr.Resolve (ec, flags);
+                       if (expr is Namespace) {
+                               Namespace ns = (Namespace) 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}' could not be found in namespace `{1}'", Identifier, ns.FullName);
+                               return retval;
                        }
                                        
                        //
@@ -7624,7 +7501,7 @@ namespace Mono.CSharp {
 
                        Type expr_type;
                        if (expr is TypeExpr){
-                               expr_type = ((TypeExpr) expr).ResolveType (ec);
+                               expr_type = expr.Type;
 
                                if (!ec.DeclSpace.CheckAccessLevel (expr_type)){
                                        Report.Error (122, loc, "'{0}' is inaccessible due to its protection level", expr_type);
@@ -7671,8 +7548,6 @@ namespace Mono.CSharp {
                                return null;
                        }
 
-                       int errors = Report.Errors;
-
                        Expression member_lookup;
                        member_lookup = MemberLookup (
                                ec, expr_type, expr_type, Identifier, loc);
@@ -7688,7 +7563,8 @@ namespace Mono.CSharp {
                        }
 
                        if (member_lookup is TypeExpr) {
-                               if (!(expr is TypeExpr) && !(expr is SimpleName)) {
+                               if (!(expr is TypeExpr) && 
+                                   !IdenticalNameAndTypeName (ec, original, expr, loc)) {
                                        Error (572, "Can't reference type `" + Identifier + "' through an expression; try `" +
                                               member_lookup.Type + "' instead");
                                        return null;
@@ -7740,65 +7616,44 @@ namespace Mono.CSharp {
 
                public override Expression DoResolve (EmitContext ec)
                {
-                       return DoResolve (ec, null, ResolveFlags.VariableOrValue |
-                                         ResolveFlags.SimpleName | ResolveFlags.Type);
+                       return DoResolve (ec, null, ResolveFlags.VariableOrValue | ResolveFlags.Type);
                }
 
                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, ResolveFlags.VariableOrValue | ResolveFlags.Type);
                }
 
-               public override Expression ResolveAsTypeStep (EmitContext ec)
+               public override FullNamedExpression ResolveAsTypeStep (EmitContext ec)
                {
-                       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;
-
-                               fname = MemberName.MakeName (fname, args);
-
-                               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) {
-                                               if (args != null)
-                                                       return new ConstructedType (
-                                                               fully_qualified, args, loc);
-                                               else
-                                                       return new TypeExpression (
-                                                               fully_qualified, loc);
-                                       }
-                               }
-
-                               full_expr = full_expr.Expr as MemberAccess;
-                       }
+                       return ResolveNamespaceOrType (ec, false);
+               }
 
-                       Expression new_expr = expr.ResolveAsTypeStep (ec);
+               public FullNamedExpression ResolveNamespaceOrType (EmitContext ec, bool silent)
+               {
+                       FullNamedExpression new_expr = expr.ResolveAsTypeStep (ec);
 
                        if (new_expr == null)
                                return null;
 
-                       if (new_expr is SimpleName){
-                               SimpleName child_expr = (SimpleName) new_expr;
-                               string fqname = DeclSpace.MakeFQN (child_expr.Name, Identifier);
-                               
-                               if (args != null)
-                                       new_expr = new ConstructedType (fqname, args, loc);
-                               else
-                                       new_expr = new SimpleName (fqname, 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}' could not be found in namespace `{1}'", Identifier, ns.FullName);
+                               return retval;
                        }
 
-                       Type expr_type = ((TypeExpr) new_expr).ResolveType (ec);
-                       if (expr_type == null)
+                       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 (" +
                                       TypeManager.CSharpName (expr_type) + ")");
@@ -7806,19 +7661,21 @@ namespace Mono.CSharp {
                        }
 
                        Expression member_lookup;
-                       string lookup_id;
-                       lookup_id = MemberName.MakeName (Identifier, args);
-                       member_lookup = MemberLookupFinal (
-                               ec, expr_type, expr_type, lookup_id, loc);
-                       if (member_lookup == null)
+                       member_lookup = MemberLookupFinal (ec, expr_type, expr_type, lookup_id, loc);
+                       if (!silent && member_lookup == null) {
+                               Report.Error (234, loc, "The type name `{0}' could not be found in type `{1}'", 
+                                             Identifier, new_expr.FullName);
                                return null;
+                       }
 
-                       TypeExpr texpr = member_lookup as TypeExpr;
-                       if (texpr == null)
+                       if (!(member_lookup is TypeExpr)) {
+                               Report.Error (118, loc, "'{0}.{1}' denotes a '{2}', where a type was expected",
+                                             new_expr.FullName, Identifier, member_lookup.ExprClassName ());
                                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;
@@ -7836,7 +7693,7 @@ namespace Mono.CSharp {
                        }
 
                        if (the_args != null) {
-                               ConstructedType ctype = new ConstructedType (t, the_args, loc);
+                               ConstructedType ctype = new ConstructedType (texpr.Type, the_args, loc);
                                return ctype.ResolveAsTypeStep (ec);
                        }
 
@@ -8616,6 +8473,8 @@ namespace Mono.CSharp {
                                UnsafeError (loc);
                                return null;
                        }
+
+                       instance_expr.CheckMarshallByRefAccess (ec.ContainerType);
                        
                        eclass = ExprClass.IndexerAccess;
                        return this;
@@ -8686,6 +8545,8 @@ namespace Mono.CSharp {
                                }
                        }
                        
+                       instance_expr.CheckMarshallByRefAccess (ec.ContainerType);
+
                        eclass = ExprClass.IndexerAccess;
                        return this;
                }
@@ -8926,6 +8787,12 @@ namespace Mono.CSharp {
                        loc = l;
                }
 
+               public Expression Source {
+                       get {
+                               return source;
+                       }
+               }
+                       
                public override Expression DoResolve (EmitContext ec)
                {
                        //
@@ -8965,13 +8832,13 @@ namespace Mono.CSharp {
                        loc = l;
                }
 
-               public override TypeExpr DoResolveAsTypeStep (EmitContext ec)
+               protected override TypeExpr DoResolveAsTypeStep (EmitContext ec)
                {
-                       TypeExpr lexpr = left.ResolveAsTypeTerminal (ec, false);
+                       TypeExpr lexpr = left.ResolveAsTypeTerminal (ec);
                        if (lexpr == null)
                                return null;
 
-                       Type ltype = lexpr.ResolveType (ec);
+                       Type ltype = lexpr.Type;
 
                        if ((ltype == TypeManager.void_type) && (dim != "*")) {
                                Report.Error (1547, Location,
@@ -8979,6 +8846,13 @@ namespace Mono.CSharp {
                                return null;
                        }
 
+                       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);
+                       }
+
                        int pos = 0;
                        while ((pos < dim.Length) && (dim [pos] == '[')) {
                                pos++;
@@ -9008,35 +8882,41 @@ namespace Mono.CSharp {
                                return this;
                        }
 
-                       //
-                       // 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.
+                       if (dim != "") {
                                //
-                               // For now, fall back to the full lookup in that case.
+                               // ltype.Fullname is already fully qualified, so we can skip
+                               // a lot of probes, and go directly to TypeManager.LookupType
                                //
-                               TypeExpr texpr = RootContext.LookupType (
-                                       ec.DeclSpace, cname, false, loc);
-
-                               if (texpr == null)
-                                       return null;
-
-                               type = texpr.ResolveType (ec);
-                               if (type == null)
-                                       return null;
+                               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.
+                                       //
+                                       FullNamedExpression e = ec.DeclSpace.LookupType (cname, false, loc);
+                                       if (e is TypeExpr)
+                                               type = ((TypeExpr) e).ResolveType (ec);
+                                       if (type == null)
+                                               return null;
+                               }
+                       } else {
+                               type = ltype;
                        }
 
                        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;
                        return this;
@@ -9047,6 +8927,12 @@ namespace Mono.CSharp {
                                return left + dim;
                        }
                }
+
+               public override string FullName {
+                       get {
+                               return type.FullName;
+                       }
+               }
        }
 
        //
@@ -9158,13 +9044,11 @@ namespace Mono.CSharp {
                                return null;
                        }
 
-                       TypeExpr texpr = t.ResolveAsTypeTerminal (ec, false);
+                       TypeExpr texpr = t.ResolveAsTypeTerminal (ec);
                        if (texpr == null)
                                return null;
 
-                       otype = texpr.ResolveType (ec);
-                       if (otype == null)
-                               return null;
+                       otype = texpr.Type;
 
                        if (!TypeManager.VerifyUnManaged (otype, loc))
                                return null;