2008-06-26 Marek Safar <marek.safar@gmail.com>
[mono.git] / mcs / mcs / nullable.cs
index 20e625fc60fb6e4f6b94b4cfde52fc5ac9daf117..73f711a7e50394d00734d8c98ec2cc806d6582ce 100644 (file)
@@ -5,10 +5,10 @@
 //          Miguel de Icaza (miguel@ximian.com)
 //          Marek Safar (marek.safar@gmail.com)
 //
-// Licensed under the terms of the GNU GPL
+// Dual licensed under the terms of the MIT X11 or GNU GPL
 //
-// (C) 2001, 2002, 2003 Ximian, Inc (http://www.ximian.com)
-// (C) 2004 Novell, Inc
+// Copyright 2001, 2002, 2003 Ximian, Inc (http://www.ximian.com)
+// Copyright 2004-2008 Novell, Inc
 //
 
 using System;
@@ -34,14 +34,6 @@ namespace Mono.CSharp.Nullable
                        : this (new TypeExpression (type, loc), loc)
                { }
 
-               public override string Name {
-                       get { return underlying.ToString () + "?"; }
-               }
-
-               public override string FullName {
-                       get { return underlying.ToString () + "?"; }
-               }
-
                protected override TypeExpr DoResolveAsTypeStep (IResolveContext ec)
                {
                        TypeArguments args = new TypeArguments (loc);
@@ -88,44 +80,6 @@ namespace Mono.CSharp.Nullable
                        Constructor = type.GetConstructor (new Type[] { UnderlyingType });
                }
        }
-       
-       public class HasValue : Expression
-       {
-               Expression expr;
-               NullableInfo info;
-
-               private HasValue (Expression expr)
-               {
-                       this.expr = expr;
-               }
-               
-               public static Expression Create (Expression expr, EmitContext ec)
-               {
-                       return new HasValue (expr).Resolve (ec);
-               }
-
-               public override void Emit (EmitContext ec)
-               {
-                       IMemoryLocation memory_loc = expr as IMemoryLocation;
-                       if (memory_loc == null) {
-                               LocalTemporary temp = new LocalTemporary (expr.Type);
-                               expr.Emit (ec);
-                               temp.Store (ec);
-                               memory_loc = temp;
-                       }
-                       memory_loc.AddressOf (ec, AddressOp.LoadStore);
-                       ec.ig.EmitCall (OpCodes.Call, info.HasValue, null);
-               }
-
-               public override Expression DoResolve (EmitContext ec)
-               {
-                       this.info = new NullableInfo (expr.Type);
-
-                       type = TypeManager.bool_type;
-                       eclass = expr.eclass;
-                       return this;
-               }
-       }               
 
        public class Unwrap : Expression, IMemoryLocation, IAssignMethod
        {
@@ -133,7 +87,6 @@ namespace Mono.CSharp.Nullable
                NullableInfo info;
 
                LocalTemporary temp;
-               bool has_temp;
 
                protected Unwrap (Expression expr)
                {
@@ -156,8 +109,6 @@ namespace Mono.CSharp.Nullable
                        if (expr == null)
                                return null;
 
-                       temp = new LocalTemporary (expr.Type);
-
                        info = new NullableInfo (expr.Type);
                        type = info.UnderlyingType;
                        eclass = expr.eclass;
@@ -171,18 +122,21 @@ namespace Mono.CSharp.Nullable
 
                public override void Emit (EmitContext ec)
                {
+                       Store (ec);
                        AddressOf (ec, AddressOp.LoadStore);
                        ec.ig.EmitCall (OpCodes.Call, info.Value, null);
                }
 
                public void EmitCheck (EmitContext ec)
                {
+                       Store (ec);
                        AddressOf (ec, AddressOp.LoadStore);
                        ec.ig.EmitCall (OpCodes.Call, info.HasValue, null);
                }
 
                public void EmitGetValueOrDefault (EmitContext ec)
                {
+                       Store (ec);
                        AddressOf (ec, AddressOp.LoadStore);
                        ec.ig.EmitCall (OpCodes.Call, info.GetValueOrDefault, null);
                }
@@ -210,43 +164,50 @@ namespace Mono.CSharp.Nullable
                        }
                }
 
-               public void Store (EmitContext ec)
+               void Store (EmitContext ec)
                {
-                       create_temp (ec);
-               }
+                       if (expr is VariableReference)
+                               return;
 
