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 = Wrap.Create (Left, rc.Module.PredefinedTypes.Nullable.TypeSpec.MakeGenericType (rc.Module, new[] { Left.Type }));
664 if (UnwrapRight == null && !Right.Type.IsNullableType)
665 Right = Wrap.Create (Right, rc.Module.PredefinedTypes.Nullable.TypeSpec.MakeGenericType (rc.Module, new[] { Right.Type }));
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 public override void Emit (EmitContext ec)
686 if (IsBitwiseBoolean && UserOperator == null) {
687 EmitBitwiseBoolean (ec);
691 if ((Binary.Oper & Binary.Operator.EqualityMask) != 0) {
696 Label is_null_label = ec.DefineLabel ();
697 Label end_label = ec.DefineLabel ();
699 if (ec.HasSet (BuilderContext.Options.AsyncBody) && Right.ContainsEmitWithAwait ()) {
700 Left = Left.EmitToField (ec);
701 Right = Right.EmitToField (ec);
704 if (UnwrapLeft != null) {
705 UnwrapLeft.EmitCheck (ec);
709 // Don't emit HasValue check when left and right expressions are same
711 if (UnwrapRight != null && !Binary.Left.Equals (Binary.Right)) {
712 UnwrapRight.EmitCheck (ec);
713 if (UnwrapLeft != null) {
714 ec.Emit (OpCodes.And);
718 ec.Emit (OpCodes.Brfalse, is_null_label);
720 if (UserOperator != null) {
721 var args = new Arguments (2);
722 args.Add (new Argument (Left));
723 args.Add (new Argument (Right));
725 var call = new CallEmitter ();
726 call.EmitPredefined (ec, UserOperator, args);
728 Binary.EmitOperator (ec, Left, Right);
732 // Wrap the result when the operator return type is nullable type
734 if (type.IsNullableType)
735 ec.Emit (OpCodes.Newobj, NullableInfo.GetConstructor (type));
737 ec.Emit (OpCodes.Br_S, end_label);
738 ec.MarkLabel (is_null_label);
740 if ((Binary.Oper & Binary.Operator.ComparisonMask) != 0) {
743 LiftedNull.Create (type, loc).Emit (ec);
746 ec.MarkLabel (end_label);
749 void EmitBitwiseBoolean (EmitContext ec)
751 Label load_left = ec.DefineLabel ();
752 Label load_right = ec.DefineLabel ();
753 Label end_label = ec.DefineLabel ();
754 Label is_null_label = ec.DefineLabel ();
756 bool or = Binary.Oper == Binary.Operator.BitwiseOr;
759 // Both operands are bool? types
761 if (UnwrapLeft != null && UnwrapRight != null) {
762 if (ec.HasSet (BuilderContext.Options.AsyncBody) && Binary.Right.ContainsEmitWithAwait ()) {
763 Left = Left.EmitToField (ec);
764 Right = Right.EmitToField (ec);
768 ec.Emit (OpCodes.Brtrue_S, load_right);
771 ec.Emit (OpCodes.Brtrue_S, load_left);
773 UnwrapLeft.EmitCheck (ec);
774 ec.Emit (OpCodes.Brfalse_S, load_right);
777 ec.MarkLabel (load_left);
779 UnwrapRight.Load (ec);
781 UnwrapLeft.Load (ec);
783 ec.Emit (OpCodes.Br_S, end_label);
786 ec.MarkLabel (load_right);
788 UnwrapLeft.Load (ec);
790 UnwrapRight.Load (ec);
792 ec.MarkLabel (end_label);
797 // Faster version when one operand is bool
799 if (UnwrapLeft == null) {
803 // Optimizes remaining (false & bool?), (true | bool?) which are not easy to handle
804 // in binary expression reduction
806 var c = Left as BoolConstant;
808 // Keep evaluation order
809 UnwrapRight.Store (ec);
811 ec.EmitInt (or ? 1 : 0);
812 ec.Emit (OpCodes.Newobj, NullableInfo.GetConstructor (type));
813 } else if (Left.IsNull) {
814 UnwrapRight.Emit (ec);
815 ec.Emit (or ? OpCodes.Brfalse_S : OpCodes.Brtrue_S, is_null_label);
817 UnwrapRight.Load (ec);
818 ec.Emit (OpCodes.Br_S, end_label);
820 ec.MarkLabel (is_null_label);
821 LiftedNull.Create (type, loc).Emit (ec);
824 ec.Emit (or ? OpCodes.Brfalse_S : OpCodes.Brtrue_S, load_right);
826 ec.EmitInt (or ? 1 : 0);
827 ec.Emit (OpCodes.Newobj, NullableInfo.GetConstructor (type));
829 ec.Emit (OpCodes.Br_S, end_label);
831 ec.MarkLabel (load_right);
832 UnwrapRight.Original.Emit (ec);
838 // Keep left-right evaluation order
839 UnwrapLeft.Store (ec);
842 // Optimizes remaining (bool? & false), (bool? | true) which are not easy to handle
843 // in binary expression reduction
845 var c = Right as BoolConstant;
847 ec.EmitInt (or ? 1 : 0);
848 ec.Emit (OpCodes.Newobj, NullableInfo.GetConstructor (type));
849 } else if (Right.IsNull) {
850 UnwrapLeft.Emit (ec);
851 ec.Emit (or ? OpCodes.Brfalse_S : OpCodes.Brtrue_S, is_null_label);
853 UnwrapLeft.Load (ec);
854 ec.Emit (OpCodes.Br_S, end_label);
856 ec.MarkLabel (is_null_label);
857 LiftedNull.Create (type, loc).Emit (ec);
860 ec.Emit (or ? OpCodes.Brfalse_S : OpCodes.Brtrue_S, load_right);
862 ec.EmitInt (or ? 1 : 0);
863 ec.Emit (OpCodes.Newobj, NullableInfo.GetConstructor (type));
865 ec.Emit (OpCodes.Br_S, end_label);
867 ec.MarkLabel (load_right);
869 UnwrapLeft.Load (ec);
873 ec.MarkLabel (end_label);
877 // Emits optimized equality or inequality operator when possible
879 void EmitEquality (EmitContext ec)
882 // Either left or right is null
884 if (UnwrapLeft != null && Binary.Right.IsNull) { // TODO: Optimize for EmitBranchable
886 // left.HasValue == false
888 UnwrapLeft.EmitCheck (ec);
889 if (Binary.Oper == Binary.Operator.Equality) {
891 ec.Emit (OpCodes.Ceq);
896 if (UnwrapRight != null && Binary.Left.IsNull) {
898 // right.HasValue == false
900 UnwrapRight.EmitCheck (ec);
901 if (Binary.Oper == Binary.Operator.Equality) {
903 ec.Emit (OpCodes.Ceq);
908 Label dissimilar_label = ec.DefineLabel ();
909 Label end_label = ec.DefineLabel ();
911 if (UserOperator != null) {
914 if (UnwrapLeft != null) {
915 UnwrapLeft.EmitCheck (ec);
917 // Keep evaluation order same
918 if (!(Left is VariableReference)) {
920 var lt = new LocalTemporary (Left.Type);
926 if (UnwrapRight != null) {
927 UnwrapRight.EmitCheck (ec);
929 if (UnwrapLeft != null) {
930 ec.Emit (OpCodes.Bne_Un, dissimilar_label);
932 Label compare_label = ec.DefineLabel ();
933 UnwrapLeft.EmitCheck (ec);
934 ec.Emit (OpCodes.Brtrue, compare_label);
936 if (Binary.Oper == Binary.Operator.Equality)
941 ec.Emit (OpCodes.Br, end_label);
943 ec.MarkLabel (compare_label);
945 ec.Emit (OpCodes.Brfalse, dissimilar_label);
948 ec.Emit (OpCodes.Brfalse, dissimilar_label);
951 var args = new Arguments (2);
952 args.Add (new Argument (left));
953 args.Add (new Argument (Right));
955 var call = new CallEmitter ();
956 call.EmitPredefined (ec, UserOperator, args);
958 if (ec.HasSet (BuilderContext.Options.AsyncBody) && Binary.Right.ContainsEmitWithAwait ()) {
959 Left = Left.EmitToField (ec);
960 Right = Right.EmitToField (ec);
964 // Emit underlying value comparison first.
966 // For this code: int? a = 1; bool b = a == 1;
968 // We emit something similar to this. Expressions with side effects have local
969 // variable created by Unwrap expression
971 // left.GetValueOrDefault ()
973 // bne.un.s dissimilar_label
984 ec.Emit (OpCodes.Bne_Un_S, dissimilar_label);
987 // Check both left and right expressions for Unwrap call in which
988 // case we need to run get_HasValue() check because the type is
989 // nullable and could have null value
991 if (UnwrapLeft != null)
992 UnwrapLeft.EmitCheck (ec);
994 if (UnwrapRight != null)
995 UnwrapRight.EmitCheck (ec);
997 if (UnwrapLeft != null && UnwrapRight != null) {
998 if (Binary.Oper == Binary.Operator.Inequality)
999 ec.Emit (OpCodes.Xor);
1001 ec.Emit (OpCodes.Ceq);
1003 if (Binary.Oper == Binary.Operator.Inequality) {
1005 ec.Emit (OpCodes.Ceq);
1010 ec.Emit (OpCodes.Br_S, end_label);
1012 ec.MarkLabel (dissimilar_label);
1013 if (Binary.Oper == Binary.Operator.Inequality)
1018 ec.MarkLabel (end_label);
1021 public override void FlowAnalysis (FlowAnalysisContext fc)
1023 Binary.FlowAnalysis (fc);
1026 public override SLE.Expression MakeExpression (BuilderContext ctx)
1028 return Binary.MakeExpression (ctx, Left, Right);
1032 public class NullCoalescingOperator : Expression
1034 Expression left, right;
1037 public NullCoalescingOperator (Expression left, Expression right)
1041 this.loc = left.Location;
1044 public Expression LeftExpression {
1050 public Expression RightExpression {
1056 public override Expression CreateExpressionTree (ResolveContext ec)
1058 if (left is NullLiteral)
1059 ec.Report.Error (845, loc, "An expression tree cannot contain a coalescing operator with null left side");
1061 UserCast uc = left as UserCast;
1062 Expression conversion = null;
1066 Arguments c_args = new Arguments (2);
1067 c_args.Add (new Argument (uc.CreateExpressionTree (ec)));
1068 c_args.Add (new Argument (left.CreateExpressionTree (ec)));
1069 conversion = CreateExpressionFactoryCall (ec, "Lambda", c_args);
1072 Arguments args = new Arguments (3);
1073 args.Add (new Argument (left.CreateExpressionTree (ec)));
1074 args.Add (new Argument (right.CreateExpressionTree (ec)));
1075 if (conversion != null)
1076 args.Add (new Argument (conversion));
1078 return CreateExpressionFactoryCall (ec, "Coalesce", args);
1081 Expression ConvertExpression (ResolveContext ec)
1083 // TODO: ImplicitConversionExists should take care of this
1084 if (left.eclass == ExprClass.MethodGroup)
1087 TypeSpec ltype = left.Type;
1090 // If left is a nullable type and an implicit conversion exists from right to underlying type of left,
1091 // the result is underlying type of left
1093 if (ltype.IsNullableType) {
1094 unwrap = Unwrap.Create (left, false);
1099 // Reduce (left ?? null) to left
1102 return ReducedExpression.Create (left, this);
1104 if (Convert.ImplicitConversionExists (ec, right, unwrap.Type)) {
1109 // If right is a dynamic expression, the result type is dynamic
1111 if (right.Type.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
1114 // Need to box underlying value type
1115 left = Convert.ImplicitBoxingConversion (left, ltype, type);
1119 right = Convert.ImplicitConversion (ec, right, ltype, loc);
1123 } else if (TypeSpec.IsReferenceType (ltype)) {
1124 if (Convert.ImplicitConversionExists (ec, right, ltype)) {
1126 // If right is a dynamic expression, the result type is dynamic
1128 if (right.Type.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
1134 // Reduce ("foo" ?? expr) to expression
1136 Constant lc = left as Constant;
1137 if (lc != null && !lc.IsDefaultValue)
1138 return ReducedExpression.Create (lc, this);
1141 // Reduce (left ?? null) to left OR (null-constant ?? right) to right
1143 if (right.IsNull || lc != null)
1144 return ReducedExpression.Create (lc != null ? right : left, this);
1146 right = Convert.ImplicitConversion (ec, right, ltype, loc);
1152 // Special case null ?? null
1154 if (ltype == right.Type) {
1162 TypeSpec rtype = right.Type;
1163 if (!Convert.ImplicitConversionExists (ec, unwrap ?? left, rtype) || right.eclass == ExprClass.MethodGroup)
1167 // Reduce (null ?? right) to right
1170 return ReducedExpression.Create (right, this).Resolve (ec);
1172 left = Convert.ImplicitConversion (ec, unwrap ?? left, rtype, loc);
1177 public override bool ContainsEmitWithAwait ()
1180 return unwrap.ContainsEmitWithAwait () || right.ContainsEmitWithAwait ();
1182 return left.ContainsEmitWithAwait () || right.ContainsEmitWithAwait ();
1185 protected override Expression DoResolve (ResolveContext ec)
1187 left = left.Resolve (ec);
1188 right = right.Resolve (ec);
1190 if (left == null || right == null)
1193 eclass = ExprClass.Value;
1195 Expression e = ConvertExpression (ec);
1197 Binary.Error_OperatorCannotBeApplied (ec, left, right, "??", loc);
1204 public override void Emit (EmitContext ec)
1206 Label end_label = ec.DefineLabel ();
1208 if (unwrap != null) {
1209 Label is_null_label = ec.DefineLabel ();
1211 unwrap.EmitCheck (ec);
1212 ec.Emit (OpCodes.Brfalse, is_null_label);
1215 ec.Emit (OpCodes.Br, end_label);
1217 ec.MarkLabel (is_null_label);
1220 ec.MarkLabel (end_label);
1225 ec.Emit (OpCodes.Dup);
1227 // Only to make verifier happy
1228 if (left.Type.IsGenericParameter)
1229 ec.Emit (OpCodes.Box, left.Type);
1231 ec.Emit (OpCodes.Brtrue, end_label);
1233 ec.Emit (OpCodes.Pop);
1236 ec.MarkLabel (end_label);
1239 public override void FlowAnalysis (FlowAnalysisContext fc)
1241 left.FlowAnalysis (fc);
1242 var left_da = fc.BranchDefiniteAssignment ();
1243 right.FlowAnalysis (fc);
1244 fc.DefiniteAssignment = left_da;
1247 protected override void CloneTo (CloneContext clonectx, Expression t)
1249 NullCoalescingOperator target = (NullCoalescingOperator) t;
1251 target.left = left.Clone (clonectx);
1252 target.right = right.Clone (clonectx);
1255 public override object Accept (StructuralVisitor visitor)
1257 return visitor.Visit (this);
1261 class LiftedUnaryMutator : UnaryMutator
1263 public LiftedUnaryMutator (Mode mode, Expression expr, Location loc)
1264 : base (mode, expr, loc)
1268 protected override Expression DoResolve (ResolveContext ec)
1270 var orig_expr = expr;
1272 expr = Unwrap.Create (expr);
1274 var res = base.DoResolveOperation (ec);
1282 protected override void EmitOperation (EmitContext ec)
1284 Label is_null_label = ec.DefineLabel ();
1285 Label end_label = ec.DefineLabel ();
1287 LocalTemporary lt = new LocalTemporary (type);
1289 // Value is on the stack
1292 var call = new CallEmitter ();
1293 call.InstanceExpression = lt;
1294 call.EmitPredefined (ec, NullableInfo.GetHasValue (expr.Type), null);
1296 ec.Emit (OpCodes.Brfalse, is_null_label);
1298 call = new CallEmitter ();
1299 call.InstanceExpression = lt;
1300 call.EmitPredefined (ec, NullableInfo.GetGetValueOrDefault (expr.Type), null);
1304 base.EmitOperation (ec);
1306 ec.Emit (OpCodes.Newobj, NullableInfo.GetConstructor (type));
1307 ec.Emit (OpCodes.Br_S, end_label);
1309 ec.MarkLabel (is_null_label);
1310 LiftedNull.Create (type, loc).Emit (ec);
1312 ec.MarkLabel (end_label);