2 // nullable.cs: Nullable types support
4 // Authors: Martin Baulig (martin@ximian.com)
5 // Miguel de Icaza (miguel@ximian.com)
6 // Marek Safar (marek.safar@gmail.com)
8 // Dual licensed under the terms of the MIT X11 or GNU GPL
10 // Copyright 2001, 2002, 2003 Ximian, Inc (http://www.ximian.com)
11 // Copyright 2004-2008 Novell, Inc
17 using IKVM.Reflection.Emit;
19 using System.Reflection.Emit;
22 namespace Mono.CSharp.Nullable
24 public class NullableType : TypeExpr
28 public NullableType (TypeExpr underlying, Location l)
30 this.underlying = underlying;
33 eclass = ExprClass.Type;
36 public NullableType (TypeSpec type, Location loc)
37 : this (new TypeExpression (type, loc), loc)
40 protected override TypeExpr DoResolveAsTypeStep (IMemberContext ec)
42 var type = ec.Module.PredefinedTypes.Nullable.Resolve (loc);
46 TypeArguments args = new TypeArguments (underlying);
47 GenericTypeExpr ctype = new GenericTypeExpr (type, args, loc);
48 return ctype.ResolveAsTypeTerminal (ec, false);
52 static class NullableInfo
54 public static MethodSpec GetConstructor (TypeSpec nullableType)
56 return (MethodSpec) MemberCache.FindMember (nullableType,
57 MemberFilter.Constructor (ParametersCompiled.CreateFullyResolved (GetUnderlyingType (nullableType))), BindingRestriction.DeclaredOnly);
60 public static MethodSpec GetHasValue (TypeSpec nullableType)
62 return (MethodSpec) MemberCache.FindMember (nullableType,
63 MemberFilter.Method ("get_HasValue", 0, ParametersCompiled.EmptyReadOnlyParameters, null), BindingRestriction.None);
66 public static MethodSpec GetGetValueOrDefault (TypeSpec nullableType)
68 return (MethodSpec) MemberCache.FindMember (nullableType,
69 MemberFilter.Method ("GetValueOrDefault", 0, ParametersCompiled.EmptyReadOnlyParameters, null), BindingRestriction.None);
72 public static MethodSpec GetValue (TypeSpec nullableType)
74 return (MethodSpec) MemberCache.FindMember (nullableType,
75 MemberFilter.Method ("get_Value", 0, ParametersCompiled.EmptyReadOnlyParameters, null), BindingRestriction.None);
78 public static TypeSpec GetUnderlyingType (TypeSpec nullableType)
80 return ((InflatedTypeSpec) nullableType).TypeArguments[0];
84 public class Unwrap : Expression, IMemoryLocation, IAssignMethod
89 readonly bool useDefaultValue;
91 Unwrap (Expression expr, bool useDefaultValue)
94 this.loc = expr.Location;
95 this.useDefaultValue = useDefaultValue;
97 type = NullableInfo.GetUnderlyingType (expr.Type);
101 public static Expression Create (Expression expr)
104 // Avoid unwraping and wraping of same type
106 Wrap wrap = expr as Wrap;
110 return Create (expr, false);
113 public static Unwrap Create (Expression expr, bool useDefaultValue)
115 return new Unwrap (expr, useDefaultValue);
118 public override Expression CreateExpressionTree (ResolveContext ec)
120 return expr.CreateExpressionTree (ec);
123 protected override Expression DoResolve (ResolveContext ec)
128 public override Expression DoResolveLValue (ResolveContext ec, Expression right_side)
130 expr = expr.DoResolveLValue (ec, right_side);
134 public override void Emit (EmitContext ec)
138 Invocation.EmitCall (ec, this, NullableInfo.GetGetValueOrDefault (expr.Type), null, loc);
140 Invocation.EmitCall (ec, this, NullableInfo.GetValue (expr.Type), null, loc);
143 public void EmitCheck (EmitContext ec)
146 Invocation.EmitCall (ec, this, NullableInfo.GetHasValue (expr.Type), null, loc);
149 public override bool Equals (object obj)
151 Unwrap uw = obj as Unwrap;
152 return uw != null && expr.Equals (uw.expr);
155 public Expression Original {
161 public override int GetHashCode ()
163 return expr.GetHashCode ();
166 public override bool IsNull {
172 void Store (EmitContext ec)
174 if (expr is VariableReference)
181 LocalVariable.Store (ec);
184 public void Load (EmitContext ec)
186 if (expr is VariableReference)
189 LocalVariable.Emit (ec);
192 public override System.Linq.Expressions.Expression MakeExpression (BuilderContext ctx)
194 return expr.MakeExpression (ctx);
197 public void AddressOf (EmitContext ec, AddressOp mode)
199 IMemoryLocation ml = expr as VariableReference;
201 ml.AddressOf (ec, mode);
203 LocalVariable.AddressOf (ec, mode);
207 // Keeps result of non-variable expression
209 LocalTemporary LocalVariable {
212 temp = new LocalTemporary (expr.Type);
217 public void Emit (EmitContext ec, bool leave_copy)
225 public void EmitAssign (EmitContext ec, Expression source,
226 bool leave_copy, bool prepare_for_load)
228 InternalWrap wrap = new InternalWrap (source, expr.Type, loc);
229 ((IAssignMethod) expr).EmitAssign (ec, wrap, leave_copy, false);
232 class InternalWrap : Expression
234 public Expression expr;
236 public InternalWrap (Expression expr, TypeSpec type, Location loc)
242 eclass = ExprClass.Value;
245 public override Expression CreateExpressionTree (ResolveContext ec)
247 throw new NotSupportedException ("ET");
250 protected override Expression DoResolve (ResolveContext ec)
255 public override void Emit (EmitContext ec)
258 ec.Emit (OpCodes.Newobj, NullableInfo.GetConstructor (type));
264 // Calls get_Value method on nullable expression
266 public class UnwrapCall : CompositeExpression
268 public UnwrapCall (Expression expr)
273 protected override Expression DoResolve (ResolveContext rc)
278 type = NullableInfo.GetUnderlyingType (type);
283 public override void Emit (EmitContext ec)
285 Invocation.EmitCall (ec, Child, NullableInfo.GetValue (Child.Type), null, loc);
289 public class Wrap : TypeCast
291 private Wrap (Expression expr, TypeSpec type)
294 eclass = ExprClass.Value;
297 public override Expression CreateExpressionTree (ResolveContext ec)
299 TypeCast child_cast = child as TypeCast;
300 if (child_cast != null) {
302 return child_cast.CreateExpressionTree (ec);
305 return base.CreateExpressionTree (ec);
308 public static Expression Create (Expression expr, TypeSpec type)
311 // Avoid unwraping and wraping of the same type
313 Unwrap unwrap = expr as Unwrap;
314 if (unwrap != null && expr.Type == NullableInfo.GetUnderlyingType (type))
315 return unwrap.Original;
317 return new Wrap (expr, type);
320 public override void Emit (EmitContext ec)
323 ec.Emit (OpCodes.Newobj, NullableInfo.GetConstructor (type));
328 // Represents null literal lifted to nullable type
330 public class LiftedNull : NullConstant, IMemoryLocation
332 private LiftedNull (TypeSpec nullable_type, Location loc)
333 : base (nullable_type, loc)
335 eclass = ExprClass.Value;
338 public static Constant Create (TypeSpec nullable, Location loc)
340 return new LiftedNull (nullable, loc);
343 public static Constant CreateFromExpression (ResolveContext ec, Expression e)
345 ec.Report.Warning (458, 2, e.Location, "The result of the expression is always `null' of type `{0}'",
346 TypeManager.CSharpName (e.Type));
348 return ReducedExpression.Create (Create (e.Type, e.Location), e);
351 public override void Emit (EmitContext ec)
353 // TODO: generate less temporary variables
354 LocalTemporary value_target = new LocalTemporary (type);
356 value_target.AddressOf (ec, AddressOp.Store);
357 ec.Emit (OpCodes.Initobj, type);
358 value_target.Emit (ec);
361 public void AddressOf (EmitContext ec, AddressOp Mode)
363 LocalTemporary value_target = new LocalTemporary (type);
365 value_target.AddressOf (ec, AddressOp.Store);
366 ec.Emit (OpCodes.Initobj, type);
367 ((IMemoryLocation) value_target).AddressOf (ec, Mode);
372 // Generic lifting expression, supports all S/S? -> T/T? cases
374 public class Lifted : Expression, IMemoryLocation
376 Expression expr, null_value;
379 public Lifted (Expression expr, Unwrap unwrap, TypeSpec type)
382 this.unwrap = unwrap;
383 this.loc = expr.Location;
387 public Lifted (Expression expr, Expression unwrap, TypeSpec type)
388 : this (expr, unwrap as Unwrap, type)
392 public override Expression CreateExpressionTree (ResolveContext ec)
394 return expr.CreateExpressionTree (ec);
397 protected override Expression DoResolve (ResolveContext ec)
400 // It's null when lifting non-nullable type
402 if (unwrap == null) {
403 // S -> T? is wrap only
404 if (type.IsNullableType)
405 return Wrap.Create (expr, type);
407 // S -> T can be simplified
411 // Wrap target for T?
412 if (type.IsNullableType) {
413 expr = Wrap.Create (expr, type);
417 null_value = LiftedNull.Create (type, loc);
418 } else if (TypeManager.IsValueType (type)) {
419 null_value = LiftedNull.Create (type, loc);
421 null_value = new NullConstant (type, loc);
424 eclass = ExprClass.Value;
428 public override void Emit (EmitContext ec)
430 Label is_null_label = ec.DefineLabel ();
431 Label end_label = ec.DefineLabel ();
433 unwrap.EmitCheck (ec);
434 ec.Emit (OpCodes.Brfalse, is_null_label);
438 ec.Emit (OpCodes.Br, end_label);
439 ec.MarkLabel (is_null_label);
441 null_value.Emit (ec);
442 ec.MarkLabel (end_label);
445 public void AddressOf (EmitContext ec, AddressOp mode)
447 unwrap.AddressOf (ec, mode);
451 public class LiftedUnaryOperator : Unary, IMemoryLocation
454 Expression user_operator;
456 public LiftedUnaryOperator (Unary.Operator op, Expression expr, Location loc)
457 : base (op, expr, loc)
461 public void AddressOf (EmitContext ec, AddressOp mode)
463 unwrap.AddressOf (ec, mode);
466 public override Expression CreateExpressionTree (ResolveContext ec)
468 if (user_operator != null)
469 return user_operator.CreateExpressionTree (ec);
471 if (Oper == Operator.UnaryPlus)
472 return Expr.CreateExpressionTree (ec);
474 return base.CreateExpressionTree (ec);
477 protected override Expression DoResolve (ResolveContext ec)
479 unwrap = Unwrap.Create (Expr, false);
483 Expression res = base.ResolveOperator (ec, unwrap);
485 if (user_operator == null)
488 res = Expr = LiftExpression (ec, Expr);
494 eclass = ExprClass.Value;
499 public override void Emit (EmitContext ec)
501 Label is_null_label = ec.DefineLabel ();
502 Label end_label = ec.DefineLabel ();
504 unwrap.EmitCheck (ec);
505 ec.Emit (OpCodes.Brfalse, is_null_label);
507 if (user_operator != null) {
508 user_operator.Emit (ec);
510 EmitOperator (ec, NullableInfo.GetUnderlyingType (type));
513 ec.Emit (OpCodes.Newobj, NullableInfo.GetConstructor (type));
514 ec.Emit (OpCodes.Br_S, end_label);
516 ec.MarkLabel (is_null_label);
517 LiftedNull.Create (type, loc).Emit (ec);
519 ec.MarkLabel (end_label);
522 Expression LiftExpression (ResolveContext ec, Expression expr)
524 TypeExpr lifted_type = new NullableType (expr.Type, expr.Location);
525 lifted_type = lifted_type.ResolveAsTypeTerminal (ec, false);
526 if (lifted_type == null)
529 expr.Type = lifted_type.Type;
533 protected override Expression ResolveEnumOperator (ResolveContext ec, Expression expr, TypeSpec[] predefined)
535 expr = base.ResolveEnumOperator (ec, expr, predefined);
539 Expr = LiftExpression (ec, Expr);
540 return LiftExpression (ec, expr);
543 protected override Expression ResolveUserOperator (ResolveContext ec, Expression expr)
545 expr = base.ResolveUserOperator (ec, expr);
550 // When a user operator is of non-nullable type
552 if (Expr is Unwrap) {
553 user_operator = LiftExpression (ec, expr);
554 return user_operator;
561 public class LiftedBinaryOperator : Binary
563 Unwrap left_unwrap, right_unwrap;
564 Expression left_orig, right_orig;
565 Expression user_operator;
566 MethodSpec wrap_ctor;
568 public LiftedBinaryOperator (Binary.Operator op, Expression left, Expression right, Location loc)
569 : base (op, left, right, loc)
573 bool IsBitwiseBoolean {
575 return (Oper == Operator.BitwiseAnd || Oper == Operator.BitwiseOr) &&
576 ((left_unwrap != null && left_unwrap.Type.BuildinType == BuildinTypeSpec.Type.Bool) ||
577 (right_unwrap != null && right_unwrap.Type.BuildinType == BuildinTypeSpec.Type.Bool));
581 bool IsLeftNullLifted {
583 return (state & State.LeftNullLifted) != 0;
587 bool IsRightNullLifted {
589 return (state & State.RightNullLifted) != 0;
593 public override Expression CreateExpressionTree (ResolveContext ec)
595 if (user_operator != null)
596 return user_operator.CreateExpressionTree (ec);
598 return base.CreateExpressionTree (ec);
602 // CSC 2 has this behavior, it allows structs to be compared
603 // with the null literal *outside* of a generics context and
604 // inlines that as true or false.
606 Constant CreateNullConstant (ResolveContext ec, Expression expr)
608 // FIXME: Handle side effect constants
609 Constant c = new BoolConstant (ec.BuildinTypes, Oper == Operator.Inequality, loc);
611 if ((Oper & Operator.EqualityMask) != 0) {
612 ec.Report.Warning (472, 2, loc, "The result of comparing value type `{0}' with null is `{1}'",
613 TypeManager.CSharpName (expr.Type), c.GetValueAsLiteral ());
615 ec.Report.Warning (464, 2, loc, "The result of comparing type `{0}' with null is always `{1}'",
616 TypeManager.CSharpName (expr.Type), c.GetValueAsLiteral ());
619 return ReducedExpression.Create (c, this);
622 protected override Expression DoResolve (ResolveContext ec)
624 if ((Oper & Operator.LogicalMask) != 0) {
625 Error_OperatorCannotBeApplied (ec, left, right);
629 bool use_default_call = (Oper & (Operator.BitwiseMask | Operator.EqualityMask)) != 0;
631 if (left.Type.IsNullableType) {
632 left = left_unwrap = Unwrap.Create (left, use_default_call);
638 if (right.Type.IsNullableType) {
639 right = right_unwrap = Unwrap.Create (right, use_default_call);
645 // Some details are in 6.4.2, 7.2.7
646 // Arguments can be lifted for equal operators when the return type is bool and both
647 // arguments are of same type
649 if (left_orig is NullLiteral) {
651 state |= State.LeftNullLifted;
652 type = ec.BuildinTypes.Bool;
655 if (right_orig.IsNull) {
656 if ((Oper & Operator.ShiftMask) != 0)
657 right = new EmptyExpression (ec.BuildinTypes.Int);
661 state |= State.RightNullLifted;
662 type = ec.BuildinTypes.Bool;
665 eclass = ExprClass.Value;
666 return DoResolveCore (ec, left_orig, right_orig);
669 void EmitBitwiseBoolean (EmitContext ec)
671 Label load_left = ec.DefineLabel ();
672 Label load_right = ec.DefineLabel ();
673 Label end_label = ec.DefineLabel ();
675 // null & value, null | value
676 if (left_unwrap == null) {
677 left_unwrap = right_unwrap;
682 left_unwrap.Emit (ec);
683 ec.Emit (OpCodes.Brtrue_S, load_right);
685 // value & null, value | null
686 if (right_unwrap != null) {
687 right_unwrap.Emit (ec);
688 ec.Emit (OpCodes.Brtrue_S, load_left);
691 left_unwrap.EmitCheck (ec);
692 ec.Emit (OpCodes.Brfalse_S, load_right);
695 ec.MarkLabel (load_left);
697 if (Oper == Operator.BitwiseAnd) {
698 left_unwrap.Load (ec);
700 if (right_unwrap == null) {
702 if (right is EmptyConstantCast || right is EmptyCast)
703 ec.Emit (OpCodes.Newobj, NullableInfo.GetConstructor (type));
705 right_unwrap.Load (ec);
706 right_unwrap = left_unwrap;
709 ec.Emit (OpCodes.Br_S, end_label);
712 ec.MarkLabel (load_right);
713 if (right_unwrap == null) {
714 if (Oper == Operator.BitwiseAnd) {
716 if (right is EmptyConstantCast || right is EmptyCast)
717 ec.Emit (OpCodes.Newobj, NullableInfo.GetConstructor (type));
719 left_unwrap.Load (ec);
722 right_unwrap.Load (ec);
725 ec.MarkLabel (end_label);
729 // Emits optimized equality or inequality operator when possible
731 void EmitEquality (EmitContext ec)
734 // Either left or right is null
736 if (left_unwrap != null && (IsRightNullLifted || right.IsNull)) {
737 left_unwrap.EmitCheck (ec);
738 if (Oper == Binary.Operator.Equality) {
739 ec.Emit (OpCodes.Ldc_I4_0);
740 ec.Emit (OpCodes.Ceq);
745 if (right_unwrap != null && (IsLeftNullLifted || left.IsNull)) {
746 right_unwrap.EmitCheck (ec);
747 if (Oper == Binary.Operator.Equality) {
748 ec.Emit (OpCodes.Ldc_I4_0);
749 ec.Emit (OpCodes.Ceq);
754 Label dissimilar_label = ec.DefineLabel ();
755 Label end_label = ec.DefineLabel ();
757 if (user_operator != null) {
758 user_operator.Emit (ec);
759 ec.Emit (Oper == Operator.Equality ? OpCodes.Brfalse_S : OpCodes.Brtrue_S, dissimilar_label);
764 ec.Emit (OpCodes.Bne_Un_S, dissimilar_label);
767 if (left_unwrap != null)
768 left_unwrap.EmitCheck (ec);
770 if (right_unwrap != null)
771 right_unwrap.EmitCheck (ec);
773 if (left_unwrap != null && right_unwrap != null) {
774 if (Oper == Operator.Inequality)
775 ec.Emit (OpCodes.Xor);
777 ec.Emit (OpCodes.Ceq);
779 if (Oper == Operator.Inequality) {
780 ec.Emit (OpCodes.Ldc_I4_0);
781 ec.Emit (OpCodes.Ceq);
785 ec.Emit (OpCodes.Br_S, end_label);
787 ec.MarkLabel (dissimilar_label);
788 if (Oper == Operator.Inequality)
789 ec.Emit (OpCodes.Ldc_I4_1);
791 ec.Emit (OpCodes.Ldc_I4_0);
793 ec.MarkLabel (end_label);
796 public override void EmitBranchable (EmitContext ec, Label target, bool onTrue)
799 ec.Emit (onTrue ? OpCodes.Brtrue : OpCodes.Brfalse, target);
802 public override void Emit (EmitContext ec)
805 // Optimize same expression operation
807 if (right_unwrap != null && right.Equals (left))
808 right_unwrap = left_unwrap;
810 if (user_operator == null && IsBitwiseBoolean) {
811 EmitBitwiseBoolean (ec);
815 if ((Oper & Operator.EqualityMask) != 0) {
820 Label is_null_label = ec.DefineLabel ();
821 Label end_label = ec.DefineLabel ();
823 if (left_unwrap != null) {
824 left_unwrap.EmitCheck (ec);
825 ec.Emit (OpCodes.Brfalse, is_null_label);
829 // Don't emit HasValue check when left and right expressions are same
831 if (right_unwrap != null && !left.Equals (right)) {
832 right_unwrap.EmitCheck (ec);
833 ec.Emit (OpCodes.Brfalse, is_null_label);
836 EmitOperator (ec, left.Type);
838 if (wrap_ctor != null)
839 ec.Emit (OpCodes.Newobj, wrap_ctor);
841 ec.Emit (OpCodes.Br_S, end_label);
842 ec.MarkLabel (is_null_label);
844 if ((Oper & Operator.ComparisonMask) != 0) {
845 ec.Emit (OpCodes.Ldc_I4_0);
847 LiftedNull.Create (type, loc).Emit (ec);
850 ec.MarkLabel (end_label);
853 protected override void EmitOperator (EmitContext ec, TypeSpec l)
855 if (user_operator != null) {
856 user_operator.Emit (ec);
860 if (l.IsNullableType)
861 l = TypeManager.GetTypeArguments (l) [0];
863 base.EmitOperator (ec, l);
866 Expression LiftResult (ResolveContext ec, Expression res_expr)
868 TypeExpr lifted_type;
871 // Avoid double conversion
873 if (left_unwrap == null || IsLeftNullLifted || left_unwrap.Type != left.Type || (left_unwrap != null && IsRightNullLifted)) {
874 lifted_type = new NullableType (left.Type, loc);
875 lifted_type = lifted_type.ResolveAsTypeTerminal (ec, false);
876 if (lifted_type == null)
879 if (left is UserCast || left is TypeCast)
880 left.Type = lifted_type.Type;
882 left = EmptyCast.Create (left, lifted_type.Type);
885 if (left != right && (right_unwrap == null || IsRightNullLifted || right_unwrap.Type != right.Type || (right_unwrap != null && IsLeftNullLifted))) {
886 lifted_type = new NullableType (right.Type, loc);
887 lifted_type = lifted_type.ResolveAsTypeTerminal (ec, false);
888 if (lifted_type == null)
892 if (r is ReducedExpression)
893 r = ((ReducedExpression) r).OriginalExpression;
895 if (r is UserCast || r is TypeCast)
896 r.Type = lifted_type.Type;
898 right = EmptyCast.Create (right, lifted_type.Type);
901 if ((Oper & Operator.ComparisonMask) == 0) {
902 lifted_type = new NullableType (res_expr.Type, loc);
903 lifted_type = lifted_type.ResolveAsTypeTerminal (ec, false);
904 if (lifted_type == null)
907 wrap_ctor = NullableInfo.GetConstructor (lifted_type.Type);
908 type = res_expr.Type = lifted_type.Type;
911 if (IsLeftNullLifted) {
912 left = LiftedNull.Create (right.Type, left.Location);
915 // Special case for bool?, the result depends on both null right side and left side value
917 if ((Oper == Operator.BitwiseAnd || Oper == Operator.BitwiseOr) && NullableInfo.GetUnderlyingType (type).BuildinType == BuildinTypeSpec.Type.Bool) {
921 if ((Oper & (Operator.ArithmeticMask | Operator.ShiftMask | Operator.BitwiseMask)) != 0)
922 return LiftedNull.CreateFromExpression (ec, res_expr);
925 // Value types and null comparison
927 if (right_unwrap == null || (Oper & Operator.RelationalMask) != 0)
928 return CreateNullConstant (ec, right_orig);
931 if (IsRightNullLifted) {
932 right = LiftedNull.Create (left.Type, right.Location);
935 // Special case for bool?, the result depends on both null right side and left side value
937 if ((Oper == Operator.BitwiseAnd || Oper == Operator.BitwiseOr) && NullableInfo.GetUnderlyingType (type).BuildinType == BuildinTypeSpec.Type.Bool) {
941 if ((Oper & (Operator.ArithmeticMask | Operator.ShiftMask | Operator.BitwiseMask)) != 0)
942 return LiftedNull.CreateFromExpression (ec, res_expr);
945 // Value types and null comparison
947 if (left_unwrap == null || (Oper & Operator.RelationalMask) != 0)
948 return CreateNullConstant (ec, left_orig);
954 protected override Expression ResolveOperatorPredefined (ResolveContext ec, Binary.PredefinedOperator [] operators, bool primitives_only, TypeSpec enum_type)
956 Expression e = base.ResolveOperatorPredefined (ec, operators, primitives_only, enum_type);
958 if (e == this || enum_type != null)
959 return LiftResult (ec, e);
962 // 7.9.9 Equality operators and null
964 // The == and != operators permit one operand to be a value of a nullable type and
965 // the other to be the null literal, even if no predefined or user-defined operator
966 // (in unlifted or lifted form) exists for the operation.
968 if (e == null && (Oper & Operator.EqualityMask) != 0) {
969 if ((IsLeftNullLifted && right_unwrap != null) || (IsRightNullLifted && left_unwrap != null))
970 return LiftResult (ec, this);
976 protected override Expression ResolveUserOperator (ResolveContext ec, Expression left, Expression right)
979 // Try original types first for exact match without unwrapping
981 Expression expr = base.ResolveUserOperator (ec, left_orig, right_orig);
985 State orig_state = state;
988 // One side is a nullable type, try to match underlying types
990 if (left_unwrap != null || right_unwrap != null || (state & (State.RightNullLifted | State.LeftNullLifted)) != 0) {
991 expr = base.ResolveUserOperator (ec, left, right);
998 // Lift the result in the case it can be null and predefined or user operator
999 // result type is of a value type
1001 if (!TypeManager.IsValueType (expr.Type))
1004 if (state != orig_state)
1007 expr = LiftResult (ec, expr);
1008 if (expr is Constant)
1012 user_operator = expr;
1017 public class NullCoalescingOperator : Expression
1019 Expression left, right;
1022 public NullCoalescingOperator (Expression left, Expression right, Location loc)
1029 public override Expression CreateExpressionTree (ResolveContext ec)
1031 if (left is NullLiteral)
1032 ec.Report.Error (845, loc, "An expression tree cannot contain a coalescing operator with null left side");
1034 UserCast uc = left as UserCast;
1035 Expression conversion = null;
1039 Arguments c_args = new Arguments (2);
1040 c_args.Add (new Argument (uc.CreateExpressionTree (ec)));
1041 c_args.Add (new Argument (left.CreateExpressionTree (ec)));
1042 conversion = CreateExpressionFactoryCall (ec, "Lambda", c_args);
1045 Arguments args = new Arguments (3);
1046 args.Add (new Argument (left.CreateExpressionTree (ec)));
1047 args.Add (new Argument (right.CreateExpressionTree (ec)));
1048 if (conversion != null)
1049 args.Add (new Argument (conversion));
1051 return CreateExpressionFactoryCall (ec, "Coalesce", args);
1054 Expression ConvertExpression (ResolveContext ec)
1056 // TODO: ImplicitConversionExists should take care of this
1057 if (left.eclass == ExprClass.MethodGroup)
1060 TypeSpec ltype = left.Type;
1063 // If left is a nullable type and an implicit conversion exists from right to underlying type of left,
1064 // the result is underlying type of left
1066 if (ltype.IsNullableType) {
1067 unwrap = Unwrap.Create (left, false);
1072 // Reduce (left ?? null) to left
1075 return ReducedExpression.Create (left, this);
1077 if (Convert.ImplicitConversionExists (ec, right, unwrap.Type)) {
1082 // If right is a dynamic expression, the result type is dynamic
1084 if (right.Type.BuildinType == BuildinTypeSpec.Type.Dynamic) {
1087 // Need to box underlying value type
1088 left = Convert.ImplicitBoxingConversion (left, ltype, type);
1092 right = Convert.ImplicitConversion (ec, right, ltype, loc);
1096 } else if (TypeManager.IsReferenceType (ltype)) {
1097 if (Convert.ImplicitConversionExists (ec, right, ltype)) {
1099 // If right is a dynamic expression, the result type is dynamic
1101 if (right.Type.BuildinType == BuildinTypeSpec.Type.Dynamic) {
1107 // Reduce ("foo" ?? expr) to expression
1109 Constant lc = left as Constant;
1110 if (lc != null && !lc.IsDefaultValue)
1111 return ReducedExpression.Create (lc, this);
1114 // Reduce (left ?? null) to left OR (null-constant ?? right) to right
1116 if (right.IsNull || lc != null)
1117 return ReducedExpression.Create (lc != null ? right : left, this);
1119 right = Convert.ImplicitConversion (ec, right, ltype, loc);
1125 // Special case null ?? null
1127 if (ltype == right.Type) {
1135 TypeSpec rtype = right.Type;
1136 if (!Convert.ImplicitConversionExists (ec, unwrap != null ? unwrap : left, rtype) || right.eclass == ExprClass.MethodGroup)
1140 // Reduce (null ?? right) to right
1143 return ReducedExpression.Create (right, this).Resolve (ec);
1145 left = Convert.ImplicitConversion (ec, unwrap != null ? unwrap : left, rtype, loc);
1150 protected override Expression DoResolve (ResolveContext ec)
1152 left = left.Resolve (ec);
1153 right = right.Resolve (ec);
1155 if (left == null || right == null)
1158 eclass = ExprClass.Value;
1160 Expression e = ConvertExpression (ec);
1162 Binary.Error_OperatorCannotBeApplied (ec, left, right, "??", loc);
1169 public override void Emit (EmitContext ec)
1171 Label end_label = ec.DefineLabel ();
1173 if (unwrap != null) {
1174 Label is_null_label = ec.DefineLabel ();
1176 unwrap.EmitCheck (ec);
1177 ec.Emit (OpCodes.Brfalse, is_null_label);
1180 ec.Emit (OpCodes.Br, end_label);
1182 ec.MarkLabel (is_null_label);
1185 ec.MarkLabel (end_label);
1190 ec.Emit (OpCodes.Dup);
1192 // Only to make verifier happy
1193 if (left.Type.IsGenericParameter)
1194 ec.Emit (OpCodes.Box, left.Type);
1196 ec.Emit (OpCodes.Brtrue, end_label);
1198 ec.Emit (OpCodes.Pop);
1201 ec.MarkLabel (end_label);
1204 protected override void CloneTo (CloneContext clonectx, Expression t)
1206 NullCoalescingOperator target = (NullCoalescingOperator) t;
1208 target.left = left.Clone (clonectx);
1209 target.right = right.Clone (clonectx);
1213 public class LiftedUnaryMutator : ExpressionStatement
1215 public readonly UnaryMutator.Mode Mode;
1217 UnaryMutator underlying;
1220 public LiftedUnaryMutator (UnaryMutator.Mode mode, Expression expr, Location loc)
1227 public override Expression CreateExpressionTree (ResolveContext ec)
1229 return new SimpleAssign (this, this).CreateExpressionTree (ec);
1232 protected override Expression DoResolve (ResolveContext ec)
1234 expr = expr.Resolve (ec);
1238 unwrap = Unwrap.Create (expr, false);
1242 underlying = (UnaryMutator) new UnaryMutator (Mode, unwrap, loc).Resolve (ec);
1243 if (underlying == null)
1247 eclass = ExprClass.Value;
1252 void DoEmit (EmitContext ec, bool is_expr)
1254 Label is_null_label = ec.DefineLabel ();
1255 Label end_label = ec.DefineLabel ();
1257 unwrap.EmitCheck (ec);
1258 ec.Emit (OpCodes.Brfalse, is_null_label);
1261 underlying.Emit (ec);
1262 ec.Emit (OpCodes.Br_S, end_label);
1264 underlying.EmitStatement (ec);
1267 ec.MarkLabel (is_null_label);
1269 LiftedNull.Create (type, loc).Emit (ec);
1271 ec.MarkLabel (end_label);
1274 public override void Emit (EmitContext ec)
1279 public override void EmitStatement (EmitContext ec)