-               void create_temp (EmitContext ec)
-               {
-                       if ((temp != null) && !has_temp) {
-                               expr.Emit (ec);
-                               temp.Store (ec);
-                               has_temp = true;
-                       }
+                       if (temp != null)
+                               return;
+
+                       expr.Emit (ec);
+                       LocalVariable.Store (ec);
                }
 
-               public void LoadTemporary (EmitContext ec)
+               public void Load (EmitContext ec)
                {
-                       temp.Emit (ec);
+                       if (expr is VariableReference)
+                               expr.Emit (ec);
+                       else
+                               LocalVariable.Emit (ec);
                }
 
                public void AddressOf (EmitContext ec, AddressOp mode)
                {
-                       create_temp (ec);
-                       if (temp != null)
-                               temp.AddressOf (ec, AddressOp.LoadStore);
+                       IMemoryLocation ml = expr as VariableReference;
+                       if (ml != null) 
+                               ml.AddressOf (ec, mode);
                        else
-                               ((IMemoryLocation) expr).AddressOf (ec, AddressOp.LoadStore);
+                               LocalVariable.AddressOf (ec, mode);
+               }
+
+               //
+               // Keeps result of non-variable expression
+               //
+               LocalTemporary LocalVariable {
+                       get {
+                               if (temp == null)
+                                       temp = new LocalTemporary (info.Type);
+                               return temp;
+                       }
                }
 
                public void Emit (EmitContext ec, bool leave_copy)
                {
-                       create_temp (ec);
-                       if (leave_copy) {
-                               if (temp != null)
-                                       temp.Emit (ec);
-                               else
-                                       expr.Emit (ec);
-                       }
+                       if (leave_copy)
+                               Load (ec);
 
                        Emit (ec);
                }
@@ -273,6 +234,11 @@ namespace Mono.CSharp.Nullable
                                eclass = ExprClass.Value;
                        }
 
+                       public override Expression CreateExpressionTree (EmitContext ec)
+                       {
+                               throw new NotSupportedException ("ET");
+                       }
+
                        public override Expression DoResolve (EmitContext ec)
                        {
                                return this;
@@ -286,7 +252,7 @@ namespace Mono.CSharp.Nullable
                }
        }
 
-       public class Wrap : EmptyCast
+       public class Wrap : TypeCast
        {
                readonly NullableInfo info;
 
@@ -297,8 +263,15 @@ namespace Mono.CSharp.Nullable
                        eclass = ExprClass.Value;
                }
 
-               public static new Expression Create (Expression expr, Type type)
+               public static Expression Create (Expression expr, Type type)
                {
+                       //
+                       // Avoid unwraping and wraping of the same type
+                       //
+                       Unwrap unwrap = expr as Unwrap;
+                       if (unwrap != null && TypeManager.IsEqual (expr.Type, TypeManager.GetTypeArguments (type) [0]))
+                               return unwrap.Original;
+               
                        return new Wrap (expr, type);
                }
                
@@ -309,19 +282,6 @@ namespace Mono.CSharp.Nullable
                }
        }
 
-       class LiftedWrap : Wrap
-       {
-               public LiftedWrap (Expression expr, Type type)
-                       : base (expr, type)
-               {
-               }
-
-               public override Expression CreateExpressionTree (EmitContext ec)
-               {
-                       return child.CreateExpressionTree (ec);
-               }
-       }
-
        //
        // Represents null literal lifted to nullable type
        //
@@ -338,6 +298,14 @@ namespace Mono.CSharp.Nullable
                        return new LiftedNull (nullable, loc);
                }
 
+               public static Expression CreateFromExpression (Expression e)
+               {
+                       Report.Warning (458, 2, e.Location, "The result of the expression is always `null' of type `{0}'",
+                               TypeManager.CSharpName (e.Type));
+
+                       return ReducedExpression.Create (Create (e.Type, e.Location), e);
+               }
+
                public override Expression CreateExpressionTree (EmitContext ec)
                {
                        ArrayList args = new ArrayList (2);
@@ -380,7 +348,10 @@ namespace Mono.CSharp.Nullable
                
                public override Expression CreateExpressionTree (EmitContext ec)
                {
-                       return underlying.CreateExpressionTree (ec);
+                       ArrayList args = new ArrayList (2);
+                       args.Add (new Argument (expr.CreateExpressionTree (ec)));
+                       args.Add (new Argument (new TypeOf (new TypeExpression (type, loc), loc)));
+                       return CreateExpressionFactoryCall ("Convert", args);
                }                       
 
                public override Expression DoResolve (EmitContext ec)
@@ -459,7 +430,10 @@ namespace Mono.CSharp.Nullable
                        Type type = TypeManager.GetTypeArguments (TargetType) [0];
 
                        if (IsUser) {
-                               return Convert.UserDefinedConversion (ec, unwrap, type, loc, IsExplicit);
+                               if (IsExplicit)
+                                       return Convert.ExplicitUserConversion (ec, unwrap, type, loc);
+                               else
+                                       return Convert.ImplicitUserConversion (ec, unwrap, type, loc);
                        } else {
                                if (IsExplicit)
                                        return Convert.ExplicitConversion (ec, unwrap, type, loc);
@@ -469,19 +443,119 @@ namespace Mono.CSharp.Nullable
                }
        }
 
