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
15 using System.Reflection;
16 using System.Reflection.Emit;
18 namespace Mono.CSharp.Nullable
20 public class NullableType : TypeExpr
24 public NullableType (TypeExpr underlying, Location l)
26 this.underlying = underlying;
29 eclass = ExprClass.Type;
32 public NullableType (Type type, Location loc)
33 : this (new TypeExpression (type, loc), loc)
36 protected override TypeExpr DoResolveAsTypeStep (IMemberContext ec)
38 if (TypeManager.generic_nullable_type == null) {
39 TypeManager.generic_nullable_type = TypeManager.CoreLookupType (ec.Compiler,
40 "System", "Nullable`1", Kind.Struct, true);
43 TypeArguments args = new TypeArguments (underlying);
44 GenericTypeExpr ctype = new GenericTypeExpr (TypeManager.generic_nullable_type, args, loc);
45 return ctype.ResolveAsTypeTerminal (ec, false);
48 public override TypeExpr ResolveAsTypeTerminal (IMemberContext ec, bool silent)
50 return ResolveAsBaseTerminal (ec, silent);
54 public sealed class NullableInfo
56 public readonly Type Type;
57 public readonly Type UnderlyingType;
58 public MethodInfo HasValue;
59 public MethodInfo Value;
60 public MethodInfo GetValueOrDefault;
61 public ConstructorInfo Constructor;
63 public NullableInfo (Type type)
66 UnderlyingType = TypeManager.TypeToCoreType (TypeManager.GetTypeArguments (type) [0]);
68 PropertyInfo has_value_pi = TypeManager.GetPredefinedProperty (type, "HasValue", Location.Null, Type.EmptyTypes);
69 PropertyInfo value_pi = TypeManager.GetPredefinedProperty (type, "Value", Location.Null, Type.EmptyTypes);
70 GetValueOrDefault = TypeManager.GetPredefinedMethod (type, "GetValueOrDefault", Location.Null, Type.EmptyTypes);
72 HasValue = has_value_pi.GetGetMethod (false);
73 Value = value_pi.GetGetMethod (false);
75 // When compiling corlib
76 if (TypeManager.IsBeingCompiled (type)) {
77 TypeContainer tc = TypeManager.LookupGenericTypeContainer (type);
79 // TODO: check for correct overload
80 Constructor c = ((Constructor) tc.InstanceConstructors [0]);
82 Constructor = TypeBuilder.GetConstructor (type, c.ConstructorBuilder);
87 if (TypeManager.IsBeingCompiled (UnderlyingType)) {
88 ConstructorInfo cinfo = TypeManager.DropGenericTypeArguments (type).GetConstructors ()[0];
89 Constructor = TypeBuilder.GetConstructor (type, cinfo);
94 Constructor = type.GetConstructor (new Type[] { UnderlyingType });
98 public class Unwrap : Expression, IMemoryLocation, IAssignMethod
104 readonly bool useDefaultValue;
106 Unwrap (Expression expr, bool useDefaultValue)
109 this.loc = expr.Location;
110 this.useDefaultValue = useDefaultValue;
112 info = new NullableInfo (expr.Type);
113 type = info.UnderlyingType;
114 eclass = expr.eclass;
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 Unwrap Create (Expression expr, bool useDefaultValue)
131 return new Unwrap (expr, useDefaultValue);
134 public override Expression CreateExpressionTree (ResolveContext ec)
136 return expr.CreateExpressionTree (ec);
139 protected override Expression DoResolve (ResolveContext ec)
144 public override Expression DoResolveLValue (ResolveContext ec, Expression right_side)
146 return DoResolve (ec);
149 public override void Emit (EmitContext ec)
153 Invocation.EmitCall (ec, false, this, info.GetValueOrDefault, null, loc);
155 Invocation.EmitCall (ec, false, this, info.Value, null, loc);
158 public void EmitCheck (EmitContext ec)
161 Invocation.EmitCall (ec, false, this, info.HasValue, null, loc);
164 public override bool Equals (object obj)
166 Unwrap uw = obj as Unwrap;
167 return uw != null && expr.Equals (uw.expr);
170 public Expression Original {
176 public override int GetHashCode ()
178 return expr.GetHashCode ();
181 public override bool IsNull {
187 void Store (EmitContext ec)
189 if (expr is VariableReference)
196 LocalVariable.Store (ec);
199 public void Load (EmitContext ec)
201 if (expr is VariableReference)
204 LocalVariable.Emit (ec);
207 public override System.Linq.Expressions.Expression MakeExpression (BuilderContext ctx)
209 return expr.MakeExpression (ctx);
212 public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
214 type = storey.MutateType (type);
215 info.Constructor = storey.MutateConstructor (info.Constructor);
216 info.HasValue = storey.MutateGenericMethod (info.HasValue);
217 info.GetValueOrDefault = storey.MutateGenericMethod (info.GetValueOrDefault);
218 info.Value = storey.MutateGenericMethod (info.Value);
221 public void AddressOf (EmitContext ec, AddressOp mode)
223 IMemoryLocation ml = expr as VariableReference;
225 ml.AddressOf (ec, mode);
227 LocalVariable.AddressOf (ec, mode);
231 // Keeps result of non-variable expression
233 LocalTemporary LocalVariable {
236 temp = new LocalTemporary (info.Type);
241 public void Emit (EmitContext ec, bool leave_copy)
249 public void EmitAssign (EmitContext ec, Expression source,
250 bool leave_copy, bool prepare_for_load)
252 InternalWrap wrap = new InternalWrap (source, info, loc);
253 ((IAssignMethod) expr).EmitAssign (ec, wrap, leave_copy, false);
256 protected class InternalWrap : Expression
258 public Expression expr;
259 public NullableInfo info;
261 public InternalWrap (Expression expr, NullableInfo info, Location loc)
268 eclass = ExprClass.Value;
271 public override Expression CreateExpressionTree (ResolveContext ec)
273 throw new NotSupportedException ("ET");
276 protected override Expression DoResolve (ResolveContext ec)
281 public override void Emit (EmitContext ec)
284 ec.ig.Emit (OpCodes.Newobj, info.Constructor);
289 public class Wrap : TypeCast
291 readonly NullableInfo info;
293 protected Wrap (Expression expr, Type type)
296 info = new NullableInfo (type);
297 eclass = ExprClass.Value;
300 public Expression Child {
301 get { return child; }
304 public override Expression CreateExpressionTree (ResolveContext ec)
306 TypeCast child_cast = child as TypeCast;
307 if (child_cast != null) {
309 return child_cast.CreateExpressionTree (ec);
312 return base.CreateExpressionTree (ec);
315 public static Expression Create (Expression expr, Type type)
318 // Avoid unwraping and wraping of the same type
320 Unwrap unwrap = expr as Unwrap;
321 if (unwrap != null && TypeManager.IsEqual (expr.Type, TypeManager.TypeToCoreType (TypeManager.GetTypeArguments (type) [0])))
322 return unwrap.Original;
324 return new Wrap (expr, type);
327 public override void Emit (EmitContext ec)
330 ec.ig.Emit (OpCodes.Newobj, info.Constructor);
335 // Represents null literal lifted to nullable type
337 public class LiftedNull : NullConstant, IMemoryLocation
339 private LiftedNull (Type nullable_type, Location loc)
340 : base (nullable_type, loc)
342 eclass = ExprClass.Value;
345 public static Constant Create (Type nullable, Location loc)
347 return new LiftedNull (nullable, loc);
350 public static Expression CreateFromExpression (ResolveContext ec, Expression e)
352 ec.Report.Warning (458, 2, e.Location, "The result of the expression is always `null' of type `{0}'",
353 TypeManager.CSharpName (e.Type));
355 return ReducedExpression.Create (Create (e.Type, e.Location), e);
358 public override void Emit (EmitContext ec)
360 // TODO: generate less temporary variables
361 LocalTemporary value_target = new LocalTemporary (type);
363 value_target.AddressOf (ec, AddressOp.Store);
364 ec.ig.Emit (OpCodes.Initobj, type);
365 value_target.Emit (ec);
368 public void AddressOf (EmitContext ec, AddressOp Mode)
370 LocalTemporary value_target = new LocalTemporary (type);
372 value_target.AddressOf (ec, AddressOp.Store);
373 ec.ig.Emit (OpCodes.Initobj, type);
374 ((IMemoryLocation) value_target).AddressOf (ec, Mode);
379 // Generic lifting expression, supports all S/S? -> T/T? cases
381 public class Lifted : Expression, IMemoryLocation
383 Expression expr, null_value;
386 public Lifted (Expression expr, Unwrap unwrap, Type type)
389 this.unwrap = unwrap;
390 this.loc = expr.Location;
394 public Lifted (Expression expr, Expression unwrap, Type type)
395 : this (expr, unwrap as Unwrap, type)
399 public override Expression CreateExpressionTree (ResolveContext ec)
401 return expr.CreateExpressionTree (ec);
404 protected override Expression DoResolve (ResolveContext ec)
407 // It's null when lifting non-nullable type
409 if (unwrap == null) {
410 // S -> T? is wrap only
411 if (TypeManager.IsNullableType (type))
412 return Wrap.Create (expr, type);
414 // S -> T can be simplified
418 // Wrap target for T?
419 if (TypeManager.IsNullableType (type)) {
420 expr = Wrap.Create (expr, type);
424 null_value = LiftedNull.Create (type, loc);
426 null_value = new NullConstant (type, loc);
429 eclass = ExprClass.Value;
433 public override void Emit (EmitContext ec)
435 ILGenerator ig = ec.ig;
436 Label is_null_label = ig.DefineLabel ();
437 Label end_label = ig.DefineLabel ();
439 unwrap.EmitCheck (ec);
440 ig.Emit (OpCodes.Brfalse, is_null_label);
444 ig.Emit (OpCodes.Br, end_label);
445 ig.MarkLabel (is_null_label);
447 null_value.Emit (ec);
448 ig.MarkLabel (end_label);
451 public void AddressOf (EmitContext ec, AddressOp mode)
453 unwrap.AddressOf (ec, mode);
457 public class LiftedUnaryOperator : Unary, IMemoryLocation
460 Expression user_operator;
462 public LiftedUnaryOperator (Unary.Operator op, Expression expr)
467 public void AddressOf (EmitContext ec, AddressOp mode)
469 unwrap.AddressOf (ec, mode);
472 public override Expression CreateExpressionTree (ResolveContext ec)
474 if (user_operator != null)
475 return user_operator.CreateExpressionTree (ec);
477 if (Oper == Operator.UnaryPlus)
478 return Expr.CreateExpressionTree (ec);
480 return base.CreateExpressionTree (ec);
483 protected override Expression DoResolve (ResolveContext ec)
485 unwrap = Unwrap.Create (Expr, false);
489 Expression res = base.ResolveOperator (ec, unwrap);
491 if (user_operator == null)
494 res = Expr = LiftExpression (ec, Expr);
500 eclass = ExprClass.Value;
505 public override void Emit (EmitContext ec)
507 ILGenerator ig = ec.ig;
508 Label is_null_label = ig.DefineLabel ();
509 Label end_label = ig.DefineLabel ();
511 unwrap.EmitCheck (ec);
512 ig.Emit (OpCodes.Brfalse, is_null_label);
514 NullableInfo ni = new NullableInfo (type);
516 if (user_operator != null) {
517 user_operator.Emit (ec);
519 EmitOperator (ec, ni.UnderlyingType);
522 ig.Emit (OpCodes.Newobj, ni.Constructor);
523 ig.Emit (OpCodes.Br_S, end_label);
525 ig.MarkLabel (is_null_label);
526 LiftedNull.Create (type, loc).Emit (ec);
528 ig.MarkLabel (end_label);
531 Expression LiftExpression (ResolveContext ec, Expression expr)
533 TypeExpr lifted_type = new NullableType (expr.Type, expr.Location);
534 lifted_type = lifted_type.ResolveAsTypeTerminal (ec, false);
535 if (lifted_type == null)
538 expr.Type = lifted_type.Type;
542 protected override Expression ResolveEnumOperator (ResolveContext ec, Expression expr)
544 expr = base.ResolveEnumOperator (ec, expr);
548 Expr = LiftExpression (ec, Expr);
549 return LiftExpression (ec, expr);
552 protected override Expression ResolveUserOperator (ResolveContext ec, Expression expr)
554 expr = base.ResolveUserOperator (ec, expr);
559 // When a user operator is of non-nullable type
561 if (Expr is Unwrap) {
562 user_operator = LiftExpression (ec, expr);
563 return user_operator;
570 public class LiftedBinaryOperator : Binary
572 Unwrap left_unwrap, right_unwrap;
573 bool left_null_lifted, right_null_lifted;
574 Expression left_orig, right_orig;
575 Expression user_operator;
576 ConstructorInfo wrap_ctor;
578 public LiftedBinaryOperator (Binary.Operator op, Expression left, Expression right,
580 : base (op, left, right)
585 public override Expression CreateExpressionTree (ResolveContext ec)
587 if (user_operator != null)
588 return user_operator.CreateExpressionTree (ec);
590 return base.CreateExpressionTree (ec);
594 // CSC 2 has this behavior, it allows structs to be compared
595 // with the null literal *outside* of a generics context and
596 // inlines that as true or false.
598 Expression CreateNullConstant (ResolveContext ec, Expression expr)
600 // FIXME: Handle side effect constants
601 Constant c = new BoolConstant (Oper == Operator.Inequality, loc).Resolve (ec);
603 if ((Oper & Operator.EqualityMask) != 0) {
604 ec.Report.Warning (472, 2, loc, "The result of comparing value type `{0}' with null is `{1}'",
605 TypeManager.CSharpName (expr.Type), c.AsString ());
607 ec.Report.Warning (464, 2, loc, "The result of comparing type `{0}' with null is always `{1}'",
608 TypeManager.CSharpName (expr.Type), c.AsString ());
611 return ReducedExpression.Create (c, this);
614 protected override Expression DoResolve (ResolveContext ec)
616 if ((Oper & Operator.LogicalMask) != 0) {
617 Error_OperatorCannotBeApplied (ec, left, right);
621 bool use_default_call = (Oper & (Operator.BitwiseMask | Operator.EqualityMask)) != 0;
623 if (TypeManager.IsNullableType (left.Type)) {
624 left = left_unwrap = Unwrap.Create (left, use_default_call);
630 if (TypeManager.IsNullableType (right.Type)) {
631 right = right_unwrap = Unwrap.Create (right, use_default_call);
637 // Some details are in 6.4.2, 7.2.7
638 // Arguments can be lifted for equal operators when the return type is bool and both
639 // arguments are of same type
641 if (left_orig.IsNull) {
643 left_null_lifted = true;
644 type = TypeManager.bool_type;
647 if (right_orig.IsNull) {
649 right_null_lifted = true;
650 type = TypeManager.bool_type;
653 eclass = ExprClass.Value;
654 return DoResolveCore (ec, left_orig, right_orig);
657 void EmitBitwiseBoolean (EmitContext ec)
659 ILGenerator ig = ec.ig;
661 Label load_left = ig.DefineLabel ();
662 Label load_right = ig.DefineLabel ();
663 Label end_label = ig.DefineLabel ();
665 left_unwrap.Emit (ec);
666 ig.Emit (OpCodes.Brtrue_S, load_right);
668 right_unwrap.Emit (ec);
669 ig.Emit (OpCodes.Brtrue_S, load_left);
671 left_unwrap.EmitCheck (ec);
672 ig.Emit (OpCodes.Brfalse_S, load_right);
675 ig.MarkLabel (load_left);
677 if (Oper == Operator.BitwiseAnd) {
678 left_unwrap.Load (ec);
680 right_unwrap.Load (ec);
681 right_unwrap = left_unwrap;
683 ig.Emit (OpCodes.Br_S, end_label);
686 ig.MarkLabel (load_right);
687 right_unwrap.Load (ec);
689 ig.MarkLabel (end_label);
693 // Emits optimized equality or inequality operator when possible
695 void EmitEquality (EmitContext ec)
697 ILGenerator ig = ec.ig;
700 // Either left or right is null
702 if (left_unwrap != null && (right_null_lifted || right.IsNull)) {
703 left_unwrap.EmitCheck (ec);
704 if (Oper == Binary.Operator.Equality) {
705 ig.Emit (OpCodes.Ldc_I4_0);
706 ig.Emit (OpCodes.Ceq);
711 if (right_unwrap != null && (left_null_lifted || left.IsNull)) {
712 right_unwrap.EmitCheck (ec);
713 if (Oper == Binary.Operator.Equality) {
714 ig.Emit (OpCodes.Ldc_I4_0);
715 ig.Emit (OpCodes.Ceq);
720 Label dissimilar_label = ig.DefineLabel ();
721 Label end_label = ig.DefineLabel ();
723 if (user_operator != null) {
724 user_operator.Emit (ec);
725 ig.Emit (Oper == Operator.Equality ? OpCodes.Brfalse_S : OpCodes.Brtrue_S, dissimilar_label);
730 ig.Emit (OpCodes.Bne_Un_S, dissimilar_label);
733 if (left_unwrap != null)
734 left_unwrap.EmitCheck (ec);
736 if (right_unwrap != null)
737 right_unwrap.EmitCheck (ec);
739 if (left_unwrap != null && right_unwrap != null) {
740 if (Oper == Operator.Inequality)
741 ig.Emit (OpCodes.Xor);
743 ig.Emit (OpCodes.Ceq);
745 if (Oper == Operator.Inequality) {
746 ig.Emit (OpCodes.Ldc_I4_0);
747 ig.Emit (OpCodes.Ceq);
751 ig.Emit (OpCodes.Br_S, end_label);
753 ig.MarkLabel (dissimilar_label);
754 if (Oper == Operator.Inequality)
755 ig.Emit (OpCodes.Ldc_I4_1);
757 ig.Emit (OpCodes.Ldc_I4_0);
759 ig.MarkLabel (end_label);
762 public override void EmitBranchable (EmitContext ec, Label target, bool onTrue)
765 ec.ig.Emit (onTrue ? OpCodes.Brtrue : OpCodes.Brfalse, target);
768 public override void Emit (EmitContext ec)
771 // Optimize same expression operation
773 if (right_unwrap != null && right.Equals (left))
774 right_unwrap = left_unwrap;
776 if (user_operator == null && IsBitwiseBoolean) {
777 EmitBitwiseBoolean (ec);
781 if ((Oper & Operator.EqualityMask) != 0) {
786 ILGenerator ig = ec.ig;
788 Label is_null_label = ig.DefineLabel ();
789 Label end_label = ig.DefineLabel ();
791 if (left_unwrap != null) {
792 left_unwrap.EmitCheck (ec);
793 ig.Emit (OpCodes.Brfalse, is_null_label);
797 // Don't emit HasValue check when left and right expressions are same
799 if (right_unwrap != null && !left.Equals (right)) {
800 right_unwrap.EmitCheck (ec);
801 ig.Emit (OpCodes.Brfalse, is_null_label);
804 EmitOperator (ec, left.Type);
806 if (wrap_ctor != null)
807 ig.Emit (OpCodes.Newobj, wrap_ctor);
809 ig.Emit (OpCodes.Br_S, end_label);
810 ig.MarkLabel (is_null_label);
812 if ((Oper & Operator.ComparisonMask) != 0) {
813 ig.Emit (OpCodes.Ldc_I4_0);
815 LiftedNull.Create (type, loc).Emit (ec);
818 ig.MarkLabel (end_label);
821 protected override void EmitOperator (EmitContext ec, Type l)
823 if (user_operator != null) {
824 user_operator.Emit (ec);
828 if (TypeManager.IsNullableType (l))
829 l = TypeManager.TypeToCoreType (TypeManager.GetTypeArguments (l) [0]);
831 base.EmitOperator (ec, l);
834 bool IsBitwiseBoolean {
836 return (Oper & Operator.BitwiseMask) != 0 && left_unwrap != null && right_unwrap != null &&
837 left_unwrap.Type == TypeManager.bool_type && right_unwrap.Type == TypeManager.bool_type;
841 Expression LiftResult (ResolveContext ec, Expression res_expr)
843 TypeExpr lifted_type;
846 // Avoid double conversion
848 if (left_unwrap == null || left_null_lifted || !TypeManager.IsEqual (left_unwrap.Type, left.Type) || (left_unwrap != null && right_null_lifted)) {
849 lifted_type = new NullableType (left.Type, loc);
850 lifted_type = lifted_type.ResolveAsTypeTerminal (ec, false);
851 if (lifted_type == null)
854 if (left is UserCast || left is TypeCast)
855 left.Type = lifted_type.Type;
857 left = EmptyCast.Create (left, lifted_type.Type);
860 if (right_unwrap == null || right_null_lifted || !TypeManager.IsEqual (right_unwrap.Type, right.Type) || (right_unwrap != null && left_null_lifted)) {
861 lifted_type = new NullableType (right.Type, loc);
862 lifted_type = lifted_type.ResolveAsTypeTerminal (ec, false);
863 if (lifted_type == null)
866 if (right is UserCast || right is TypeCast)
867 right.Type = lifted_type.Type;
869 right = EmptyCast.Create (right, lifted_type.Type);
872 if ((Oper & Operator.ComparisonMask) == 0) {
873 lifted_type = new NullableType (res_expr.Type, loc);
874 lifted_type = lifted_type.ResolveAsTypeTerminal (ec, false);
875 if (lifted_type == null)
878 wrap_ctor = new NullableInfo (lifted_type.Type).Constructor;
879 type = res_expr.Type = lifted_type.Type;
882 if (left_null_lifted) {
883 left = LiftedNull.Create (right.Type, left.Location);
885 if ((Oper & (Operator.ArithmeticMask | Operator.ShiftMask | Operator.BitwiseMask)) != 0)
886 return LiftedNull.CreateFromExpression (ec, res_expr);
889 // Value types and null comparison
891 if (right_unwrap == null || (Oper & Operator.RelationalMask) != 0)
892 return CreateNullConstant (ec, right_orig).Resolve (ec);
895 if (right_null_lifted) {
896 right = LiftedNull.Create (left.Type, right.Location);
898 if ((Oper & (Operator.ArithmeticMask | Operator.ShiftMask | Operator.BitwiseMask)) != 0)
899 return LiftedNull.CreateFromExpression (ec, res_expr);
902 // Value types and null comparison
904 if (left_unwrap == null || (Oper & Operator.RelationalMask) != 0)
905 return CreateNullConstant (ec, left_orig);
911 protected override Expression ResolveOperatorPredefined (ResolveContext ec, Binary.PredefinedOperator [] operators, bool primitives_only, Type enum_type)
913 Expression e = base.ResolveOperatorPredefined (ec, operators, primitives_only, enum_type);
915 if (e == this || enum_type != null)
916 return LiftResult (ec, e);
919 // 7.9.9 Equality operators and null
921 // The == and != operators permit one operand to be a value of a nullable type and
922 // the other to be the null literal, even if no predefined or user-defined operator
923 // (in unlifted or lifted form) exists for the operation.
925 if (e == null && (Oper & Operator.EqualityMask) != 0) {
926 if ((left_null_lifted && right_unwrap != null) || (right_null_lifted && left_unwrap != null))
927 return LiftResult (ec, this);
933 protected override Expression ResolveUserOperator (ResolveContext ec, Type l, Type r)
935 Expression expr = base.ResolveUserOperator (ec, l, r);
939 expr = LiftResult (ec, expr);
940 if (expr is Constant)
944 user_operator = expr;
949 public class NullCoalescingOperator : Expression
951 Expression left, right;
954 public NullCoalescingOperator (Expression left, Expression right, Location loc)
961 public override Expression CreateExpressionTree (ResolveContext ec)
963 if (left.Type == TypeManager.null_type)
964 ec.Report.Error (845, loc, "An expression tree cannot contain a coalescing operator with null left side");
966 UserCast uc = left as UserCast;
967 Expression conversion = null;
971 Arguments c_args = new Arguments (2);
972 c_args.Add (new Argument (uc.CreateExpressionTree (ec)));
973 c_args.Add (new Argument (left.CreateExpressionTree (ec)));
974 conversion = CreateExpressionFactoryCall (ec, "Lambda", c_args);
977 Arguments args = new Arguments (3);
978 args.Add (new Argument (left.CreateExpressionTree (ec)));
979 args.Add (new Argument (right.CreateExpressionTree (ec)));
980 if (conversion != null)
981 args.Add (new Argument (conversion));
983 return CreateExpressionFactoryCall (ec, "Coalesce", args);
986 Expression ConvertExpression (ResolveContext ec)
988 // TODO: ImplicitConversionExists should take care of this
989 if (left.eclass == ExprClass.MethodGroup)
992 Type ltype = left.Type;
995 // If left is a nullable type and an implicit conversion exists from right to underlying type of left,
996 // the result is underlying type of left
998 if (TypeManager.IsNullableType (ltype)) {
999 unwrap = Unwrap.Create (left, false);
1003 if (Convert.ImplicitConversionExists (ec, right, unwrap.Type)) {
1006 right = Convert.ImplicitConversion (ec, right, type, loc);
1009 } else if (TypeManager.IsReferenceType (ltype)) {
1010 if (Convert.ImplicitConversionExists (ec, right, ltype)) {
1012 // Reduce (constant ?? expr) to constant
1014 Constant lc = left as Constant;
1015 if (lc != null && !lc.IsDefaultValue)
1016 return new SideEffectConstant (lc, right, loc).Resolve (ec);
1019 // Reduce (left ?? null) to left OR (null-constant ?? right) to right
1021 if (right.IsNull || lc != null)
1022 return ReducedExpression.Create (lc != null ? right : left, this);
1024 right = Convert.ImplicitConversion (ec, right, ltype, loc);
1032 Type rtype = right.Type;
1033 if (!Convert.ImplicitConversionExists (ec, unwrap != null ? unwrap : left, rtype) || right.eclass == ExprClass.MethodGroup)
1037 // Reduce (null ?? right) to right
1040 return ReducedExpression.Create (right, this);
1042 left = Convert.ImplicitConversion (ec, unwrap != null ? unwrap : left, rtype, loc);
1047 protected override Expression DoResolve (ResolveContext ec)
1049 left = left.Resolve (ec);
1050 right = right.Resolve (ec);
1052 if (left == null || right == null)
1055 eclass = ExprClass.Value;
1057 Expression e = ConvertExpression (ec);
1059 Binary.Error_OperatorCannotBeApplied (ec, left, right, "??", loc);
1066 public override void Emit (EmitContext ec)
1068 ILGenerator ig = ec.ig;
1070 Label end_label = ig.DefineLabel ();
1072 if (unwrap != null) {
1073 Label is_null_label = ig.DefineLabel ();
1075 unwrap.EmitCheck (ec);
1076 ig.Emit (OpCodes.Brfalse, is_null_label);
1079 ig.Emit (OpCodes.Br, end_label);
1081 ig.MarkLabel (is_null_label);
1084 ig.MarkLabel (end_label);
1090 ig.Emit (OpCodes.Dup);
1091 ig.Emit (OpCodes.Brtrue, end_label);
1093 ig.Emit (OpCodes.Pop);
1096 ig.MarkLabel (end_label);
1099 public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
1101 left.MutateHoistedGenericType (storey);
1102 right.MutateHoistedGenericType (storey);
1103 type = storey.MutateType (type);
1106 protected override void CloneTo (CloneContext clonectx, Expression t)
1108 NullCoalescingOperator target = (NullCoalescingOperator) t;
1110 target.left = left.Clone (clonectx);
1111 target.right = right.Clone (clonectx);
1115 public class LiftedUnaryMutator : ExpressionStatement
1117 public readonly UnaryMutator.Mode Mode;
1119 UnaryMutator underlying;
1122 public LiftedUnaryMutator (UnaryMutator.Mode mode, Expression expr, Location loc)
1129 public override Expression CreateExpressionTree (ResolveContext ec)
1131 return new SimpleAssign (this, this).CreateExpressionTree (ec);
1134 protected override Expression DoResolve (ResolveContext ec)
1136 expr = expr.Resolve (ec);
1140 unwrap = Unwrap.Create (expr, false);
1144 underlying = (UnaryMutator) new UnaryMutator (Mode, unwrap).Resolve (ec);
1145 if (underlying == null)
1149 eclass = ExprClass.Value;
1154 void DoEmit (EmitContext ec, bool is_expr)
1156 ILGenerator ig = ec.ig;
1157 Label is_null_label = ig.DefineLabel ();
1158 Label end_label = ig.DefineLabel ();
1160 unwrap.EmitCheck (ec);
1161 ig.Emit (OpCodes.Brfalse, is_null_label);
1164 underlying.Emit (ec);
1165 ig.Emit (OpCodes.Br_S, end_label);
1167 underlying.EmitStatement (ec);
1170 ig.MarkLabel (is_null_label);
1172 LiftedNull.Create (type, loc).Emit (ec);
1174 ig.MarkLabel (end_label);
1177 public override void Emit (EmitContext ec)
1182 public override void EmitStatement (EmitContext ec)