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
12 // Copyright 2011 Xamarin Inc
16 using SLE = System.Linq.Expressions;
19 using IKVM.Reflection.Emit;
21 using System.Reflection.Emit;
24 namespace Mono.CSharp.Nullable
26 public class NullableType : TypeExpr
28 readonly TypeSpec underlying;
30 public NullableType (TypeSpec type, Location loc)
32 this.underlying = type;
36 public override TypeSpec ResolveAsType (IMemberContext ec)
38 eclass = ExprClass.Type;
40 var otype = ec.Module.PredefinedTypes.Nullable.Resolve ();
44 TypeArguments args = new TypeArguments (new TypeExpression (underlying, loc));
45 GenericTypeExpr ctype = new GenericTypeExpr (otype, args, loc);
47 type = ctype.ResolveAsType (ec);
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);
73 // Don't use unless really required for correctness, see Unwrap::Emit
75 public static MethodSpec GetValue (TypeSpec nullableType)
77 return (MethodSpec) MemberCache.FindMember (nullableType,
78 MemberFilter.Method ("get_Value", 0, ParametersCompiled.EmptyReadOnlyParameters, null), BindingRestriction.None);
81 public static TypeSpec GetUnderlyingType (TypeSpec nullableType)
83 return ((InflatedTypeSpec) nullableType).TypeArguments[0];
86 public static TypeSpec GetEnumUnderlyingType (ModuleContainer module, TypeSpec nullableEnum)
88 return module.PredefinedTypes.Nullable.TypeSpec.MakeGenericType (module,
89 new[] { EnumSpec.GetUnderlyingType (GetUnderlyingType (nullableEnum)) });
93 public class Unwrap : Expression, IMemoryLocation
98 Expression temp_field;
99 readonly bool useDefaultValue;
101 public Unwrap (Expression expr, bool useDefaultValue = true)
104 this.loc = expr.Location;
105 this.useDefaultValue = useDefaultValue;
107 type = NullableInfo.GetUnderlyingType (expr.Type);
108 eclass = expr.eclass;
111 public override bool ContainsEmitWithAwait ()
113 return expr.ContainsEmitWithAwait ();
117 public static Expression Create (Expression expr)
120 // Avoid unwraping and wraping of same type
122 Wrap wrap = expr as Wrap;
126 return Create (expr, false);
129 public static Expression CreateUnwrapped (Expression expr)
132 // Avoid unwraping and wraping of same type
134 Wrap wrap = expr as Wrap;
138 return Create (expr, true);
141 public static Unwrap Create (Expression expr, bool useDefaultValue)
143 return new Unwrap (expr, useDefaultValue);
146 public override Expression CreateExpressionTree (ResolveContext ec)
148 return expr.CreateExpressionTree (ec);
151 protected override Expression DoResolve (ResolveContext ec)
156 public override Expression DoResolveLValue (ResolveContext ec, Expression right_side)
158 expr = expr.DoResolveLValue (ec, right_side);
162 public override void Emit (EmitContext ec)
166 var call = new CallEmitter ();
167 call.InstanceExpression = this;
170 // Using GetGetValueOrDefault is prefered because JIT can possibly
171 // inline it whereas Value property contains a throw which is very
172 // unlikely to be inlined
175 call.EmitPredefined (ec, NullableInfo.GetGetValueOrDefault (expr.Type), null);
177 call.EmitPredefined (ec, NullableInfo.GetValue (expr.Type), null);
180 public void EmitCheck (EmitContext ec)
184 var call = new CallEmitter ();
185 call.InstanceExpression = this;
187 call.EmitPredefined (ec, NullableInfo.GetHasValue (expr.Type), null);
190 public override Expression EmitToField (EmitContext ec)
192 if (temp_field == null)
193 temp_field = this.expr.EmitToField (ec);
198 public override bool Equals (object obj)
200 Unwrap uw = obj as Unwrap;
201 return uw != null && expr.Equals (uw.expr);
204 public Expression Original {
210 public override int GetHashCode ()
212 return expr.GetHashCode ();
215 public override bool IsNull {
221 public void Store (EmitContext ec)
223 if (temp != null || temp_field != null)
226 if (expr is VariableReference)
230 LocalVariable.Store (ec);
233 public void Load (EmitContext ec)
235 if (temp_field != null)
236 temp_field.Emit (ec);
237 else if (expr is VariableReference)
240 LocalVariable.Emit (ec);
243 public override SLE.Expression MakeExpression (BuilderContext ctx)
245 return expr.MakeExpression (ctx);
248 public void AddressOf (EmitContext ec, AddressOp mode)
252 if (temp_field != null) {
253 ml = temp_field as IMemoryLocation;
255 var lt = new LocalTemporary (temp_field.Type);
256 temp_field.Emit (ec);
261 ml = expr as VariableReference;
265 ml.AddressOf (ec, mode);
267 LocalVariable.AddressOf (ec, mode);
271 // Keeps result of non-variable expression
273 LocalTemporary LocalVariable {
275 if (temp == null && temp_field == null)
276 temp = new LocalTemporary (expr.Type);
283 // Calls get_Value method on nullable expression
285 public class UnwrapCall : CompositeExpression
287 public UnwrapCall (Expression expr)
292 protected override Expression DoResolve (ResolveContext rc)
297 type = NullableInfo.GetUnderlyingType (type);
302 public override void Emit (EmitContext ec)
304 var call = new CallEmitter ();
305 call.InstanceExpression = Child;
306 call.EmitPredefined (ec, NullableInfo.GetValue (Child.Type), null);
310 public class Wrap : TypeCast
312 private Wrap (Expression expr, TypeSpec type)
315 eclass = ExprClass.Value;
318 public override Expression CreateExpressionTree (ResolveContext ec)
320 TypeCast child_cast = child as TypeCast;
321 if (child_cast != null) {
323 return child_cast.CreateExpressionTree (ec);
326 var user_cast = child as UserCast;
327 if (user_cast != null) {
329 return user_cast.CreateExpressionTree (ec);
332 return base.CreateExpressionTree (ec);
335 public static Expression Create (Expression expr, TypeSpec type)
338 // Avoid unwraping and wraping of the same type
340 Unwrap unwrap = expr as Unwrap;
341 if (unwrap != null && expr.Type == NullableInfo.GetUnderlyingType (type))
342 return unwrap.Original;
344 return new Wrap (expr, type);
347 public override void Emit (EmitContext ec)
350 ec.Emit (OpCodes.Newobj, NullableInfo.GetConstructor (type));
355 // Represents null literal lifted to nullable type
357 public class LiftedNull : NullConstant, IMemoryLocation
359 private LiftedNull (TypeSpec nullable_type, Location loc)
360 : base (nullable_type, loc)
362 eclass = ExprClass.Value;
365 public static Constant Create (TypeSpec nullable, Location loc)
367 return new LiftedNull (nullable, loc);
370 public static Constant CreateFromExpression (ResolveContext rc, Expression e)
372 if (!rc.HasSet (ResolveContext.Options.ExpressionTreeConversion)) {
373 rc.Report.Warning (458, 2, e.Location, "The result of the expression is always `null' of type `{0}'",
374 e.Type.GetSignatureForError ());
377 return ReducedExpression.Create (Create (e.Type, e.Location), e);
380 public override void Emit (EmitContext ec)
382 // TODO: generate less temporary variables
383 LocalTemporary value_target = new LocalTemporary (type);
385 value_target.AddressOf (ec, AddressOp.Store);
386 ec.Emit (OpCodes.Initobj, type);
387 value_target.Emit (ec);
388 value_target.Release (ec);
391 public void AddressOf (EmitContext ec, AddressOp Mode)
393 LocalTemporary value_target = new LocalTemporary (type);
395 value_target.AddressOf (ec, AddressOp.Store);
396 ec.Emit (OpCodes.Initobj, type);
397 value_target.AddressOf (ec, Mode);
402 // Generic lifting expression, supports all S/S? -> T/T? cases
404 public class LiftedConversion : Expression, IMemoryLocation
406 Expression expr, null_value;
409 public LiftedConversion (Expression expr, Unwrap unwrap, TypeSpec type)
412 this.unwrap = unwrap;
413 this.loc = expr.Location;
417 public LiftedConversion (Expression expr, Expression unwrap, TypeSpec type)
418 : this (expr, unwrap as Unwrap, type)
422 public override bool ContainsEmitWithAwait ()
424 return unwrap.ContainsEmitWithAwait ();
427 public override Expression CreateExpressionTree (ResolveContext ec)
429 return expr.CreateExpressionTree (ec);
432 protected override Expression DoResolve (ResolveContext ec)
435 // It's null when lifting non-nullable type
437 if (unwrap == null) {
438 // S -> T? is wrap only
439 if (type.IsNullableType)
440 return Wrap.Create (expr, type);
442 // S -> T can be simplified
446 // Wrap target for T?
447 if (type.IsNullableType) {
448 if (!expr.Type.IsNullableType) {
449 expr = Wrap.Create (expr, type);
454 null_value = LiftedNull.Create (type, loc);
455 } else if (TypeSpec.IsValueType (type)) {
456 null_value = LiftedNull.Create (type, loc);
458 null_value = new NullConstant (type, loc);
461 eclass = ExprClass.Value;
465 public override void Emit (EmitContext ec)
467 Label is_null_label = ec.DefineLabel ();
468 Label end_label = ec.DefineLabel ();
470 unwrap.EmitCheck (ec);
471 ec.Emit (OpCodes.Brfalse, is_null_label);
475 ec.Emit (OpCodes.Br, end_label);
476 ec.MarkLabel (is_null_label);
478 null_value.Emit (ec);
480 ec.MarkLabel (end_label);
483 public void AddressOf (EmitContext ec, AddressOp mode)
485 unwrap.AddressOf (ec, mode);
489 public class LiftedUnaryOperator : Unary, IMemoryLocation
492 Expression user_operator;
494 public LiftedUnaryOperator (Unary.Operator op, Expression expr, Location loc)
495 : base (op, expr, loc)
499 public void AddressOf (EmitContext ec, AddressOp mode)
501 unwrap.AddressOf (ec, mode);
504 public override Expression CreateExpressionTree (ResolveContext ec)
506 if (user_operator != null)
507 return user_operator.CreateExpressionTree (ec);
509 if (Oper == Operator.UnaryPlus)
510 return Expr.CreateExpressionTree (ec);
512 return base.CreateExpressionTree (ec);
515 protected override Expression DoResolve (ResolveContext ec)
517 unwrap = Unwrap.Create (Expr, false);
521 Expression res = base.ResolveOperator (ec, unwrap);
523 if (user_operator == null)
526 res = Expr = LiftExpression (ec, Expr);
532 eclass = ExprClass.Value;
537 public override void Emit (EmitContext ec)
539 Label is_null_label = ec.DefineLabel ();
540 Label end_label = ec.DefineLabel ();
542 unwrap.EmitCheck (ec);
543 ec.Emit (OpCodes.Brfalse, is_null_label);
545 if (user_operator != null) {
546 user_operator.Emit (ec);
548 EmitOperator (ec, NullableInfo.GetUnderlyingType (type));
551 ec.Emit (OpCodes.Newobj, NullableInfo.GetConstructor (type));
552 ec.Emit (OpCodes.Br_S, end_label);
554 ec.MarkLabel (is_null_label);
555 LiftedNull.Create (type, loc).Emit (ec);
557 ec.MarkLabel (end_label);
560 static Expression LiftExpression (ResolveContext ec, Expression expr)
562 var lifted_type = new NullableType (expr.Type, expr.Location);
563 if (lifted_type.ResolveAsType (ec) == null)
566 expr.Type = lifted_type.Type;
570 protected override Expression ResolveEnumOperator (ResolveContext ec, Expression expr, TypeSpec[] predefined)
572 expr = base.ResolveEnumOperator (ec, expr, predefined);
576 Expr = LiftExpression (ec, Expr);
577 return LiftExpression (ec, expr);
580 protected override Expression ResolveUserOperator (ResolveContext ec, Expression expr)
582 expr = base.ResolveUserOperator (ec, expr);
587 // When a user operator is of non-nullable type
589 if (Expr is Unwrap) {
590 user_operator = LiftExpression (ec, expr);
591 return user_operator;
599 // Lifted version of binary operators
601 class LiftedBinaryOperator : Expression
603 public LiftedBinaryOperator (Binary b)
606 this.loc = b.Location;
609 public Binary Binary { get; private set; }
611 public Expression Left { get; set; }
613 public Expression Right { get; set; }
615 public Unwrap UnwrapLeft { get; set; }
617 public Unwrap UnwrapRight { get; set; }
619 public MethodSpec UserOperator { get; set; }
621 bool IsBitwiseBoolean {
623 return (Binary.Oper == Binary.Operator.BitwiseAnd || Binary.Oper == Binary.Operator.BitwiseOr) &&
624 ((UnwrapLeft != null && UnwrapLeft.Type.BuiltinType == BuiltinTypeSpec.Type.Bool) ||
625 (UnwrapRight != null && UnwrapRight.Type.BuiltinType == BuiltinTypeSpec.Type.Bool));
629 public override bool ContainsEmitWithAwait ()
631 return Left.ContainsEmitWithAwait () || Right.ContainsEmitWithAwait ();
634 public override Expression CreateExpressionTree (ResolveContext rc)
636 if (UserOperator != null) {
637 Arguments args = new Arguments (2);
638 args.Add (new Argument (Binary.Left));
639 args.Add (new Argument (Binary.Right));
641 var method = new UserOperatorCall (UserOperator, args, Binary.CreateExpressionTree, loc);
642 return method.CreateExpressionTree (rc);
645 return Binary.CreateExpressionTree (rc);
648 protected override Expression DoResolve (ResolveContext rc)
650 if (rc.IsRuntimeBinder) {
651 if (UnwrapLeft == null && !Left.Type.IsNullableType)
652 Left = Wrap.Create (Left, rc.Module.PredefinedTypes.Nullable.TypeSpec.MakeGenericType (rc.Module, new[] { Left.Type }));
654 if (UnwrapRight == null && !Right.Type.IsNullableType)
655 Right = Wrap.Create (Right, rc.Module.PredefinedTypes.Nullable.TypeSpec.MakeGenericType (rc.Module, new[] { Right.Type }));
657 if (UnwrapLeft == null && Left != null && Left.Type.IsNullableType) {
658 Left = Unwrap.CreateUnwrapped (Left);
659 UnwrapLeft = Left as Unwrap;
662 if (UnwrapRight == null && Right != null && Right.Type.IsNullableType) {
663 Right = Unwrap.CreateUnwrapped (Right);
664 UnwrapRight = Right as Unwrap;
669 eclass = Binary.eclass;
674 public override void Emit (EmitContext ec)
676 if (IsBitwiseBoolean && UserOperator == null) {
677 EmitBitwiseBoolean (ec);
681 if ((Binary.Oper & Binary.Operator.EqualityMask) != 0) {
686 Label is_null_label = ec.DefineLabel ();
687 Label end_label = ec.DefineLabel ();
689 if (ec.HasSet (BuilderContext.Options.AsyncBody) && Right.ContainsEmitWithAwait ()) {
690 Left = Left.EmitToField (ec);
691 Right = Right.EmitToField (ec);
694 if (UnwrapLeft != null) {
695 UnwrapLeft.EmitCheck (ec);
699 // Don't emit HasValue check when left and right expressions are same
701 if (UnwrapRight != null && !Binary.Left.Equals (Binary.Right)) {
702 UnwrapRight.EmitCheck (ec);
703 if (UnwrapLeft != null) {
704 ec.Emit (OpCodes.And);
708 ec.Emit (OpCodes.Brfalse, is_null_label);
710 if (UserOperator != null) {
711 var args = new Arguments (2);
712 args.Add (new Argument (Left));
713 args.Add (new Argument (Right));
715 var call = new CallEmitter ();
716 call.EmitPredefined (ec, UserOperator, args);
718 Binary.EmitOperator (ec, Left, Right);
722 // Wrap the result when the operator return type is nullable type
724 if (type.IsNullableType)
725 ec.Emit (OpCodes.Newobj, NullableInfo.GetConstructor (type));
727 ec.Emit (OpCodes.Br_S, end_label);
728 ec.MarkLabel (is_null_label);
730 if ((Binary.Oper & Binary.Operator.ComparisonMask) != 0) {
733 LiftedNull.Create (type, loc).Emit (ec);
736 ec.MarkLabel (end_label);
739 void EmitBitwiseBoolean (EmitContext ec)
741 Label load_left = ec.DefineLabel ();
742 Label load_right = ec.DefineLabel ();
743 Label end_label = ec.DefineLabel ();
744 Label is_null_label = ec.DefineLabel ();
746 bool or = Binary.Oper == Binary.Operator.BitwiseOr;
749 // Both operands are bool? types
751 if (UnwrapLeft != null && UnwrapRight != null) {
752 if (ec.HasSet (BuilderContext.Options.AsyncBody) && Binary.Right.ContainsEmitWithAwait ()) {
753 Left = Left.EmitToField (ec);
754 Right = Right.EmitToField (ec);
758 ec.Emit (OpCodes.Brtrue_S, load_right);
761 ec.Emit (OpCodes.Brtrue_S, load_left);
763 UnwrapLeft.EmitCheck (ec);
764 ec.Emit (OpCodes.Brfalse_S, load_right);
767 ec.MarkLabel (load_left);
769 UnwrapRight.Load (ec);
771 UnwrapLeft.Load (ec);
773 ec.Emit (OpCodes.Br_S, end_label);
776 ec.MarkLabel (load_right);
778 UnwrapLeft.Load (ec);
780 UnwrapRight.Load (ec);
782 ec.MarkLabel (end_label);
787 // Faster version when one operand is bool
789 if (UnwrapLeft == null) {
793 // Optimizes remaining (false & bool?), (true | bool?) which are not easy to handle
794 // in binary expression reduction
796 var c = Left as BoolConstant;
798 // Keep evaluation order
799 UnwrapRight.Store (ec);
801 ec.EmitInt (or ? 1 : 0);
802 ec.Emit (OpCodes.Newobj, NullableInfo.GetConstructor (type));
803 } else if (Left.IsNull) {
804 UnwrapRight.Emit (ec);
805 ec.Emit (or ? OpCodes.Brfalse_S : OpCodes.Brtrue_S, is_null_label);
807 UnwrapRight.Load (ec);
808 ec.Emit (OpCodes.Br_S, end_label);
810 ec.MarkLabel (is_null_label);
811 LiftedNull.Create (type, loc).Emit (ec);
814 ec.Emit (or ? OpCodes.Brfalse_S : OpCodes.Brtrue_S, load_right);
816 ec.EmitInt (or ? 1 : 0);
817 ec.Emit (OpCodes.Newobj, NullableInfo.GetConstructor (type));
819 ec.Emit (OpCodes.Br_S, end_label);
821 ec.MarkLabel (load_right);
822 UnwrapRight.Original.Emit (ec);
828 // Keep left-right evaluation order
829 UnwrapLeft.Store (ec);
832 // Optimizes remaining (bool? & false), (bool? | true) which are not easy to handle
833 // in binary expression reduction
835 var c = Right as BoolConstant;
837 ec.EmitInt (or ? 1 : 0);
838 ec.Emit (OpCodes.Newobj, NullableInfo.GetConstructor (type));
839 } else if (Right.IsNull) {
840 UnwrapLeft.Emit (ec);
841 ec.Emit (or ? OpCodes.Brfalse_S : OpCodes.Brtrue_S, is_null_label);
843 UnwrapLeft.Load (ec);
844 ec.Emit (OpCodes.Br_S, end_label);
846 ec.MarkLabel (is_null_label);
847 LiftedNull.Create (type, loc).Emit (ec);
850 ec.Emit (or ? OpCodes.Brfalse_S : OpCodes.Brtrue_S, load_right);
852 ec.EmitInt (or ? 1 : 0);
853 ec.Emit (OpCodes.Newobj, NullableInfo.GetConstructor (type));
855 ec.Emit (OpCodes.Br_S, end_label);
857 ec.MarkLabel (load_right);
859 UnwrapLeft.Load (ec);
863 ec.MarkLabel (end_label);
867 // Emits optimized equality or inequality operator when possible
869 void EmitEquality (EmitContext ec)
872 // Either left or right is null
874 if (UnwrapLeft != null && Binary.Right.IsNull) { // TODO: Optimize for EmitBranchable
876 // left.HasValue == false
878 UnwrapLeft.EmitCheck (ec);
879 if (Binary.Oper == Binary.Operator.Equality) {
881 ec.Emit (OpCodes.Ceq);
886 if (UnwrapRight != null && Binary.Left.IsNull) {
888 // right.HasValue == false
890 UnwrapRight.EmitCheck (ec);
891 if (Binary.Oper == Binary.Operator.Equality) {
893 ec.Emit (OpCodes.Ceq);
898 Label dissimilar_label = ec.DefineLabel ();
899 Label end_label = ec.DefineLabel ();
901 if (UserOperator != null) {
904 if (UnwrapLeft != null) {
905 UnwrapLeft.EmitCheck (ec);
907 // Keep evaluation order same
908 if (!(Left is VariableReference)) {
910 var lt = new LocalTemporary (Left.Type);
916 if (UnwrapRight != null) {
917 UnwrapRight.EmitCheck (ec);
919 if (UnwrapLeft != null) {
920 ec.Emit (OpCodes.Bne_Un, dissimilar_label);
922 Label compare_label = ec.DefineLabel ();
923 UnwrapLeft.EmitCheck (ec);
924 ec.Emit (OpCodes.Brtrue, compare_label);
926 if (Binary.Oper == Binary.Operator.Equality)
931 ec.Emit (OpCodes.Br, end_label);
933 ec.MarkLabel (compare_label);
935 ec.Emit (OpCodes.Brfalse, dissimilar_label);
938 ec.Emit (OpCodes.Brfalse, dissimilar_label);
941 var args = new Arguments (2);
942 args.Add (new Argument (left));
943 args.Add (new Argument (Right));
945 var call = new CallEmitter ();
946 call.EmitPredefined (ec, UserOperator, args);
948 if (ec.HasSet (BuilderContext.Options.AsyncBody) && Binary.Right.ContainsEmitWithAwait ()) {
949 Left = Left.EmitToField (ec);
950 Right = Right.EmitToField (ec);
954 // Emit underlying value comparison first.
956 // For this code: int? a = 1; bool b = a == 1;
958 // We emit something similar to this. Expressions with side effects have local
959 // variable created by Unwrap expression
961 // left.GetValueOrDefault ()
963 // bne.un.s dissimilar_label
974 ec.Emit (OpCodes.Bne_Un_S, dissimilar_label);
977 // Check both left and right expressions for Unwrap call in which
978 // case we need to run get_HasValue() check because the type is
979 // nullable and could have null value
981 if (UnwrapLeft != null)
982 UnwrapLeft.EmitCheck (ec);
984 if (UnwrapRight != null)
985 UnwrapRight.EmitCheck (ec);
987 if (UnwrapLeft != null && UnwrapRight != null) {
988 if (Binary.Oper == Binary.Operator.Inequality)
989 ec.Emit (OpCodes.Xor);
991 ec.Emit (OpCodes.Ceq);
993 if (Binary.Oper == Binary.Operator.Inequality) {
995 ec.Emit (OpCodes.Ceq);
1000 ec.Emit (OpCodes.Br_S, end_label);
1002 ec.MarkLabel (dissimilar_label);
1003 if (Binary.Oper == Binary.Operator.Inequality)
1008 ec.MarkLabel (end_label);
1011 public override SLE.Expression MakeExpression (BuilderContext ctx)
1013 return Binary.MakeExpression (ctx, Left, Right);
1017 public class NullCoalescingOperator : Expression
1019 Expression left, right;
1022 public NullCoalescingOperator (Expression left, Expression right)
1026 this.loc = left.Location;
1029 public Expression LeftExpression {
1035 public Expression RightExpression {
1041 public override Expression CreateExpressionTree (ResolveContext ec)
1043 if (left is NullLiteral)
1044 ec.Report.Error (845, loc, "An expression tree cannot contain a coalescing operator with null left side");
1046 UserCast uc = left as UserCast;
1047 Expression conversion = null;
1051 Arguments c_args = new Arguments (2);
1052 c_args.Add (new Argument (uc.CreateExpressionTree (ec)));
1053 c_args.Add (new Argument (left.CreateExpressionTree (ec)));
1054 conversion = CreateExpressionFactoryCall (ec, "Lambda", c_args);
1057 Arguments args = new Arguments (3);
1058 args.Add (new Argument (left.CreateExpressionTree (ec)));
1059 args.Add (new Argument (right.CreateExpressionTree (ec)));
1060 if (conversion != null)
1061 args.Add (new Argument (conversion));
1063 return CreateExpressionFactoryCall (ec, "Coalesce", args);
1066 Expression ConvertExpression (ResolveContext ec)
1068 // TODO: ImplicitConversionExists should take care of this
1069 if (left.eclass == ExprClass.MethodGroup)
1072 TypeSpec ltype = left.Type;
1075 // If left is a nullable type and an implicit conversion exists from right to underlying type of left,
1076 // the result is underlying type of left
1078 if (ltype.IsNullableType) {
1079 unwrap = Unwrap.Create (left, false);
1084 // Reduce (left ?? null) to left
1087 return ReducedExpression.Create (left, this);
1089 if (Convert.ImplicitConversionExists (ec, right, unwrap.Type)) {
1094 // If right is a dynamic expression, the result type is dynamic
1096 if (right.Type.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
1099 // Need to box underlying value type
1100 left = Convert.ImplicitBoxingConversion (left, ltype, type);
1104 right = Convert.ImplicitConversion (ec, right, ltype, loc);
1108 } else if (TypeSpec.IsReferenceType (ltype)) {
1109 if (Convert.ImplicitConversionExists (ec, right, ltype)) {
1111 // If right is a dynamic expression, the result type is dynamic
1113 if (right.Type.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
1119 // Reduce ("foo" ?? expr) to expression
1121 Constant lc = left as Constant;
1122 if (lc != null && !lc.IsDefaultValue)
1123 return ReducedExpression.Create (lc, this);
1126 // Reduce (left ?? null) to left OR (null-constant ?? right) to right
1128 if (right.IsNull || lc != null)
1129 return ReducedExpression.Create (lc != null ? right : left, this);
1131 right = Convert.ImplicitConversion (ec, right, ltype, loc);
1137 // Special case null ?? null
1139 if (ltype == right.Type) {
1147 TypeSpec rtype = right.Type;
1148 if (!Convert.ImplicitConversionExists (ec, unwrap ?? left, rtype) || right.eclass == ExprClass.MethodGroup)
1152 // Reduce (null ?? right) to right
1155 return ReducedExpression.Create (right, this).Resolve (ec);
1157 left = Convert.ImplicitConversion (ec, unwrap ?? left, rtype, loc);
1162 public override bool ContainsEmitWithAwait ()
1165 return unwrap.ContainsEmitWithAwait () || right.ContainsEmitWithAwait ();
1167 return left.ContainsEmitWithAwait () || right.ContainsEmitWithAwait ();
1170 protected override Expression DoResolve (ResolveContext ec)
1172 left = left.Resolve (ec);
1173 right = right.Resolve (ec);
1175 if (left == null || right == null)
1178 eclass = ExprClass.Value;
1180 Expression e = ConvertExpression (ec);
1182 Binary.Error_OperatorCannotBeApplied (ec, left, right, "??", loc);
1189 public override void Emit (EmitContext ec)
1191 Label end_label = ec.DefineLabel ();
1193 if (unwrap != null) {
1194 Label is_null_label = ec.DefineLabel ();
1196 unwrap.EmitCheck (ec);
1197 ec.Emit (OpCodes.Brfalse, is_null_label);
1200 ec.Emit (OpCodes.Br, end_label);
1202 ec.MarkLabel (is_null_label);
1205 ec.MarkLabel (end_label);
1210 ec.Emit (OpCodes.Dup);
1212 // Only to make verifier happy
1213 if (left.Type.IsGenericParameter)
1214 ec.Emit (OpCodes.Box, left.Type);
1216 ec.Emit (OpCodes.Brtrue, end_label);
1218 ec.Emit (OpCodes.Pop);
1221 ec.MarkLabel (end_label);
1224 protected override void CloneTo (CloneContext clonectx, Expression t)
1226 NullCoalescingOperator target = (NullCoalescingOperator) t;
1228 target.left = left.Clone (clonectx);
1229 target.right = right.Clone (clonectx);
1232 public override object Accept (StructuralVisitor visitor)
1234 return visitor.Visit (this);
1238 class LiftedUnaryMutator : UnaryMutator
1240 public LiftedUnaryMutator (Mode mode, Expression expr, Location loc)
1241 : base (mode, expr, loc)
1245 protected override Expression DoResolve (ResolveContext ec)
1247 var orig_expr = expr;
1249 expr = Unwrap.Create (expr);
1251 var res = base.DoResolveOperation (ec);
1259 protected override void EmitOperation (EmitContext ec)
1261 Label is_null_label = ec.DefineLabel ();
1262 Label end_label = ec.DefineLabel ();
1264 LocalTemporary lt = new LocalTemporary (type);
1266 // Value is on the stack
1269 var call = new CallEmitter ();
1270 call.InstanceExpression = lt;
1271 call.EmitPredefined (ec, NullableInfo.GetHasValue (expr.Type), null);
1273 ec.Emit (OpCodes.Brfalse, is_null_label);
1275 call = new CallEmitter ();
1276 call.InstanceExpression = lt;
1277 call.EmitPredefined (ec, NullableInfo.GetGetValueOrDefault (expr.Type), null);
1281 base.EmitOperation (ec);
1283 ec.Emit (OpCodes.Newobj, NullableInfo.GetConstructor (type));
1284 ec.Emit (OpCodes.Br_S, end_label);
1286 ec.MarkLabel (is_null_label);
1287 LiftedNull.Create (type, loc).Emit (ec);
1289 ec.MarkLabel (end_label);