-       public class LiftedUnaryOperator : Lifted
+       public class LiftedUnaryOperator : Unary, IMemoryLocation
        {
-               public readonly Unary.Operator Oper;
+               Unwrap unwrap;
+               Expression user_operator;
 
                public LiftedUnaryOperator (Unary.Operator op, Expression expr, Location loc)
-                       : base (expr, loc)
+                       : base (op, expr, loc)
                {
-                       this.Oper = op;
                }
 
-               protected override Expression ResolveUnderlying (Expression unwrap, EmitContext ec)
+               public void AddressOf (EmitContext ec, AddressOp mode)
+               {
+                       unwrap.AddressOf (ec, mode);
+               }
+
+               public override Expression CreateExpressionTree (EmitContext ec)
+               {
+                       if (user_operator != null)
+                               return user_operator.CreateExpressionTree (ec);
+
+                       if (Oper == Operator.UnaryPlus)
+                               return Expr.CreateExpressionTree (ec);
+
+                       return base.CreateExpressionTree (ec);
+               }
+
+               public override Expression DoResolve (EmitContext ec)
                {
-                       return new Unary (Oper, unwrap, loc).Resolve (ec);
+                       if (eclass != ExprClass.Invalid)
+                               return this;
+
+                       unwrap = Unwrap.Create (Expr, ec);
+                       if (unwrap == null)
+                               return null;
+
+                       Expression res = base.ResolveOperator (ec, unwrap);
+                       if (res != this) {
+                               if (user_operator == null)
+                                       return res;
+                       } else {
+                               res = Expr = LiftExpression (ec, Expr);
+                       }
+
+                       if (res == null)
+                               return null;
+
+                       eclass = ExprClass.Value;
+                       type = res.Type;
+                       return this;
+               }
+
+               public override void Emit (EmitContext ec)
+               {
+                       ILGenerator ig = ec.ig;
+                       Label is_null_label = ig.DefineLabel ();
+                       Label end_label = ig.DefineLabel ();
+
+                       unwrap.EmitCheck (ec);
+                       ig.Emit (OpCodes.Brfalse, is_null_label);
+
+                       NullableInfo ni = new NullableInfo (type);
+
+                       if (user_operator != null) {
+                               user_operator.Emit (ec);
+                       } else {
+                               EmitOperator (ec, ni.UnderlyingType);
+                       }
+
+                       ig.Emit (OpCodes.Newobj, ni.Constructor);
+                       ig.Emit (OpCodes.Br_S, end_label);
+
+                       ig.MarkLabel (is_null_label);
+                       LiftedNull.Create (type, loc).Emit (ec);
+
+                       ig.MarkLabel (end_label);
+               }
+
+               Expression LiftExpression (EmitContext ec, Expression expr)
+               {
+                       TypeExpr lifted_type = new NullableType (expr.Type, expr.Location);
+                       lifted_type = lifted_type.ResolveAsTypeTerminal (ec, false);
+                       if (lifted_type == null)
+                               return null;
+
+                       expr.Type = lifted_type.Type;
+                       return expr;
+               }
+
+               protected override Expression ResolveEnumOperator (EmitContext ec, Expression expr)
+               {
+                       expr = base.ResolveEnumOperator (ec, expr);
+                       if (expr == null)
+                               return null;
+
+                       Expr = LiftExpression (ec, Expr);
+                       return LiftExpression (ec, expr);
+               }
+
+               protected override Expression ResolveUserOperator (EmitContext ec, Expression expr)
+               {
+                       expr = base.ResolveUserOperator (ec, expr);
+                       if (expr == null)
+                               return null;
+
+                       //
+                       // When a user operator is of non-nullable type
+                       //
+                       if (Expr is Unwrap) {
+                               user_operator = LiftExpression (ec, expr);
+                               return user_operator;
+                       }
+
+                       return expr;
                }
        }
 
