2004-12-08 Martin Baulig <martin@ximian.com>
[mono.git] / mcs / gmcs / expression.cs
old mode 100755 (executable)
new mode 100644 (file)
index 3c1121b..87e0a95
@@ -323,11 +323,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 +364,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) {
@@ -439,6 +438,16 @@ namespace Mono.CSharp {
                                        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))
@@ -863,7 +872,7 @@ namespace Mono.CSharp {
 
                                return null;
                        } else {
-                               expr.Error_UnexpectedKind ("variable, indexer or property access");
+                               expr.Error_UnexpectedKind ("variable, indexer or property access", loc);
                                return null;
                        }
 
@@ -1012,7 +1021,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;
                
@@ -1031,10 +1040,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);
 
@@ -1153,6 +1162,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 +1177,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 +1243,9 @@ namespace Mono.CSharp {
                        }
 
                        if (Convert.ExplicitReferenceConversionExists (etype, probe_type)){
+                               if (etype.IsGenericParameter)
+                                       expr = new BoxedCast (expr, etype);
+
                                do_isinst = true;
                                return this;
                        }
@@ -1768,10 +1783,11 @@ namespace Mono.CSharp {
                        if (expr == null)
                                return null;
 
-                       type = ec.DeclSpace.ResolveType (target_type, false, Location);
-                       
-                       if (type == null)
+                       TypeExpr target = target_type.ResolveAsTypeTerminal (ec);
+                       if (target == null)
                                return null;
+                       
+                       type = target.Type;
 
                        CheckObsoleteAttribute (type);
 
@@ -2235,8 +2251,8 @@ namespace Mono.CSharp {
                        // 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))){
+                               if ((!TypeManager.IsValueType (l) && r == TypeManager.null_type) ||
+                                   (!TypeManager.IsValueType (r) && l == TypeManager.null_type)) {
                                        Type = TypeManager.bool_type;
                                        
                                        return this;
@@ -2395,8 +2411,8 @@ namespace Mono.CSharp {
                                        //
                                        // Also, a standard conversion must exist from either one
                                        //
-                                       if (!(Convert.ImplicitStandardConversionExists (left, r) ||
-                                             Convert.ImplicitStandardConversionExists (right, l))){
+                                       if (!(Convert.ImplicitStandardConversionExists (ec, left, r) ||
+                                             Convert.ImplicitStandardConversionExists (ec, right, l))){
                                                Error_OperatorCannotBeApplied ();
                                                return null;
                                        }
@@ -2428,14 +2444,16 @@ namespace Mono.CSharp {
                        //
                        if (oper == Operator.Addition || oper == Operator.Subtraction) {
                                if (TypeManager.IsDelegateType (l)){
-                                       if ((right.eclass == ExprClass.MethodGroup) &&
-                                           (RootContext.Version != LanguageVersion.ISO_1)){
+                                       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;
@@ -2693,16 +2711,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 sence 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);
@@ -3093,7 +3122,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)
                {
@@ -3147,14 +3180,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;
@@ -3168,10 +3200,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
@@ -3333,8 +3366,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);
 
@@ -3344,8 +3375,6 @@ namespace Mono.CSharp {
                        ig.MarkLabel (false_target);
                        op.Emit (ec);
                        ig.MarkLabel (end_target);
-
-                       ig.Emit (OpCodes.Nop);
                }
        }
 
@@ -3557,8 +3586,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)
                {
@@ -3568,8 +3599,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)
@@ -3579,7 +3612,9 @@ namespace Mono.CSharp {
                }
 
                public VariableInfo VariableInfo {
-                       get { return local_info.VariableInfo; }
+                       get {
+                               return local_info.VariableInfo;
+                       }
                }
 
                public bool IsReadOnly {
@@ -3588,22 +3623,31 @@ namespace Mono.CSharp {
                        }
                }
 
-               protected void DoResolveBase (EmitContext ec)
+               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){
+                                       Error (1604, "cannot assign to `" + Name + "' because it is readonly");
+                                       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;
@@ -3611,50 +3655,41 @@ namespace Mono.CSharp {
                                return e.Resolve (ec);
                        }
 
-                       VariableInfo variable_info = local_info.VariableInfo; 
                        if ((variable_info != null) && !variable_info.IsAssigned (ec, loc))
                                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){
+                                       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);
-
-                       if (e == null)
-                               return null;
-
-                       if (is_readonly){
-                               Error (1604, "cannot assign to `" + Name + "' because it is readonly");
-                               return null;
-                       }
-
-                       CheckObsoleteAttribute (e.Type);
+                       Expression ret = DoResolveBase (ec, right_side);
+                       if (ret != null)
+                               CheckObsoleteAttribute (ret.Type);
 
-                       if (local_info.LocalBuilder == null)
-                               return ec.RemapLocalLValue (local_info, right_side);
-                       
-                       return this;
+                       return ret;
                }
 
                public bool VerifyFixed (bool is_expression)
@@ -3666,29 +3701,86 @@ namespace Mono.CSharp {
                {
                        ILGenerator ig = ec.ig;
 
+                       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)
+                       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, bool leave_copy, bool prepare_for_load)
                {
+                       ILGenerator ig = ec.ig;
+                       prepared = prepare_for_load;
+
+                       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);
-                       ec.ig.Emit (OpCodes.Stloc, local_info.LocalBuilder);
+                               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 ()
@@ -3709,6 +3801,19 @@ namespace Mono.CSharp {
                VariableInfo vi;
                public Parameter.Modifier mod;
                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)
@@ -3732,8 +3837,7 @@ namespace Mono.CSharp {
 
                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,
@@ -3743,8 +3847,7 @@ namespace Mono.CSharp {
 
                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,
@@ -3766,13 +3869,30 @@ 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];
+
+                       if (ec.CurrentAnonymousMethod != null){
+                               if (is_ref){
+                                       Report.Error (1628, Location,
+                                                     "Can not reference a ref or out parameter in an anonymous method");
+                                       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.IsLocalParameter (name)){
+                                       ec.CaptureParameter (name, type, idx);
+                               }
+                       }
                }
 
                //
@@ -3841,17 +3961,25 @@ namespace Mono.CSharp {
                                arg_idx++;
 
                        EmitLdArg (ig, arg_idx);
+
+                       //
+                       // FIXME: Review for anonymous methods
+                       //
                }
                
                public override void Emit (EmitContext ec)
                {
+                       if (ec.HaveCaptureInfo && ec.IsParameterCaptured (name)){
+                               ec.EmitParameter (name);
+                               return;
+                       }
+                       
                        Emit (ec, false);
                }
                
                public void Emit (EmitContext ec, bool leave_copy)
                {
                        ILGenerator ig = ec.ig;
-                       
                        int arg_idx = idx;
 
                        if (!ec.IsStatic)
@@ -3882,6 +4010,11 @@ namespace Mono.CSharp {
                
                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;
                        
@@ -3918,6 +4051,11 @@ 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)
@@ -4031,7 +4169,7 @@ namespace Mono.CSharp {
                                }
                                Expr = Expr.ResolveLValue (ec, Expr);
                        } else if (ArgType == AType.Out)
-                               Expr = Expr.ResolveLValue (ec, new EmptyExpression ());
+                               Expr = Expr.ResolveLValue (ec, EmptyExpression.Null);
                        else
                                Expr = Expr.Resolve (ec);
 
@@ -4051,8 +4189,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;
                                                }
                                        }
@@ -4097,7 +4236,7 @@ namespace Mono.CSharp {
                                if (Expr is ParameterReference){
                                        ParameterReference pr = (ParameterReference) Expr;
 
-                                       if (pr.is_ref)
+                                       if (pr.IsRef)
                                                pr.EmitLoad (ec);
                                        else {
                                                
@@ -4119,7 +4258,6 @@ namespace Mono.CSharp {
 
                Expression expr;
                MethodBase method = null;
-               bool is_base;
                
                static Hashtable method_parameter_cache;
 
@@ -4176,10 +4314,11 @@ namespace Mono.CSharp {
                /// <summary>
                ///   Determines "better conversion" as specified in 7.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 = TypeManager.TypeToCoreType (a.Type);
                        Expression argument_expr = a.Expr;
@@ -4194,71 +4333,84 @@ namespace Mono.CSharp {
                        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 (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;
+                               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>
@@ -4266,11 +4418,11 @@ 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, int argument_count,
+               static bool BetterFunction (EmitContext ec, ArrayList args, int argument_count,
                                           MethodBase candidate, bool candidate_params,
                                           MethodBase best, bool best_params, Location loc)
                {
@@ -4301,24 +4453,21 @@ namespace Mono.CSharp {
                        // Trim (); is better than Trim (params char[] chars);
                         //
                        if (cand_count == 0 && argument_count == 0)
-                               return best_params ? 1 : 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 0;
+                                       return false;
 
-                       int rating1 = 0, rating2 = 0;
+                       bool better_at_least_one = false;
+                       bool is_equal = true;
 
                        for (int j = 0; j < argument_count; ++j) {
-                               int x, y;
-                               
                                Argument a = (Argument) args [j];
 
-                               Type ct = TypeManager.TypeToCoreType (
-                                       candidate_pd.ParameterType (j));
-                               Type bt = TypeManager.TypeToCoreType (
-                                       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)
@@ -4328,14 +4477,19 @@ 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))
+                                       is_equal = false;
 
-                               if (x < y)
-                                       return 0;
+                               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;
                        }
 
                         //
@@ -4346,12 +4500,20 @@ namespace Mono.CSharp {
                         // force it to select the candidate
                         //
                         if (!candidate_params && best_params && cand_count == argument_count)
-                                return 1;
+                                return true;
 
-                       if (rating1 > rating2)
-                               return 1;
-                       else
-                               return 0;
+                       //
+                       // 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;
+                       }
+
+                       return better_at_least_one;
                }
 
                public static string FullMethodDesc (MethodBase mb)
@@ -4498,9 +4660,9 @@ namespace Mono.CSharp {
                                Argument a = (Argument) arguments [i];
 
                                Parameter.Modifier a_mod = a.GetParameterModifier () &
-                                       ~(Parameter.Modifier.OUT | Parameter.Modifier.REF);
+                                       (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) {
 
@@ -4573,9 +4735,9 @@ namespace Mono.CSharp {
                                Argument a = (Argument) arguments [i];
 
                                Parameter.Modifier a_mod = a.GetParameterModifier () &
-                                       ~(Parameter.Modifier.OUT | Parameter.Modifier.REF);
+                                       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 ||
@@ -4745,7 +4907,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 (
@@ -4818,7 +4980,7 @@ namespace Mono.CSharp {
 
                                if (BetterFunction (ec, Arguments, arg_count, 
                                                    candidate, cand_params,
-                                                   method, method_params, loc) != 0) {
+                                                   method, method_params, loc)) {
                                        method = candidate;
                                        method_params = cand_params;
                                }
@@ -4836,10 +4998,10 @@ namespace Mono.CSharp {
                                         continue;
 
                                 bool cand_params = candidate_to_form != null && candidate_to_form.Contains (candidate);
-                               if (BetterFunction (ec, Arguments, arg_count,
+                               if (!BetterFunction (ec, Arguments, arg_count,
                                                    method, method_params,
                                                    candidate, cand_params,
-                                                   loc) != 1) {
+                                                    loc)) {
                                        Report.SymbolRelatedToPreviousError (candidate);
                                        ambiguous = true;
                                }
@@ -4958,10 +5120,17 @@ namespace Mono.CSharp {
                                                a.Expr = conv;
                                }
 
+                               if (parameter_type.IsPointer){
+                                       if (!ec.InUnsafe){
+                                               UnsafeError (loc);
+                                               return false;
+                                       }
+                               }
+                               
                                Parameter.Modifier a_mod = a.GetParameterModifier () &
-                                       ~(Parameter.Modifier.OUT | Parameter.Modifier.REF);
+                                       unchecked (~(Parameter.Modifier.OUT | Parameter.Modifier.REF));
                                Parameter.Modifier p_mod = pd.ParameterModifier (j) &
-                                       ~(Parameter.Modifier.OUT | Parameter.Modifier.REF);
+                                       unchecked (~(Parameter.Modifier.OUT | Parameter.Modifier.REF));
                                
                                if (a_mod != p_mod &&
                                    pd.ParameterModifier (pd_count - 1) != Parameter.Modifier.PARAMS) {
@@ -4982,7 +5151,7 @@ namespace Mono.CSharp {
                        return true;
                }
 
-               static bool InferType (Type pt, Type at, ref Type[] infered)
+               static bool InferType (Type pt, Type at, Type[] infered)
                {
                        if (pt.IsGenericParameter && (pt.DeclaringMethod != null)) {
                                int pos = pt.GenericParameterPosition;
@@ -4992,7 +5161,7 @@ namespace Mono.CSharp {
                                        while (check.IsArray)
                                                check = check.GetElementType ();
 
-                                       if (pt.Equals (check))
+                                       if (pt == check)
                                                return false;
 
                                        infered [pos] = at;
@@ -5005,16 +5174,19 @@ namespace Mono.CSharp {
                                return true;
                        }
 
-                       if (!pt.ContainsGenericParameters)
-                               return true;
+                       if (!pt.ContainsGenericParameters) {
+                               if (at.ContainsGenericParameters)
+                                       return InferType (at, pt, infered);
+                               else
+                                       return true;
+                       }
 
                        if (at.IsArray) {
                                if (!pt.IsArray ||
                                    (at.GetArrayRank () != pt.GetArrayRank ()))
                                        return false;
 
-                               return InferType (pt.GetElementType (), at.GetElementType (),
-                                                 ref infered);
+                               return InferType (pt.GetElementType (), at.GetElementType (), infered);
                        }
 
                        if (pt.IsArray) {
@@ -5022,36 +5194,63 @@ namespace Mono.CSharp {
                                    (pt.GetArrayRank () != at.GetArrayRank ()))
                                        return false;
 
-                               return InferType (pt.GetElementType (), at.GetElementType (),
-                                                 ref infered);
+                               return InferType (pt.GetElementType (), at.GetElementType (), infered);
                        }
 
-                       if (!at.IsGenericInstance)
-                               return false;
+                       if (pt.IsByRef && at.IsByRef)
+                               return InferType (pt.GetElementType (), at.GetElementType (), infered);
+                       ArrayList list = new ArrayList ();
+                       if (at.IsGenericInstance)
+                               list.Add (at);
+                       else {
+                               for (Type bt = at.BaseType; bt != null; bt = bt.BaseType)
+                                       list.Add (bt);
+
+                               list.AddRange (TypeManager.GetInterfaces (at));
+                       }
+
+                       bool found_one = false;
+
+                       foreach (Type type in list) {
+                               if (!type.IsGenericInstance)
+                                       continue;
+
+                               Type[] infered_types = new Type [infered.Length];
+
+                               if (!InferGenericInstance (pt, type, infered_types))
+                                       continue;
+
+                               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;
+                               }
 
+                               found_one = true;
+                       }
+
+                       return found_one;
+               }
+
+               static bool InferGenericInstance (Type pt, Type at, Type[] infered_types)
+               {
                        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)
+                       for (int i = 0; i < at_args.Length; i++) {
+                               if (!InferType (pt_args [i], at_args [i], infered_types))
                                        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])
+                               if (infered_types [i] == null)
                                        return false;
                        }
 
@@ -5104,7 +5303,7 @@ namespace Mono.CSharp {
                                Type pt = pd.ParameterType (i);
                                Type at = a.Type;
 
-                               if (!InferType (pt, at, ref infered_types))
+                               if (!InferType (pt, at, infered_types))
                                        return false;
                        }
 
@@ -5116,7 +5315,7 @@ namespace Mono.CSharp {
                                if ((a.Expr is NullLiteral) || (a.Expr is MethodGroupExpr))
                                        continue;
 
-                               if (!InferType (element_type, a.Type, ref infered_types))
+                               if (!InferType (element_type, a.Type, infered_types))
                                        return false;
                        }
 
@@ -5128,8 +5327,7 @@ namespace Mono.CSharp {
                        return true;
                }
 
-               public static bool InferTypeArguments (Type[] param_types, Type[] arg_types,
-                                                      ref Type[] infered_types)
+               public static bool InferTypeArguments (Type[] param_types, Type[] arg_types, Type[] infered_types)
                {
                        if (infered_types == null)
                                return false;
@@ -5138,8 +5336,7 @@ namespace Mono.CSharp {
                                if (arg_types [i] == null)
                                        continue;
 
-                               if (!InferType (param_types [i], arg_types [i],
-                                               ref infered_types))
+                               if (!InferType (param_types [i], arg_types [i], infered_types))
                                        return false;
                        }
 
@@ -5167,6 +5364,17 @@ namespace Mono.CSharp {
                                return false;
 
                        Type[] method_args = method.GetGenericArguments ();
+
+                       bool is_open = false;
+                       for (int i = 0; i < method_args.Length; i++) {
+                               if (method_args [i].IsGenericParameter) {
+                                       is_open = true;
+                                       break;
+                               }
+                       }
+                       if (!is_open)
+                               return true;
+
                        Type[] infered_types = new Type [method_args.Length];
 
                        Type[] param_types = new Type [pd.Count];
@@ -5182,7 +5390,7 @@ namespace Mono.CSharp {
                                arg_types [i] = a.Type;
                        }
 
-                       if (!InferTypeArguments (param_types, arg_types, ref infered_types))
+                       if (!InferTypeArguments (param_types, arg_types, infered_types))
                                return false;
 
                        method = method.BindGenericParameters (infered_types);
@@ -5210,7 +5418,7 @@ namespace Mono.CSharp {
                                arg_types [i] = apd.ParameterType (i);
                        }
 
-                       if (!InferTypeArguments (param_types, arg_types, ref infered_types))
+                       if (!InferTypeArguments (param_types, arg_types, infered_types))
                                return false;
 
                        method = method.BindGenericParameters (infered_types);
@@ -5223,9 +5431,6 @@ 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);
 
@@ -5245,7 +5450,7 @@ namespace Mono.CSharp {
                        }
 
                        if (!(expr is MethodGroupExpr)){
-                               expr.Error_UnexpectedKind (ResolveFlags.MethodGroup);
+                               expr.Error_UnexpectedKind (ResolveFlags.MethodGroup, loc);
                                return null;
                        }
 
@@ -5294,14 +5499,14 @@ namespace Mono.CSharp {
                        //
                        // Only base will allow this invocation to happen.
                        //
-                       if (is_base && method.IsAbstract){
+                       if (mg.IsBase && method.IsAbstract){
                                Report.Error (205, loc, "Cannot call an abstract base member: " +
                                              FullMethodDesc (method));
                                return null;
                        }
 
                        if (method.Name == "Finalize" && Arguments == null) {
-                               if (is_base)
+                               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");
@@ -5309,10 +5514,15 @@ namespace Mono.CSharp {
                        }
 
                        if ((method.Attributes & MethodAttributes.SpecialName) != 0){
-                               if (TypeManager.IsSpecialMethod (method))
-                                       Report.Error (571, loc, method.Name + ": can not call operator or accessor");
+                               if (TypeManager.LookupDeclSpace (method.DeclaringType) != null || TypeManager.IsSpecialMethod (method)) {
+                                       Report.Error (571, loc, TypeManager.CSharpSignature (method) + ": can not call operator or accessor");
+                                       return null;
+                               }
                        }
                        
+                       if (mg.InstanceExpression != null)
+                               mg.InstanceExpression.CheckMarshallByRefAccess (ec.ContainerType);
+
                        eclass = ExprClass.Value;
                        return this;
                }
@@ -5645,7 +5855,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)
@@ -5680,9 +5890,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);
                        }
 
@@ -5727,8 +5937,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;
                        }
@@ -5814,7 +6024,7 @@ namespace Mono.CSharp {
                        value_target = value;
                        value_target_set = true;
                        if (!(value_target is IMemoryLocation)){
-                               Error_UnexpectedKind ("variable");
+                               Error_UnexpectedKind ("variable", loc);
                                return false;
                        }
                        return true;
@@ -5863,8 +6073,11 @@ namespace Mono.CSharp {
                                return this;
                        }
                        
-                       type = ec.DeclSpace.ResolveType (RequestedType, false, loc);
+                       TypeExpr texpr = RequestedType.ResolveAsTypeTerminal (ec);
+                       if (texpr == null)
+                               return null;
                        
+                       type = texpr.Type;
                        if (type == null)
                                return null;
                        
@@ -5875,7 +6088,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;
                        }
@@ -5913,7 +6126,7 @@ namespace Mono.CSharp {
                                return null;
                        }
 
-                       bool is_struct = type.IsValueType && !type.IsGenericInstance;
+                       bool is_struct = type.IsValueType;
                        eclass = ExprClass.Value;
 
                        //
@@ -5934,7 +6147,7 @@ namespace Mono.CSharp {
                        
                        if (! (ml is MethodGroupExpr)){
                                if (!is_struct){
-                                       ml.Error_UnexpectedKind ("method group");
+                                       ml.Error_UnexpectedKind ("method group", loc);
                                        return null;
                                }
                        }
@@ -6395,13 +6608,14 @@ 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;
 
+                       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;
@@ -6464,7 +6678,7 @@ namespace Mono.CSharp {
                                                   AllBindingFlags, loc);
                                
                                if (!(ml is MethodGroupExpr)) {
-                                       ml.Error_UnexpectedKind ("method group");
+                                       ml.Error_UnexpectedKind ("method group", loc);
                                        return null;
                                }
                                
@@ -6900,7 +7114,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;
 
@@ -7104,7 +7318,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)
@@ -7115,11 +7329,12 @@ 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");
@@ -7184,22 +7399,20 @@ namespace Mono.CSharp {
                        if (!ec.InUnsafe) {
                                Report.Error (
                                        233, loc, "Sizeof may only be used in an unsafe context " +
-                                       "(consider using System.Runtime.InteropServices.Marshal.Sizeof");
+                                       "(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)
-                               return null;
+                       type_queried = texpr.Type;
 
                        CheckObsoleteAttribute (type_queried);
 
@@ -7269,6 +7482,8 @@ namespace Mono.CSharp {
                        return RootContext.LookupType (ec.DeclSpace, 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)
@@ -7294,7 +7509,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) {
@@ -7304,16 +7522,21 @@ namespace Mono.CSharp {
 
                                                object real_value = ((Constant) c.Expr).GetValue ();
 
-                                               return Constantify (real_value, fi.FieldType);
+                                               return Constantify (real_value, t);
                                        }
                                }
 
+                               // 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);
@@ -7350,7 +7573,7 @@ namespace Mono.CSharp {
                                        return exp;
                                }
 
-                               if (fi.FieldType.IsPointer && !ec.InUnsafe){
+                               if (t.IsPointer && !ec.InUnsafe){
                                        UnsafeError (loc);
                                        return null;
                                }
@@ -7478,9 +7701,13 @@ namespace Mono.CSharp {
 
                        if (expr is SimpleName){
                                SimpleName child_expr = (SimpleName) expr;
-                               string id = MemberName.MakeName (Identifier, args);
+                               string fqname = DeclSpace.MakeFQN (child_expr.Name, Identifier);
 
-                               Expression new_expr = new SimpleName (child_expr.Name, id, loc);
+                               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);
                        }
@@ -7496,7 +7723,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);
@@ -7638,12 +7865,11 @@ namespace Mono.CSharp {
                                        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);
+                                               if (args == null)
+                                                       return new TypeExpression (fully_qualified, loc);
+
+                                               ConstructedType ctype = new ConstructedType (fully_qualified, args, loc);
+                                               return ctype.ResolveAsTypeStep (ec);
                                        }
                                }
 
@@ -7667,10 +7893,12 @@ namespace Mono.CSharp {
                                return new_expr.ResolveAsTypeStep (ec);
                        }
 
-                       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) + ")");
@@ -7689,10 +7917,11 @@ namespace Mono.CSharp {
                        if (texpr == null)
                                return null;
 
-                       Type t = texpr.ResolveType (ec);
-                       if (t == null)
+                       texpr = texpr.ResolveAsTypeTerminal (ec);
+                       if (texpr == null)
                                return null;
 
+                       TypeArguments the_args = args;
                        if (TypeManager.HasGenericArguments (expr_type)) {
                                Type[] decl_args = TypeManager.GetTypeArguments (expr_type);
 
@@ -7703,11 +7932,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);
                        }
 
@@ -7985,8 +8214,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, a.Expr.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
@@ -8482,6 +8716,8 @@ namespace Mono.CSharp {
                                UnsafeError (loc);
                                return null;
                        }
+
+                       instance_expr.CheckMarshallByRefAccess (ec.ContainerType);
                        
                        eclass = ExprClass.IndexerAccess;
                        return this;
@@ -8552,6 +8788,8 @@ namespace Mono.CSharp {
                                }
                        }
                        
+                       instance_expr.CheckMarshallByRefAccess (ec.ContainerType);
+
                        eclass = ExprClass.IndexerAccess;
                        return this;
                }
@@ -8741,6 +8979,9 @@ namespace Mono.CSharp {
        ///   is needed (the `New' class).
        /// </summary>
        public class EmptyExpression : Expression {
+               public static readonly EmptyExpression Null = new EmptyExpression ();
+
+               // TODO: should be protected
                public EmptyExpression ()
                {
                        type = TypeManager.object_type;
@@ -8789,6 +9030,12 @@ namespace Mono.CSharp {
                        loc = l;
                }
 
+               public Expression Source {
+                       get {
+                               return source;
+                       }
+               }
+                       
                public override Expression DoResolve (EmitContext ec)
                {
                        //
@@ -8828,12 +9075,14 @@ namespace Mono.CSharp {
                        loc = l;
                }
 
-               public override TypeExpr DoResolveAsTypeStep (EmitContext ec)
+               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");
@@ -8883,27 +9132,15 @@ namespace Mono.CSharp {
                                //
                                // For now, fall back to the full lookup in that case.
                                //
-                               TypeExpr texpr = RootContext.LookupType (
-                                       ec.DeclSpace, cname, false, loc);
-
-                               if (texpr == null)
-                                       return null;
-
-                               type = texpr.ResolveType (ec);
+                               type = RootContext.LookupType (ec.DeclSpace, cname, false, loc);
                                if (type == null)
                                        return null;
                        }
 
-                       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;
                        }
-                       }
                        
                        eclass = ExprClass.Type;
                        return this;
@@ -9013,8 +9250,7 @@ namespace Mono.CSharp {
                        }
 
                        Constant c = count as Constant;
-                       // TODO: because we don't have property IsNegative
-                       if (c != null && c.ConvertToUInt () == null) {
+                       if (c != null && c.IsNegative) {
                                Report.Error (247, loc, "Cannot use a negative size with stackalloc");
                                return null;
                        }
@@ -9026,11 +9262,12 @@ namespace Mono.CSharp {
                                return null;
                        }
 
-                       otype = ec.DeclSpace.ResolveType (t, false, loc);
-
-                       if (otype == null)
+                       TypeExpr texpr = t.ResolveAsTypeTerminal (ec);
+                       if (texpr == null)
                                return null;
 
+                       otype = texpr.Type;
+
                        if (!TypeManager.VerifyUnManaged (otype, loc))
                                return null;