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 override void FlowAnalysis (FlowAnalysisContext fc)
206 expr.FlowAnalysis (fc);
209 public Expression Original {
215 public override int GetHashCode ()
217 return expr.GetHashCode ();
220 public override bool IsNull {
226 public void Store (EmitContext ec)
228 if (temp != null || temp_field != null)
231 if (expr is VariableReference)
235 LocalVariable.Store (ec);
238 public void Load (EmitContext ec)
240 if (temp_field != null)
241 temp_field.Emit (ec);
242 else if (expr is VariableReference)
245 LocalVariable.Emit (ec);
248 public override SLE.Expression MakeExpression (BuilderContext ctx)
250 return expr.MakeExpression (ctx);
253 public void AddressOf (EmitContext ec, AddressOp mode)
257 if (temp_field != null) {
258 ml = temp_field as IMemoryLocation;
260 var lt = new LocalTemporary (temp_field.Type);
261 temp_field.Emit (ec);
266 ml = expr as VariableReference;
270 ml.AddressOf (ec, mode);
272 LocalVariable.AddressOf (ec, mode);
276 // Keeps result of non-variable expression
278 LocalTemporary LocalVariable {
280 if (temp == null && temp_field == null)
281 temp = new LocalTemporary (expr.Type);
288 // Calls get_Value method on nullable expression
290 public class UnwrapCall : CompositeExpression
292 public UnwrapCall (Expression expr)
297 protected override Expression DoResolve (ResolveContext rc)
302 type = NullableInfo.GetUnderlyingType (type);
307 public override void Emit (EmitContext ec)
309 var call = new CallEmitter ();
310 call.InstanceExpression = Child;
311 call.EmitPredefined (ec, NullableInfo.GetValue (Child.Type), null);
315 public class Wrap : TypeCast
317 private Wrap (Expression expr, TypeSpec type)
320 eclass = ExprClass.Value;
323 public override Expression CreateExpressionTree (ResolveContext ec)
325 TypeCast child_cast = child as TypeCast;
326 if (child_cast != null) {
328 return child_cast.CreateExpressionTree (ec);
331 var user_cast = child as UserCast;
332 if (user_cast != null) {
334 return user_cast.CreateExpressionTree (ec);
337 return base.CreateExpressionTree (ec);
340 public static Expression Create (Expression expr, TypeSpec type)
343 // Avoid unwraping and wraping of the same type
345 Unwrap unwrap = expr as Unwrap;
346 if (unwrap != null && expr.Type == NullableInfo.GetUnderlyingType (type))
347 return unwrap.Original;
349 return new Wrap (expr, type);
352 public override void Emit (EmitContext ec)
355 ec.Emit (OpCodes.Newobj, NullableInfo.GetConstructor (type));
360 // Represents null literal lifted to nullable type
362 public class LiftedNull : NullConstant, IMemoryLocation
364 private LiftedNull (TypeSpec nullable_type, Location loc)
365 : base (nullable_type, loc)
367 eclass = ExprClass.Value;
370 public static Constant Create (TypeSpec nullable, Location loc)
372 return new LiftedNull (nullable, loc);
375 public static Constant CreateFromExpression (ResolveContext rc, Expression e)
377 if (!rc.HasSet (ResolveContext.Options.ExpressionTreeConversion)) {
378 rc.Report.Warning (458, 2, e.Location, "The result of the expression is always `null' of type `{0}'",
379 e.Type.GetSignatureForError ());
382 return ReducedExpression.Create (Create (e.Type, e.Location), e);
385 public override void Emit (EmitContext ec)
387 // TODO: generate less temporary variables
388 LocalTemporary value_target = new LocalTemporary (type);
390 value_target.AddressOf (ec, AddressOp.Store);
391 ec.Emit (OpCodes.Initobj, type);
392 value_target.Emit (ec);
393 value_target.Release (ec);
396 public void AddressOf (EmitContext ec, AddressOp Mode)
398 LocalTemporary value_target = new LocalTemporary (type);
400 value_target.AddressOf (ec, AddressOp.Store);
401 ec.Emit (OpCodes.Initobj, type);
402 value_target.AddressOf (ec, Mode);
407 // Generic lifting expression, supports all S/S? -> T/T? cases
409 public class LiftedConversion : Expression, IMemoryLocation
411 Expression expr, null_value;
414 public LiftedConversion (Expression expr, Unwrap unwrap, TypeSpec type)
417 this.unwrap = unwrap;
418 this.loc = expr.Location;
422 public LiftedConversion (Expression expr, Expression unwrap, TypeSpec type)
423 : this (expr, unwrap as Unwrap, type)
427 public override bool ContainsEmitWithAwait ()
429 return unwrap.ContainsEmitWithAwait ();
432 public override Expression CreateExpressionTree (ResolveContext ec)
434 return expr.CreateExpressionTree (ec);
437 protected override Expression DoResolve (ResolveContext ec)
440 // It's null when lifting non-nullable type
442 if (unwrap == null) {
443 // S -> T? is wrap only
444 if (type.IsNullableType)
445 return Wrap.Create (expr, type);
447 // S -> T can be simplified
451 // Wrap target for T?
452 if (type.IsNullableType) {
453 if (!expr.Type.IsNullableType) {
454 expr = Wrap.Create (expr, type);
459 null_value = LiftedNull.Create (type, loc);
460 } else if (TypeSpec.IsValueType (type)) {
461 null_value = LiftedNull.Create (type, loc);
463 null_value = new NullConstant (type, loc);
466 eclass = ExprClass.Value;
470 public override void Emit (EmitContext ec)
472 Label is_null_label = ec.DefineLabel ();
473 Label end_label = ec.DefineLabel ();
475 unwrap.EmitCheck (ec);
476 ec.Emit (OpCodes.Brfalse, is_null_label);
480 ec.Emit (OpCodes.Br, end_label);
481 ec.MarkLabel (is_null_label);
483 null_value.Emit (ec);
485 ec.MarkLabel (end_label);
488 public override void FlowAnalysis (FlowAnalysisContext fc)
490 expr.FlowAnalysis (fc);
493 public void AddressOf (EmitContext ec, AddressOp mode)
495 unwrap.AddressOf (ec, mode);
499 public class LiftedUnaryOperator : Unary, IMemoryLocation
502 Expression user_operator;
504 public LiftedUnaryOperator (Unary.Operator op, Expression expr, Location loc)
505 : base (op, expr, loc)
509 public void AddressOf (EmitContext ec, AddressOp mode)
511 unwrap.AddressOf (ec, mode);
514 public override Expression CreateExpressionTree (ResolveContext ec)
516 if (user_operator != null)
517 return user_operator.CreateExpressionTree (ec);
519 if (Oper == Operator.UnaryPlus)
520 return Expr.CreateExpressionTree (ec);
522 return base.CreateExpressionTree (ec);
525 protected override Expression DoResolve (ResolveContext ec)
527 unwrap = Unwrap.Create (Expr, false);
531 Expression res = base.ResolveOperator (ec, unwrap);
533 if (user_operator == null)
536 res = Expr = LiftExpression (ec, Expr);
542 eclass = ExprClass.Value;
547 public override void Emit (EmitContext ec)
549 Label is_null_label = ec.DefineLabel ();
550 Label end_label = ec.DefineLabel ();
552 unwrap.EmitCheck (ec);
553 ec.Emit (OpCodes.Brfalse, is_null_label);
555 if (user_operator != null) {
556 user_operator.Emit (ec);
558 EmitOperator (ec, NullableInfo.GetUnderlyingType (type));
561 ec.Emit (OpCodes.Newobj, NullableInfo.GetConstructor (type));
562 ec.Emit (OpCodes.Br_S, end_label);
564 ec.MarkLabel (is_null_label);
565 LiftedNull.Create (type, loc).Emit (ec);
567 ec.MarkLabel (end_label);
570 static Expression LiftExpression (ResolveContext ec, Expression expr)
572 var lifted_type = new NullableType (expr.Type, expr.Location);
573 if (lifted_type.ResolveAsType (ec) == null)
576 expr.Type = lifted_type.Type;
580 protected override Expression ResolveEnumOperator (ResolveContext ec, Expression expr, TypeSpec[] predefined)
582 expr = base.ResolveEnumOperator (ec, expr, predefined);
586 Expr = LiftExpression (ec, Expr);
587 return LiftExpression (ec, expr);
590 protected override Expression ResolveUserOperator (ResolveContext ec, Expression expr)
592 expr = base.ResolveUserOperator (ec, expr);
597 // When a user operator is of non-nullable type
599 if (Expr is Unwrap) {
600 user_operator = LiftExpression (ec, expr);
601 return user_operator;
609 // Lifted version of binary operators
611 class LiftedBinaryOperator : Expression
613 public LiftedBinaryOperator (Binary b)
616 this.loc = b.Location;
619 public Binary Binary { get; private set; }
621 public Expression Left { get; set; }
623 public Expression Right { get; set; }
625 public Unwrap UnwrapLeft { get; set; }
627 public Unwrap UnwrapRight { get; set; }
629 public MethodSpec UserOperator { get; set; }
631 bool IsBitwiseBoolean {
633 return (Binary.Oper == Binary.Operator.BitwiseAnd || Binary.Oper == Binary.Operator.BitwiseOr) &&
634 ((UnwrapLeft != null && UnwrapLeft.Type.BuiltinType == BuiltinTypeSpec.Type.Bool) ||
635 (UnwrapRight != null && UnwrapRight.Type.BuiltinType == BuiltinTypeSpec.Type.Bool));
639 public override bool ContainsEmitWithAwait ()
641 return Left.ContainsEmitWithAwait () || Right.ContainsEmitWithAwait ();
644 public override Expression CreateExpressionTree (ResolveContext rc)
646 if (UserOperator != null) {
647 Arguments args = new Arguments (2);
648 args.Add (new Argument (Binary.Left));
649 args.Add (new Argument (Binary.Right));
651 var method = new UserOperatorCall (UserOperator, args, Binary.CreateExpressionTree, loc);
652 return method.CreateExpressionTree (rc);
655 return Binary.CreateExpressionTree (rc);
658 protected override Expression DoResolve (ResolveContext rc)
660 if (rc.IsRuntimeBinder) {
661 if (UnwrapLeft == null && !Left.Type.IsNullableType)
662 Left = LiftOperand (rc, Left);
664 if (UnwrapRight == null && !Right.Type.IsNullableType)
665 Right = LiftOperand (rc, Right);
667 if (UnwrapLeft == null && Left != null && Left.Type.IsNullableType) {
668 Left = Unwrap.CreateUnwrapped (Left);
669 UnwrapLeft = Left as Unwrap;
672 if (UnwrapRight == null && Right != null && Right.Type.IsNullableType) {
673 Right = Unwrap.CreateUnwrapped (Right);
674 UnwrapRight = Right as Unwrap;
679 eclass = Binary.eclass;
684 Expression LiftOperand (ResolveContext rc, Expression expr)
688 type = Left.IsNull ? Right.Type : Left.Type;
693 if (!type.IsNullableType)
694 type = rc.Module.PredefinedTypes.Nullable.TypeSpec.MakeGenericType (rc.Module, new[] { type });
696 return Wrap.Create (expr, type);
699 public override void Emit (EmitContext ec)
701 if (IsBitwiseBoolean && UserOperator == null) {
702 EmitBitwiseBoolean (ec);
706 if ((Binary.Oper & Binary.Operator.EqualityMask) != 0) {
711 Label is_null_label = ec.DefineLabel ();
712 Label end_label = ec.DefineLabel ();
714 if (ec.HasSet (BuilderContext.Options.AsyncBody) && Right.ContainsEmitWithAwait ()) {
715 Left = Left.EmitToField (ec);
716 Right = Right.EmitToField (ec);
719 if (UnwrapLeft != null) {
720 UnwrapLeft.EmitCheck (ec);
724 // Don't emit HasValue check when left and right expressions are same
726 if (UnwrapRight != null && !Binary.Left.Equals (Binary.Right)) {
727 UnwrapRight.EmitCheck (ec);
728 if (UnwrapLeft != null) {
729 ec.Emit (OpCodes.And);
733 ec.Emit (OpCodes.Brfalse, is_null_label);
735 if (UserOperator != null) {
736 var args = new Arguments (2);
737 args.Add (new Argument (Left));
738 args.Add (new Argument (Right));
740 var call = new CallEmitter ();
741 call.EmitPredefined (ec, UserOperator, args);
743 Binary.EmitOperator (ec, Left, Right);
747 // Wrap the result when the operator return type is nullable type
749 if (type.IsNullableType)
750 ec.Emit (OpCodes.Newobj, NullableInfo.GetConstructor (type));
752 ec.Emit (OpCodes.Br_S, end_label);
753 ec.MarkLabel (is_null_label);
755 if ((Binary.Oper & Binary.Operator.ComparisonMask) != 0) {
758 LiftedNull.Create (type, loc).Emit (ec);
761 ec.MarkLabel (end_label);
764 void EmitBitwiseBoolean (EmitContext ec)
766 Label load_left = ec.DefineLabel ();
767 Label load_right = ec.DefineLabel ();
768 Label end_label = ec.DefineLabel ();
769 Label is_null_label = ec.DefineLabel ();
771 bool or = Binary.Oper == Binary.Operator.BitwiseOr;
774 // Both operands are bool? types
776 if (UnwrapLeft != null && UnwrapRight != null) {
777 if (ec.HasSet (BuilderContext.Options.AsyncBody) && Binary.Right.ContainsEmitWithAwait ()) {
778 Left = Left.EmitToField (ec);
779 Right = Right.EmitToField (ec);
783 ec.Emit (OpCodes.Brtrue_S, load_right);
786 ec.Emit (OpCodes.Brtrue_S, load_left);
788 UnwrapLeft.EmitCheck (ec);
789 ec.Emit (OpCodes.Brfalse_S, load_right);
792 ec.MarkLabel (load_left);
794 UnwrapRight.Load (ec);
796 UnwrapLeft.Load (ec);
798 ec.Emit (OpCodes.Br_S, end_label);
801 ec.MarkLabel (load_right);
803 UnwrapLeft.Load (ec);
805 UnwrapRight.Load (ec);
807 ec.MarkLabel (end_label);
812 // Faster version when one operand is bool
814 if (UnwrapLeft == null) {
818 // Optimizes remaining (false & bool?), (true | bool?) which are not easy to handle
819 // in binary expression reduction
821 var c = Left as BoolConstant;
823 // Keep evaluation order
824 UnwrapRight.Store (ec);
826 ec.EmitInt (or ? 1 : 0);
827 ec.Emit (OpCodes.Newobj, NullableInfo.GetConstructor (type));
828 } else if (Left.IsNull) {
829 UnwrapRight.Emit (ec);
830 ec.Emit (or ? OpCodes.Brfalse_S : OpCodes.Brtrue_S, is_null_label);
832 UnwrapRight.Load (ec);
833 ec.Emit (OpCodes.Br_S, end_label);
835 ec.MarkLabel (is_null_label);
836 LiftedNull.Create (type, loc).Emit (ec);
839 ec.Emit (or ? OpCodes.Brfalse_S : OpCodes.Brtrue_S, load_right);
841 ec.EmitInt (or ? 1 : 0);
842 ec.Emit (OpCodes.Newobj, NullableInfo.GetConstructor (type));
844 ec.Emit (OpCodes.Br_S, end_label);
846 ec.MarkLabel (load_right);
847 UnwrapRight.Original.Emit (ec);
853 // Keep left-right evaluation order
854 UnwrapLeft.Store (ec);
857 // Optimizes remaining (bool? & false), (bool? | true) which are not easy to handle
858 // in binary expression reduction
860 var c = Right as BoolConstant;
862 ec.EmitInt (or ? 1 : 0);
863 ec.Emit (OpCodes.Newobj, NullableInfo.GetConstructor (type));
864 } else if (Right.IsNull) {
865 UnwrapLeft.Emit (ec);
866 ec.Emit (or ? OpCodes.Brfalse_S : OpCodes.Brtrue_S, is_null_label);
868 UnwrapLeft.Load (ec);
869 ec.Emit (OpCodes.Br_S, end_label);
871 ec.MarkLabel (is_null_label);
872 LiftedNull.Create (type, loc).Emit (ec);
875 ec.Emit (or ? OpCodes.Brfalse_S : OpCodes.Brtrue_S, load_right);
877 ec.EmitInt (or ? 1 : 0);
878 ec.Emit (OpCodes.Newobj, NullableInfo.GetConstructor (type));
880 ec.Emit (OpCodes.Br_S, end_label);
882 ec.MarkLabel (load_right);
884 UnwrapLeft.Load (ec);
888 ec.MarkLabel (end_label);
892 // Emits optimized equality or inequality operator when possible
894 void EmitEquality (EmitContext ec)
897 // Either left or right is null
899 if (UnwrapLeft != null && Binary.Right.IsNull) { // TODO: Optimize for EmitBranchable
901 // left.HasValue == false
903 UnwrapLeft.EmitCheck (ec);
904 if (Binary.Oper == Binary.Operator.Equality) {
906 ec.Emit (OpCodes.Ceq);
911 if (UnwrapRight != null && Binary.Left.IsNull) {
913 // right.HasValue == false
915 UnwrapRight.EmitCheck (ec);
916 if (Binary.Oper == Binary.Operator.Equality) {
918 ec.Emit (OpCodes.Ceq);
923 Label dissimilar_label = ec.DefineLabel ();
924 Label end_label = ec.DefineLabel ();
926 if (UserOperator != null) {
929 if (UnwrapLeft != null) {
930 UnwrapLeft.EmitCheck (ec);
932 // Keep evaluation order same
933 if (!(Left is VariableReference)) {
935 var lt = new LocalTemporary (Left.Type);
941 if (UnwrapRight != null) {
942 UnwrapRight.EmitCheck (ec);
944 if (UnwrapLeft != null) {
945 ec.Emit (OpCodes.Bne_Un, dissimilar_label);
947 Label compare_label = ec.DefineLabel ();
948 UnwrapLeft.EmitCheck (ec);
949 ec.Emit (OpCodes.Brtrue, compare_label);
951 if (Binary.Oper == Binary.Operator.Equality)
956 ec.Emit (OpCodes.Br, end_label);
958 ec.MarkLabel (compare_label);
960 ec.Emit (OpCodes.Brfalse, dissimilar_label);
963 ec.Emit (OpCodes.Brfalse, dissimilar_label);
966 var args = new Arguments (2);
967 args.Add (new Argument (left));
968 args.Add (new Argument (Right));
970 var call = new CallEmitter ();
971 call.EmitPredefined (ec, UserOperator, args);
973 if (ec.HasSet (BuilderContext.Options.AsyncBody) && Binary.Right.ContainsEmitWithAwait ()) {
974 Left = Left.EmitToField (ec);
975 Right = Right.EmitToField (ec);
979 // Emit underlying value comparison first.
981 // For this code: int? a = 1; bool b = a == 1;
983 // We emit something similar to this. Expressions with side effects have local
984 // variable created by Unwrap expression
986 // left.GetValueOrDefault ()
988 // bne.un.s dissimilar_label
999 ec.Emit (OpCodes.Bne_Un_S, dissimilar_label);
1002 // Check both left and right expressions for Unwrap call in which
1003 // case we need to run get_HasValue() check because the type is
1004 // nullable and could have null value
1006 if (UnwrapLeft != null)
1007 UnwrapLeft.EmitCheck (ec);
1009 if (UnwrapRight != null)
1010 UnwrapRight.EmitCheck (ec);
1012 if (UnwrapLeft != null && UnwrapRight != null) {
1013 if (Binary.Oper == Binary.Operator.Inequality)
1014 ec.Emit (OpCodes.Xor);
1016 ec.Emit (OpCodes.Ceq);
1018 if (Binary.Oper == Binary.Operator.Inequality) {
1020 ec.Emit (OpCodes.Ceq);
1025 ec.Emit (OpCodes.Br_S, end_label);
1027 ec.MarkLabel (dissimilar_label);
1028 if (Binary.Oper == Binary.Operator.Inequality)
1033 ec.MarkLabel (end_label);
1036 public override void FlowAnalysis (FlowAnalysisContext fc)
1038 Binary.FlowAnalysis (fc);
1041 public override SLE.Expression MakeExpression (BuilderContext ctx)
1043 return Binary.MakeExpression (ctx, Left, Right);
1047 public class NullCoalescingOperator : Expression
1049 Expression left, right;
1052 public NullCoalescingOperator (Expression left, Expression right)
1056 this.loc = left.Location;
1059 public Expression LeftExpression {
1065 public Expression RightExpression {
1071 public override Expression CreateExpressionTree (ResolveContext ec)
1073 if (left is NullLiteral)
1074 ec.Report.Error (845, loc, "An expression tree cannot contain a coalescing operator with null left side");
1076 UserCast uc = left as UserCast;
1077 Expression conversion = null;
1081 Arguments c_args = new Arguments (2);
1082 c_args.Add (new Argument (uc.CreateExpressionTree (ec)));
1083 c_args.Add (new Argument (left.CreateExpressionTree (ec)));
1084 conversion = CreateExpressionFactoryCall (ec, "Lambda", c_args);
1087 Arguments args = new Arguments (3);
1088 args.Add (new Argument (left.CreateExpressionTree (ec)));
1089 args.Add (new Argument (right.CreateExpressionTree (ec)));
1090 if (conversion != null)
1091 args.Add (new Argument (conversion));
1093 return CreateExpressionFactoryCall (ec, "Coalesce", args);
1096 Expression ConvertExpression (ResolveContext ec)
1098 // TODO: ImplicitConversionExists should take care of this
1099 if (left.eclass == ExprClass.MethodGroup)
1102 TypeSpec ltype = left.Type;
1105 // If left is a nullable type and an implicit conversion exists from right to underlying type of left,
1106 // the result is underlying type of left
1108 if (ltype.IsNullableType) {
1109 unwrap = Unwrap.Create (left, false);
1114 // Reduce (left ?? null) to left
1117 return ReducedExpression.Create (left, this);
1119 if (Convert.ImplicitConversionExists (ec, right, unwrap.Type)) {
1124 // If right is a dynamic expression, the result type is dynamic
1126 if (right.Type.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
1129 // Need to box underlying value type
1130 left = Convert.ImplicitBoxingConversion (left, ltype, type);
1134 right = Convert.ImplicitConversion (ec, right, ltype, loc);
1138 } else if (TypeSpec.IsReferenceType (ltype)) {
1139 if (Convert.ImplicitConversionExists (ec, right, ltype)) {
1141 // If right is a dynamic expression, the result type is dynamic
1143 if (right.Type.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
1149 // Reduce ("foo" ?? expr) to expression
1151 Constant lc = left as Constant;
1152 if (lc != null && !lc.IsDefaultValue)
1153 return ReducedExpression.Create (lc, this);
1156 // Reduce (left ?? null) to left OR (null-constant ?? right) to right
1158 if (right.IsNull || lc != null)
1159 return ReducedExpression.Create (lc != null ? right : left, this);
1161 right = Convert.ImplicitConversion (ec, right, ltype, loc);
1167 // Special case null ?? null
1169 if (ltype == right.Type) {
1177 TypeSpec rtype = right.Type;
1178 if (!Convert.ImplicitConversionExists (ec, unwrap ?? left, rtype) || right.eclass == ExprClass.MethodGroup)
1182 // Reduce (null ?? right) to right
1185 return ReducedExpression.Create (right, this).Resolve (ec);
1187 left = Convert.ImplicitConversion (ec, unwrap ?? left, rtype, loc);
1192 public override bool ContainsEmitWithAwait ()
1195 return unwrap.ContainsEmitWithAwait () || right.ContainsEmitWithAwait ();
1197 return left.ContainsEmitWithAwait () || right.ContainsEmitWithAwait ();
1200 protected override Expression DoResolve (ResolveContext ec)
1202 left = left.Resolve (ec);
1203 right = right.Resolve (ec);
1205 if (left == null || right == null)
1208 eclass = ExprClass.Value;
1210 Expression e = ConvertExpression (ec);
1212 Binary.Error_OperatorCannotBeApplied (ec, left, right, "??", loc);
1219 public override void Emit (EmitContext ec)
1221 Label end_label = ec.DefineLabel ();
1223 if (unwrap != null) {
1224 Label is_null_label = ec.DefineLabel ();
1226 unwrap.EmitCheck (ec);
1227 ec.Emit (OpCodes.Brfalse, is_null_label);
1230 ec.Emit (OpCodes.Br, end_label);
1232 ec.MarkLabel (is_null_label);
1235 ec.MarkLabel (end_label);
1240 ec.Emit (OpCodes.Dup);
1242 // Only to make verifier happy
1243 if (left.Type.IsGenericParameter)
1244 ec.Emit (OpCodes.Box, left.Type);
1246 ec.Emit (OpCodes.Brtrue, end_label);
1248 ec.Emit (OpCodes.Pop);
1251 ec.MarkLabel (end_label);
1254 public override void FlowAnalysis (FlowAnalysisContext fc)
1256 left.FlowAnalysis (fc);
1257 var left_da = fc.BranchDefiniteAssignment ();
1258 right.FlowAnalysis (fc);
1259 fc.DefiniteAssignment = left_da;
1262 protected override void CloneTo (CloneContext clonectx, Expression t)
1264 NullCoalescingOperator target = (NullCoalescingOperator) t;
1266 target.left = left.Clone (clonectx);
1267 target.right = right.Clone (clonectx);
1270 public override object Accept (StructuralVisitor visitor)
1272 return visitor.Visit (this);
1276 class LiftedUnaryMutator : UnaryMutator
1278 public LiftedUnaryMutator (Mode mode, Expression expr, Location loc)
1279 : base (mode, expr, loc)
1283 protected override Expression DoResolve (ResolveContext ec)
1285 var orig_expr = expr;
1287 expr = Unwrap.Create (expr);
1289 var res = base.DoResolveOperation (ec);
1297 protected override void EmitOperation (EmitContext ec)
1299 Label is_null_label = ec.DefineLabel ();
1300 Label end_label = ec.DefineLabel ();
1302 LocalTemporary lt = new LocalTemporary (type);
1304 // Value is on the stack
1307 var call = new CallEmitter ();
1308 call.InstanceExpression = lt;
1309 call.EmitPredefined (ec, NullableInfo.GetHasValue (expr.Type), null);
1311 ec.Emit (OpCodes.Brfalse, is_null_label);
1313 call = new CallEmitter ();
1314 call.InstanceExpression = lt;
1315 call.EmitPredefined (ec, NullableInfo.GetGetValueOrDefault (expr.Type), null);
1319 base.EmitOperation (ec);
1321 ec.Emit (OpCodes.Newobj, NullableInfo.GetConstructor (type));
1322 ec.Emit (OpCodes.Br_S, end_label);
1324 ec.MarkLabel (is_null_label);
1325 LiftedNull.Create (type, loc).Emit (ec);
1327 ec.MarkLabel (end_label);