@@ -490,6 +564,8 @@ namespace Mono.CSharp.Nullable
                Unwrap left_unwrap, right_unwrap;
                bool left_null_lifted, right_null_lifted;
                Expression left_orig, right_orig;
+               Expression user_operator;
+               ConstructorInfo wrap_ctor;
 
                public LiftedBinaryOperator (Binary.Operator op, Expression left, Expression right,
                                             Location loc)
@@ -498,6 +574,14 @@ namespace Mono.CSharp.Nullable
                        this.loc = loc;
                }
 
+               public override Expression CreateExpressionTree (EmitContext ec)
+               {
+                       if (user_operator != null)
+                               return user_operator.CreateExpressionTree (ec);
+
+                       return base.CreateExpressionTree (ec);
+               }
+
                //
                // CSC 2 has this behavior, it allows structs to be compared
                // with the null literal *outside* of a generics context and
@@ -525,9 +609,7 @@ namespace Mono.CSharp.Nullable
                        if (eclass != ExprClass.Invalid)
                                return this;
 
-                       // TODO: How does it work with use-operators?
-                       if ((Oper == Binary.Operator.LogicalAnd) ||
-                           (Oper == Binary.Operator.LogicalOr)) {
+                       if ((Oper & Operator.LogicalMask) != 0) {
                                Error_OperatorCannotBeApplied (left, right);
                                return null;
                        }
@@ -546,28 +628,25 @@ namespace Mono.CSharp.Nullable
                                        return null;
                        }
 
+                       //
+                       // Some details are in 6.4.2, 7.2.7
+                       // Arguments can be lifted for equal operators when the return type is bool and both
+                       // arguments are of same type
+                       //      
                        if (left is NullLiteral) {
                                left = right;
                                left_null_lifted = true;
+                               type = TypeManager.bool_type;
                        }
 
                        if (right is NullLiteral) {
                                right = left;
                                right_null_lifted = true;
+                               type = TypeManager.bool_type;
                        }
 
                        eclass = ExprClass.Value;
-                       Expression expr = DoResolveCore (ec, left_orig, right_orig);
-                       if (expr != this || (Oper & Operator.ComparisonMask) != 0)
-                               return expr;
-
-                       TypeExpr target_type = new NullableType (type, loc);
-                       target_type = target_type.ResolveAsTypeTerminal (ec, false);
-                       if (target_type == null)
-                               return null;
-
-                       type = target_type.Type;
-                       return this;
+                       return DoResolveCore (ec, left_orig, right_orig);
                }
 
                void EmitBitwiseBoolean (EmitContext ec)
@@ -591,117 +670,93 @@ namespace Mono.CSharp.Nullable
                        ig.MarkLabel (load_left);
 
                        if (Oper == Operator.BitwiseAnd) {
-                               left_unwrap.LoadTemporary (ec);
+                               left_unwrap.Load (ec);
                        } else {
-                               right_unwrap.LoadTemporary (ec);
+                               right_unwrap.Load (ec);
                                right_unwrap = left_unwrap;
                        }
                        ig.Emit (OpCodes.Br_S, end_label);
 
                        // load right
                        ig.MarkLabel (load_right);
-                       right_unwrap.LoadTemporary (ec);
+                       right_unwrap.Load (ec);
 
                        ig.MarkLabel (end_label);
                }
 
-               void EmitEquality (EmitContext ec)
+               //
+               // Emits optimized equality or inequality operator when possible
+               //
+               bool EmitEquality (EmitContext ec)
                {
                        ILGenerator ig = ec.ig;
 
-                       Label both_have_value_label = ig.DefineLabel ();
-                       Label end_label = ig.DefineLabel ();
-
                        //
-                       // Both are nullable types
+                       // Either left or right is null
                        //
-                       if (left_unwrap != null && right_unwrap != null && !right.IsNull && !left.IsNull) {
-                               Label dissimilar_label = ig.DefineLabel ();
-
-                               left_unwrap.EmitGetValueOrDefault (ec);
-                               right_unwrap.EmitGetValueOrDefault (ec);
-                               ig.Emit (OpCodes.Bne_Un_S, dissimilar_label);
-
+                       if (left_unwrap != null && (right_null_lifted || right.IsNull)) {
                                left_unwrap.EmitCheck (ec);
-                               right_unwrap.EmitCheck (ec);
-                               if (Oper == Operator.Inequality)
-                                       ig.Emit (OpCodes.Xor);
-                               else
-                                       ig.Emit (OpCodes.Ceq);
-
-                               ig.Emit (OpCodes.Br_S, end_label);
-
-                               ig.MarkLabel (dissimilar_label);
-                               if (Oper == Operator.Inequality)
-                                       ig.Emit (OpCodes.Ldc_I4_1);
-                               else
+                               if (Oper == Binary.Operator.Equality) {
                                        ig.Emit (OpCodes.Ldc_I4_0);
-
-                               ig.MarkLabel (end_label);
-                               return;
+                                       ig.Emit (OpCodes.Ceq);
+                               }
+                               return true;
                        }
 
-                       //
-                       // Either left or right is nullable
-                       //
-                       if (left_unwrap != null) {
-                               left_unwrap.EmitCheck (ec);
-                               if (right.IsNull) {
-                                       if (Oper == Binary.Operator.Equality) {
-                                               ig.Emit (OpCodes.Ldc_I4_0);
-                                               ig.Emit (OpCodes.Ceq);
-                                       }
-                                       return;
-                               }
-                               ig.Emit (OpCodes.Brtrue_S, both_have_value_label);
-                       } else {
+                       if (right_unwrap != null && (left_null_lifted || left.IsNull)) {
                                right_unwrap.EmitCheck (ec);
-                               if (left.IsNull) {
-                                       if (Oper == Binary.Operator.Equality) {
-                                               ig.Emit (OpCodes.Ldc_I4_0);
-                                               ig.Emit (OpCodes.Ceq);
-                                       }
-                                       return;
+                               if (Oper == Binary.Operator.Equality) {
+                                       ig.Emit (OpCodes.Ldc_I4_0);
+                                       ig.Emit (OpCodes.Ceq);
                                }
-                               ig.Emit (OpCodes.Brtrue_S, both_have_value_label);
+                               return true;
                        }
 
-                       if (Oper == Binary.Operator.Equality)
-                               ig.Emit (OpCodes.Ldc_I4_0);
-                       else
-                               ig.Emit (OpCodes.Ldc_I4_1);
-                       ig.Emit (OpCodes.Br, end_label);
+                       if (user_operator != null)
+                               return false;
 
-                       ig.MarkLabel (both_have_value_label);
-                       EmitOperator (ec);
+                       Label dissimilar_label = ig.DefineLabel ();
+                       Label end_label = ig.DefineLabel ();
 
-                       ig.MarkLabel (end_label);
-               }
+                       if (left_unwrap != null)
+                               left_unwrap.EmitGetValueOrDefault (ec);
+                       else
+                               left.Emit (ec);
 
-               void EmitComparision (EmitContext ec)
-               {
-                       ILGenerator ig = ec.ig;
+                       if (right_unwrap != null)
+                               right_unwrap.EmitGetValueOrDefault (ec);
+                       else
+                               right.Emit (ec);
 
-                       Label is_null_label = ig.DefineLabel ();
-                       Label end_label = ig.DefineLabel ();
+                       ig.Emit (OpCodes.Bne_Un_S, dissimilar_label);
 
-                       if (left_unwrap != null) {
+                       if (left_unwrap != null)
                                left_unwrap.EmitCheck (ec);
-                               ig.Emit (OpCodes.Brfalse, is_null_label);
-                       }
-
-                       if (right_unwrap != null) {
+                       if (right_unwrap != null)
                                right_unwrap.EmitCheck (ec);
-                               ig.Emit (OpCodes.Brfalse, is_null_label);
+
+                       if (left_unwrap != null && right_unwrap != null) {
+                               if (Oper == Operator.Inequality)
+                                       ig.Emit (OpCodes.Xor);
+                               else
+                                       ig.Emit (OpCodes.Ceq);
+                       } else {
+                               if (Oper == Operator.Inequality) {
+                                       ig.Emit (OpCodes.Ldc_I4_0);
+                                       ig.Emit (OpCodes.Ceq);
+                               }
                        }
 
-                       EmitOperator (ec);
                        ig.Emit (OpCodes.Br_S, end_label);
 
-                       ig.MarkLabel (is_null_label);
-                       ig.Emit (OpCodes.Ldc_I4_0);
+                       ig.MarkLabel (dissimilar_label);
+                       if (Oper == Operator.Inequality)
+                               ig.Emit (OpCodes.Ldc_I4_1);
+                       else
+                               ig.Emit (OpCodes.Ldc_I4_0);
 
                        ig.MarkLabel (end_label);
+                       return true;
                }
                
                public override void EmitBranchable (EmitContext ec, Label target, bool onTrue)
@@ -712,24 +767,20 @@ namespace Mono.CSharp.Nullable
 
                public override void Emit (EmitContext ec)
                {
-                       if (left_unwrap != null)
-                               left_unwrap.Store (ec);
-                       if (right_unwrap != null)
-                               right_unwrap.Store (ec);
+                       //
+                       // Optimize same expression operation
+                       //
+                       if (right_unwrap != null && right.Equals (left))
+                               right_unwrap = left_unwrap;
 
-                       if (IsBitwiseBoolean) {
+                       if (user_operator == null && IsBitwiseBoolean) {
                                EmitBitwiseBoolean (ec);
                                return;
                        }
 
                        if ((Oper & Operator.EqualityMask) != 0) {
-                               EmitEquality (ec);
-                               return;
-                       }
-
-                       if ((Oper & Operator.ComparisonMask) != 0) {
-                               EmitComparision (ec);
-                               return;
+                               if (EmitEquality (ec))
+                                       return;
                        }
 
                        ILGenerator ig = ec.ig;
@@ -742,20 +793,47 @@ namespace Mono.CSharp.Nullable
                                ig.Emit (OpCodes.Brfalse, is_null_label);
                        }
 
-                       if (right_unwrap != null) {
+                       //
+                       // Don't emit HasValue check when left and right expressions are same
+                       //
+                       if (right_unwrap != null && !left.Equals (right)) {
                                right_unwrap.EmitCheck (ec);
                                ig.Emit (OpCodes.Brfalse, is_null_label);
                        }
 
-                       base.EmitOperator (ec);
+                       EmitOperator (ec, left.Type);
+
+                       if (wrap_ctor != null)
+                               ig.Emit (OpCodes.Newobj, wrap_ctor);
 
                        ig.Emit (OpCodes.Br_S, end_label);
                        ig.MarkLabel (is_null_label);
-                       LiftedNull.Create (type, loc).Emit (ec);
+
+                       if ((Oper & Operator.ComparisonMask) != 0) {
+                               if (Oper == Operator.Equality)
+                                       ig.Emit (OpCodes.Ldc_I4_1);
+                               else
+                                       ig.Emit (OpCodes.Ldc_I4_0);
+                       } else {
+                               LiftedNull.Create (type, loc).Emit (ec);
+                       }
 
                        ig.MarkLabel (end_label);
                }
 
+               protected override void EmitOperator (EmitContext ec, Type l)
+               {
+                       if (user_operator != null) {
+                               user_operator.Emit (ec);
+                               return;
+                       }
+
+                       if (TypeManager.IsNullableType (l))
+                               l = TypeManager.GetTypeArguments (l) [0];
+
+                       base.EmitOperator (ec, l);
+               }
+
                bool IsBitwiseBoolean {
                        get {
                                return (Oper & Operator.BitwiseMask) != 0 && left_unwrap != null && right_unwrap != null &&
@@ -776,7 +854,10 @@ namespace Mono.CSharp.Nullable
                                if (lifted_type == null)
                                        return null;
 
-                               left = EmptyCast.Create (left, lifted_type.Type);
+                               if (left is UserCast || left is TypeCast)
+                                       left.Type = lifted_type.Type;
+                               else
+                                       left = EmptyCast.Create (left, lifted_type.Type);
                        }
 
                        if (right_unwrap == null || right_null_lifted || !TypeManager.IsEqual (right_unwrap.Type, right.Type)) {
@@ -785,12 +866,28 @@ namespace Mono.CSharp.Nullable
                                if (lifted_type == null)
                                        return null;
 
-                               right = EmptyCast.Create (right, lifted_type.Type);
+                               if (right is UserCast || right is TypeCast)
+                                       right.Type = lifted_type.Type;
+                               else
+                                       right = EmptyCast.Create (right, lifted_type.Type);
+                       }
+
+                       if ((Oper & Operator.ComparisonMask) == 0) {
+                               lifted_type = new NullableType (res_expr.Type, loc);
+                               lifted_type = lifted_type.ResolveAsTypeTerminal (ec, false);
+                               if (lifted_type == null)
+                                       return null;
+
+                               wrap_ctor = new NullableInfo (lifted_type.Type).Constructor;
+                               type = res_expr.Type = lifted_type.Type;
                        }
 
                        if (left_null_lifted) {
                                left = LiftedNull.Create (right.Type, left.Location);
 
+                               if ((Oper & (Operator.ArithmeticMask | Operator.ShiftMask)) != 0)
+                                       return LiftedNull.CreateFromExpression (res_expr);
+
                                //
                                // Value types and null comparison
                                //
@@ -801,6 +898,9 @@ namespace Mono.CSharp.Nullable
                        if (right_null_lifted) {
                                right = LiftedNull.Create (left.Type, right.Location);
 
+                               if ((Oper & (Operator.ArithmeticMask | Operator.ShiftMask)) != 0)
+                                       return LiftedNull.CreateFromExpression (res_expr);
+
                                //
                                // Value types and null comparison
                                //
@@ -808,23 +908,14 @@ namespace Mono.CSharp.Nullable
                                        return CreateNullConstant (left_orig).Resolve (ec);
                        }
 
-                       // TODO: Handle bitwise bool 
-                       if ((Oper & Operator.ComparisonMask) != 0 || IsBitwiseBoolean)
-                               return res_expr;
-
-                       lifted_type = new NullableType (res_expr.Type, loc);
-                       lifted_type = lifted_type.ResolveAsTypeTerminal (ec, false);
-                       if (lifted_type == null)
-                               return null;
-
-                       return new LiftedWrap (res_expr, lifted_type.Type).Resolve (ec);
+                       return res_expr;
                }
 
-               protected override Expression ResolveOperatorPredefined (EmitContext ec, Binary.PredefinedOperator [] operators, bool primitives_only)
+               protected override Expression ResolveOperatorPredefined (EmitContext ec, Binary.PredefinedOperator [] operators, bool primitives_only, Type enum_type)
                {
-                       Expression e = base.ResolveOperatorPredefined (ec, operators, primitives_only);
+                       Expression e = base.ResolveOperatorPredefined (ec, operators, primitives_only, enum_type);
 
-                       if (e == this)
+                       if (e == this || enum_type != null)
                                return LiftResult (ec, e);
 
                        //
@@ -848,7 +939,13 @@ namespace Mono.CSharp.Nullable
                        if (expr == null)
                                return null;
 
-                       return LiftResult (ec, expr);
+                       expr = LiftResult (ec, expr);
+                       if (expr is Constant)
+                               return expr;
+
+                       type = expr.Type;
+                       user_operator = expr;
+                       return this;
                }
        }
 
@@ -866,6 +963,9 @@ namespace Mono.CSharp.Nullable
                
                public override Expression CreateExpressionTree (EmitContext ec)
                {
+                       if (left is NullLiteral)
+                               Report.Error (845, loc, "An expression tree cannot contain a coalescing operator with null left side");
+
                        UserCast uc = left as UserCast;
                        Expression conversion = null;
                        if (uc != null) {
@@ -899,54 +999,71 @@ namespace Mono.CSharp.Nullable
 
                        eclass = ExprClass.Value;
                        Type ltype = left.Type, rtype = right.Type;
-                       Expression expr;
-
-                       if (TypeManager.IsNullableType (ltype)) {
-                               NullableInfo info = new NullableInfo (ltype);
 
+                       //
+                       // If left is a nullable type and an implicit conversion exists from right to underlying type of left,
+                       // the result is underlying type of left
+                       //
+                       if (TypeManager.IsNullableType (ltype) && left.eclass != ExprClass.MethodGroup) {
                                unwrap = Unwrap.Create (left, ec);
                                if (unwrap == null)
                                        return null;
 
-                               expr = Convert.ImplicitConversion (ec, right, info.UnderlyingType, loc);
-                               if (expr != null) {
+                               if (Convert.ImplicitConversionExists (ec, right, unwrap.Type)) {
                                        left = unwrap;
-                                       right = expr;
-                                       type = expr.Type;
+                                       type = left.Type;
+                                       right = Convert.ImplicitConversion (ec, right, type, loc);
+                                       return this;
+                               }                       
+                       } else if (TypeManager.IsReferenceType (ltype) && right.eclass != ExprClass.MethodGroup) {
+                               if (Convert.ImplicitConversionExists (ec, right, ltype)) {
+                                       //
+                                       // Reduce (constant ?? expr) to constant
+                                       //
+                                       Constant lc = left as Constant;
+                                       if (lc != null && !lc.IsDefaultValue)
+                                               return new SideEffectConstant (lc, right, loc).Resolve (ec);
+
+                                       //
+                                       // Reduce (left ?? null) to left OR (null-constant ?? right) to right
+                                       //
+                                       if (right.IsNull || lc != null)
+                                               return ReducedExpression.Create (lc != null ? right : left, this).Resolve (ec);
+
+                                       right = Convert.ImplicitConversion (ec, right, ltype, loc);
+                                       type = left.Type;
                                        return this;
                                }
-                       } else if (!TypeManager.IsReferenceType (ltype)) {
-                               Binary.Error_OperatorCannotBeApplied (loc, "??", ltype, rtype);
+                       } else {
+                               Binary.Error_OperatorCannotBeApplied (left, right, "??", loc);
                                return null;
                        }
 
-                       expr = Convert.ImplicitConversion (ec, right, ltype, loc);
-                       if (expr != null) {
-                               type = expr.Type;
-                               right = expr;
-                               return this;
+                       if (!Convert.ImplicitConversionExists (ec, unwrap != null ? unwrap : left, rtype)) {
+                               Binary.Error_OperatorCannotBeApplied (left, right, "??", loc);
+                               return null;
                        }
 
-                       Expression left_null = unwrap != null ? unwrap : left;
-                       expr = Convert.ImplicitConversion (ec, left_null, rtype, loc);
-                       if (expr != null) {
-                               left = expr;
-                               type = rtype;
-                               return this;
-                       }
+                       //
+                       // Reduce (null ?? right) to right
+                       //
+                       if (left.IsNull)
+                               return ReducedExpression.Create (right, this).Resolve (ec);
 
-                       Binary.Error_OperatorCannotBeApplied (loc, "??", ltype, rtype);
-                       return null;
+                       left = Convert.ImplicitConversion (ec, unwrap != null ? unwrap : left, rtype, loc);
+                       type = rtype;
+                       return this;
                }
 
                public override void Emit (EmitContext ec)
                {
                        ILGenerator ig = ec.ig;
 
-                       Label is_null_label = ig.DefineLabel ();
                        Label end_label = ig.DefineLabel ();
 
                        if (unwrap != null) {
+                               Label is_null_label = ig.DefineLabel ();
+
                                unwrap.EmitCheck (ec);
                                ig.Emit (OpCodes.Brfalse, is_null_label);
 
@@ -957,19 +1074,20 @@ namespace Mono.CSharp.Nullable
                                right.Emit (ec);
 
                                ig.MarkLabel (end_label);
-                       } else {
-                               left.Emit (ec);
-                               ig.Emit (OpCodes.Dup);
-                               ig.Emit (OpCodes.Brtrue, end_label);
+                               return;
+                       }
 
-                               ig.MarkLabel (is_null_label);
+                       left.Emit (ec);
 
-                               ig.Emit (OpCodes.Pop);
-                               right.Emit (ec);
+                       ig.Emit (OpCodes.Dup);
+                       ig.Emit (OpCodes.Brtrue, end_label);
 
-                               ig.MarkLabel (end_label);
-                       }
+                       ig.Emit (OpCodes.Pop);
+                       right.Emit (ec);
+
+                       ig.MarkLabel (end_label);
                }
+
                protected override void CloneTo (CloneContext clonectx, Expression t)
                {
                        NullCoalescingOperator target = (NullCoalescingOperator) t;
@@ -982,7 +1100,7 @@ namespace Mono.CSharp.Nullable
        public class LiftedUnaryMutator : ExpressionStatement
        {
                public readonly UnaryMutator.Mode Mode;
-               Expression expr, null_value;
+               Expression expr;
                UnaryMutator underlying;
                Unwrap unwrap;
 
@@ -995,6 +1113,11 @@ namespace Mono.CSharp.Nullable
                        eclass = ExprClass.Value;
                }
 
+               public override Expression CreateExpressionTree (EmitContext ec)
+               {
+                       return new SimpleAssign (this, this).CreateExpressionTree (ec);
+               }
+
                public override Expression DoResolve (EmitContext ec)
                {
                        expr = expr.Resolve (ec);
@@ -1010,7 +1133,6 @@ namespace Mono.CSharp.Nullable
                                return null;
 
                        type = expr.Type;
-                       null_value = LiftedNull.Create (type, loc);
                        return this;
                }
 
@@ -1023,15 +1145,16 @@ namespace Mono.CSharp.Nullable
                        unwrap.EmitCheck (ec);
                        ig.Emit (OpCodes.Brfalse, is_null_label);
 
-                       if (is_expr)
+                       if (is_expr) {
                                underlying.Emit (ec);
-                       else
+                               ig.Emit (OpCodes.Br_S, end_label);
+                       } else {
                                underlying.EmitStatement (ec);
-                       ig.Emit (OpCodes.Br, end_label);
+                       }
 
                        ig.MarkLabel (is_null_label);
                        if (is_expr)
-                               null_value.Emit (ec);
+                               LiftedNull.Create (type, loc).Emit (ec);
 
                        ig.MarkLabel (end_label);
                }