Merge pull request #819 from brendanzagaeski/patch-1
[mono.git] / mcs / mcs / nullable.cs
1 //
2 // nullable.cs: Nullable types support
3 //
4 // Authors: Martin Baulig (martin@ximian.com)
5 //          Miguel de Icaza (miguel@ximian.com)
6 //          Marek Safar (marek.safar@gmail.com)
7 //
8 // Dual licensed under the terms of the MIT X11 or GNU GPL
9 //
10 // Copyright 2001, 2002, 2003 Ximian, Inc (http://www.ximian.com)
11 // Copyright 2004-2008 Novell, Inc
12 // Copyright 2011 Xamarin Inc
13 //
14
15 using System;
16 using SLE = System.Linq.Expressions;
17
18 #if STATIC
19 using IKVM.Reflection.Emit;
20 #else
21 using System.Reflection.Emit;
22 #endif
23         
24 namespace Mono.CSharp.Nullable
25 {
26         public class NullableType : TypeExpr
27         {
28                 readonly TypeSpec underlying;
29
30                 public NullableType (TypeSpec type, Location loc)
31                 {
32                         this.underlying = type;
33                         this.loc = loc;
34                 }
35
36                 public override TypeSpec ResolveAsType (IMemberContext ec)
37                 {
38                         eclass = ExprClass.Type;
39
40                         var otype = ec.Module.PredefinedTypes.Nullable.Resolve ();
41                         if (otype == null)
42                                 return null;
43
44                         TypeArguments args = new TypeArguments (new TypeExpression (underlying, loc));
45                         GenericTypeExpr ctype = new GenericTypeExpr (otype, args, loc);
46                         
47                         type = ctype.ResolveAsType (ec);
48                         return type;
49                 }
50         }
51
52         static class NullableInfo
53         {
54                 public static MethodSpec GetConstructor (TypeSpec nullableType)
55                 {
56                         return (MethodSpec) MemberCache.FindMember (nullableType,
57                                 MemberFilter.Constructor (ParametersCompiled.CreateFullyResolved (GetUnderlyingType (nullableType))), BindingRestriction.DeclaredOnly);
58                 }
59
60                 public static MethodSpec GetHasValue (TypeSpec nullableType)
61                 {
62                         return (MethodSpec) MemberCache.FindMember (nullableType,
63                                 MemberFilter.Method ("get_HasValue", 0, ParametersCompiled.EmptyReadOnlyParameters, null), BindingRestriction.None);
64                 }
65
66                 public static MethodSpec GetGetValueOrDefault (TypeSpec nullableType)
67                 {
68                         return (MethodSpec) MemberCache.FindMember (nullableType,
69                                 MemberFilter.Method ("GetValueOrDefault", 0, ParametersCompiled.EmptyReadOnlyParameters, null), BindingRestriction.None);
70                 }
71
72                 //
73                 // Don't use unless really required for correctness, see Unwrap::Emit
74                 //
75                 public static MethodSpec GetValue (TypeSpec nullableType)
76                 {
77                         return (MethodSpec) MemberCache.FindMember (nullableType,
78                                 MemberFilter.Method ("get_Value", 0, ParametersCompiled.EmptyReadOnlyParameters, null), BindingRestriction.None);
79                 }
80
81                 public static TypeSpec GetUnderlyingType (TypeSpec nullableType)
82                 {
83                         return ((InflatedTypeSpec) nullableType).TypeArguments[0];
84                 }
85
86                 public static TypeSpec GetEnumUnderlyingType (ModuleContainer module, TypeSpec nullableEnum)
87                 {
88                         return module.PredefinedTypes.Nullable.TypeSpec.MakeGenericType (module,
89                                 new[] { EnumSpec.GetUnderlyingType (GetUnderlyingType (nullableEnum)) });
90                 }
91         }
92
93         public class Unwrap : Expression, IMemoryLocation
94         {
95                 Expression expr;
96
97                 LocalTemporary temp;
98                 Expression temp_field;
99                 readonly bool useDefaultValue;
100
101                 public Unwrap (Expression expr, bool useDefaultValue = true)
102                 {
103                         this.expr = expr;
104                         this.loc = expr.Location;
105                         this.useDefaultValue = useDefaultValue;
106
107                         type = NullableInfo.GetUnderlyingType (expr.Type);
108                         eclass = expr.eclass;
109                 }
110
111                 public override bool ContainsEmitWithAwait ()
112                 {
113                         return expr.ContainsEmitWithAwait ();
114                 }
115
116                 // TODO: REMOVE
117                 public static Expression Create (Expression expr)
118                 {
119                         //
120                         // Avoid unwraping and wraping of same type
121                         //
122                         Wrap wrap = expr as Wrap;
123                         if (wrap != null)
124                                 return wrap.Child;
125
126                         return Create (expr, false);
127                 }
128
129                 public static Expression CreateUnwrapped (Expression expr)
130                 {
131                         //
132                         // Avoid unwraping and wraping of same type
133                         //
134                         Wrap wrap = expr as Wrap;
135                         if (wrap != null)
136                                 return wrap.Child;
137
138                         return Create (expr, true);
139                 }
140
141                 public static Unwrap Create (Expression expr, bool useDefaultValue)
142                 {
143                         return new Unwrap (expr, useDefaultValue);
144                 }
145                 
146                 public override Expression CreateExpressionTree (ResolveContext ec)
147                 {
148                         return expr.CreateExpressionTree (ec);
149                 }
150
151                 protected override Expression DoResolve (ResolveContext ec)
152                 {
153                         return this;
154                 }
155
156                 public override Expression DoResolveLValue (ResolveContext ec, Expression right_side)
157                 {
158                         expr = expr.DoResolveLValue (ec, right_side);
159                         return this;
160                 }
161
162                 public override void Emit (EmitContext ec)
163                 {
164                         Store (ec);
165
166                         var call = new CallEmitter ();
167                         call.InstanceExpression = this;
168
169                         //
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
173                         //
174                         if (useDefaultValue)
175                                 call.EmitPredefined (ec, NullableInfo.GetGetValueOrDefault (expr.Type), null);
176                         else
177                                 call.EmitPredefined (ec, NullableInfo.GetValue (expr.Type), null);
178                 }
179
180                 public void EmitCheck (EmitContext ec)
181                 {
182                         Store (ec);
183
184                         var call = new CallEmitter ();
185                         call.InstanceExpression = this;
186
187                         call.EmitPredefined (ec, NullableInfo.GetHasValue (expr.Type), null);
188                 }
189
190                 public override Expression EmitToField (EmitContext ec)
191                 {
192                         if (temp_field == null)
193                                 temp_field = this.expr.EmitToField (ec);
194                         
195                         return this;
196                 }
197
198                 public override bool Equals (object obj)
199                 {
200                         Unwrap uw = obj as Unwrap;
201                         return uw != null && expr.Equals (uw.expr);
202                 }
203
204                 public override void FlowAnalysis (FlowAnalysisContext fc)
205                 {
206                         expr.FlowAnalysis (fc);
207                 }
208
209                 public Expression Original {
210                         get {
211                                 return expr;
212                         }
213                 }
214                 
215                 public override int GetHashCode ()
216                 {
217                         return expr.GetHashCode ();
218                 }
219
220                 public override bool IsNull {
221                         get {
222                                 return expr.IsNull;
223                         }
224                 }
225
226                 public void Store (EmitContext ec)
227                 {
228                         if (temp != null || temp_field != null)
229                                 return;
230
231                         if (expr is VariableReference)
232                                 return;
233
234                         expr.Emit (ec);
235                         LocalVariable.Store (ec);
236                 }
237
238                 public void Load (EmitContext ec)
239                 {
240                         if (temp_field != null)
241                                 temp_field.Emit (ec);
242                         else if (expr is VariableReference)
243                                 expr.Emit (ec);
244                         else
245                                 LocalVariable.Emit (ec);
246                 }
247
248                 public override SLE.Expression MakeExpression (BuilderContext ctx)
249                 {
250                         return expr.MakeExpression (ctx);
251                 }
252
253                 public void AddressOf (EmitContext ec, AddressOp mode)
254                 {
255                         IMemoryLocation ml;
256
257                         if (temp_field != null) {
258                                 ml = temp_field as IMemoryLocation;
259                                 if (ml == null) {
260                                         var lt = new LocalTemporary (temp_field.Type);
261                                         temp_field.Emit (ec);
262                                         lt.Store (ec);
263                                         ml = lt;
264                                 }
265                         } else {
266                                 ml = expr as VariableReference;
267                         }
268
269                         if (ml != null)
270                                 ml.AddressOf (ec, mode);
271                         else
272                                 LocalVariable.AddressOf (ec, mode);
273                 }
274
275                 //
276                 // Keeps result of non-variable expression
277                 //
278                 LocalTemporary LocalVariable {
279                         get {
280                                 if (temp == null && temp_field == null)
281                                         temp = new LocalTemporary (expr.Type);
282                                 return temp;
283                         }
284                 }
285         }
286
287         //
288         // Calls get_Value method on nullable expression
289         //
290         public class UnwrapCall : CompositeExpression
291         {
292                 public UnwrapCall (Expression expr)
293                         : base (expr)
294                 {
295                 }
296
297                 protected override Expression DoResolve (ResolveContext rc)
298                 {
299                         base.DoResolve (rc);
300
301                         if (type != null)
302                                 type = NullableInfo.GetUnderlyingType (type);
303
304                         return this;
305                 }
306
307                 public override void Emit (EmitContext ec)
308                 {
309                         var call = new CallEmitter ();
310                         call.InstanceExpression = Child;
311                         call.EmitPredefined (ec, NullableInfo.GetValue (Child.Type), null);
312                 }
313         }
314
315         public class Wrap : TypeCast
316         {
317                 private Wrap (Expression expr, TypeSpec type)
318                         : base (expr, type)
319                 {
320                         eclass = ExprClass.Value;
321                 }
322
323                 public override Expression CreateExpressionTree (ResolveContext ec)
324                 {
325                         TypeCast child_cast = child as TypeCast;
326                         if (child_cast != null) {
327                                 child.Type = type;
328                                 return child_cast.CreateExpressionTree (ec);
329                         }
330
331                         var user_cast = child as UserCast;
332                         if (user_cast != null) {
333                                 child.Type = type;
334                                 return user_cast.CreateExpressionTree (ec);
335                         }
336
337                         return base.CreateExpressionTree (ec);
338                 }
339
340                 public static Expression Create (Expression expr, TypeSpec type)
341                 {
342                         //
343                         // Avoid unwraping and wraping of the same type
344                         //
345                         Unwrap unwrap = expr as Unwrap;
346                         if (unwrap != null && expr.Type == NullableInfo.GetUnderlyingType (type))
347                                 return unwrap.Original;
348                 
349                         return new Wrap (expr, type);
350                 }
351                 
352                 public override void Emit (EmitContext ec)
353                 {
354                         child.Emit (ec);
355                         ec.Emit (OpCodes.Newobj, NullableInfo.GetConstructor (type));
356                 }
357         }
358
359         //
360         // Represents null literal lifted to nullable type
361         //
362         public class LiftedNull : NullConstant, IMemoryLocation
363         {
364                 private LiftedNull (TypeSpec nullable_type, Location loc)
365                         : base (nullable_type, loc)
366                 {
367                         eclass = ExprClass.Value;
368                 }
369
370                 public static Constant Create (TypeSpec nullable, Location loc)
371                 {
372                         return new LiftedNull (nullable, loc);
373                 }
374
375                 public static Constant CreateFromExpression (ResolveContext rc, Expression e)
376                 {
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 ());
380                         }
381
382                         return ReducedExpression.Create (Create (e.Type, e.Location), e);
383                 }
384
385                 public override void Emit (EmitContext ec)
386                 {
387                         // TODO: generate less temporary variables
388                         LocalTemporary value_target = new LocalTemporary (type);
389
390                         value_target.AddressOf (ec, AddressOp.Store);
391                         ec.Emit (OpCodes.Initobj, type);
392                         value_target.Emit (ec);
393                         value_target.Release (ec);
394                 }
395
396                 public void AddressOf (EmitContext ec, AddressOp Mode)
397                 {
398                         LocalTemporary value_target = new LocalTemporary (type);
399                                 
400                         value_target.AddressOf (ec, AddressOp.Store);
401                         ec.Emit (OpCodes.Initobj, type);
402                         value_target.AddressOf (ec, Mode);
403                 }
404         }
405
406         //
407         // Generic lifting expression, supports all S/S? -> T/T? cases
408         //
409         public class LiftedConversion : Expression, IMemoryLocation
410         {
411                 Expression expr, null_value;
412                 Unwrap unwrap;
413
414                 public LiftedConversion (Expression expr, Unwrap unwrap, TypeSpec type)
415                 {
416                         this.expr = expr;
417                         this.unwrap = unwrap;
418                         this.loc = expr.Location;
419                         this.type = type;
420                 }
421
422                 public LiftedConversion (Expression expr, Expression unwrap, TypeSpec type)
423                         : this (expr, unwrap as Unwrap, type)
424                 {
425                 }
426
427                 public override bool ContainsEmitWithAwait ()
428                 {
429                         return unwrap.ContainsEmitWithAwait ();
430                 }
431                 
432                 public override Expression CreateExpressionTree (ResolveContext ec)
433                 {
434                         return expr.CreateExpressionTree (ec);
435                 }                       
436
437                 protected override Expression DoResolve (ResolveContext ec)
438                 {
439                         //
440                         // It's null when lifting non-nullable type
441                         //
442                         if (unwrap == null) {
443                                 // S -> T? is wrap only
444                                 if (type.IsNullableType)
445                                         return Wrap.Create (expr, type);
446
447                                 // S -> T can be simplified
448                                 return expr;
449                         }
450
451                         // Wrap target for T?
452                         if (type.IsNullableType) {
453                                 if (!expr.Type.IsNullableType) {
454                                         expr = Wrap.Create (expr, type);
455                                         if (expr == null)
456                                                 return null;
457                                 }
458
459                                 null_value = LiftedNull.Create (type, loc);
460                         } else if (TypeSpec.IsValueType (type)) {
461                                 null_value = LiftedNull.Create (type, loc);
462                         } else {
463                                 null_value = new NullConstant (type, loc);
464                         }
465
466                         eclass = ExprClass.Value;
467                         return this;
468                 }
469
470                 public override void Emit (EmitContext ec)
471                 {
472                         Label is_null_label = ec.DefineLabel ();
473                         Label end_label = ec.DefineLabel ();
474
475                         unwrap.EmitCheck (ec);
476                         ec.Emit (OpCodes.Brfalse, is_null_label);
477
478                         expr.Emit (ec);
479
480                         ec.Emit (OpCodes.Br, end_label);
481                         ec.MarkLabel (is_null_label);
482
483                         null_value.Emit (ec);
484
485                         ec.MarkLabel (end_label);
486                 }
487
488                 public override void FlowAnalysis (FlowAnalysisContext fc)
489                 {
490                         expr.FlowAnalysis (fc);
491                 }
492
493                 public void AddressOf (EmitContext ec, AddressOp mode)
494                 {
495                         unwrap.AddressOf (ec, mode);
496                 }
497         }
498
499         public class LiftedUnaryOperator : Unary, IMemoryLocation
500         {
501                 Unwrap unwrap;
502                 Expression user_operator;
503
504                 public LiftedUnaryOperator (Unary.Operator op, Expression expr, Location loc)
505                         : base (op, expr, loc)
506                 {
507                 }
508
509                 public void AddressOf (EmitContext ec, AddressOp mode)
510                 {
511                         unwrap.AddressOf (ec, mode);
512                 }
513
514                 public override Expression CreateExpressionTree (ResolveContext ec)
515                 {
516                         if (user_operator != null)
517                                 return user_operator.CreateExpressionTree (ec);
518
519                         if (Oper == Operator.UnaryPlus)
520                                 return Expr.CreateExpressionTree (ec);
521
522                         return base.CreateExpressionTree (ec);
523                 }
524
525                 protected override Expression DoResolve (ResolveContext ec)
526                 {
527                         unwrap = Unwrap.Create (Expr, false);
528                         if (unwrap == null)
529                                 return null;
530
531                         Expression res = base.ResolveOperator (ec, unwrap);
532                         if (res != this) {
533                                 if (user_operator == null)
534                                         return res;
535                         } else {
536                                 res = Expr = LiftExpression (ec, Expr);
537                         }
538
539                         if (res == null)
540                                 return null;
541
542                         eclass = ExprClass.Value;
543                         type = res.Type;
544                         return this;
545                 }
546
547                 public override void Emit (EmitContext ec)
548                 {
549                         Label is_null_label = ec.DefineLabel ();
550                         Label end_label = ec.DefineLabel ();
551
552                         unwrap.EmitCheck (ec);
553                         ec.Emit (OpCodes.Brfalse, is_null_label);
554
555                         if (user_operator != null) {
556                                 user_operator.Emit (ec);
557                         } else {
558                                 EmitOperator (ec, NullableInfo.GetUnderlyingType (type));
559                         }
560
561                         ec.Emit (OpCodes.Newobj, NullableInfo.GetConstructor (type));
562                         ec.Emit (OpCodes.Br_S, end_label);
563
564                         ec.MarkLabel (is_null_label);
565                         LiftedNull.Create (type, loc).Emit (ec);
566
567                         ec.MarkLabel (end_label);
568                 }
569
570                 static Expression LiftExpression (ResolveContext ec, Expression expr)
571                 {
572                         var lifted_type = new NullableType (expr.Type, expr.Location);
573                         if (lifted_type.ResolveAsType (ec) == null)
574                                 return null;
575
576                         expr.Type = lifted_type.Type;
577                         return expr;
578                 }
579
580                 protected override Expression ResolveEnumOperator (ResolveContext ec, Expression expr, TypeSpec[] predefined)
581                 {
582                         expr = base.ResolveEnumOperator (ec, expr, predefined);
583                         if (expr == null)
584                                 return null;
585
586                         Expr = LiftExpression (ec, Expr);
587                         return LiftExpression (ec, expr);
588                 }
589
590                 protected override Expression ResolveUserOperator (ResolveContext ec, Expression expr)
591                 {
592                         expr = base.ResolveUserOperator (ec, expr);
593                         if (expr == null)
594                                 return null;
595
596                         //
597                         // When a user operator is of non-nullable type
598                         //
599                         if (Expr is Unwrap) {
600                                 user_operator = LiftExpression (ec, expr);
601                                 return user_operator;
602                         }
603
604                         return expr;
605                 }
606         }
607
608         //
609         // Lifted version of binary operators
610         //
611         class LiftedBinaryOperator : Expression
612         {
613                 public LiftedBinaryOperator (Binary b)
614                 {
615                         this.Binary = b;
616                         this.loc = b.Location;
617                 }
618
619                 public Binary Binary { get; private set; }
620
621                 public Expression Left { get; set; }
622
623                 public Expression Right { get; set; }
624
625                 public Unwrap UnwrapLeft { get; set; }
626
627                 public Unwrap UnwrapRight { get; set; }
628
629                 public MethodSpec UserOperator { get; set; }
630
631                 bool IsBitwiseBoolean {
632                         get {
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));
636                         }
637                 }
638
639                 public override bool ContainsEmitWithAwait ()
640                 {
641                         return Left.ContainsEmitWithAwait () || Right.ContainsEmitWithAwait ();
642                 }
643
644                 public override Expression CreateExpressionTree (ResolveContext rc)
645                 {
646                         if (UserOperator != null) {
647                                 Arguments args = new Arguments (2);
648                                 args.Add (new Argument (Binary.Left));
649                                 args.Add (new Argument (Binary.Right));
650
651                                 var method = new UserOperatorCall (UserOperator, args, Binary.CreateExpressionTree, loc);
652                                 return method.CreateExpressionTree (rc);
653                         }
654
655                         return Binary.CreateExpressionTree (rc);
656                 }
657
658                 protected override Expression DoResolve (ResolveContext rc)
659                 {
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 }));
663
664                                 if (UnwrapRight == null && !Right.Type.IsNullableType)
665                                         Right = Wrap.Create (Right, rc.Module.PredefinedTypes.Nullable.TypeSpec.MakeGenericType (rc.Module, new[] { Right.Type }));
666                         } else {
667                                 if (UnwrapLeft == null && Left != null && Left.Type.IsNullableType) {
668                                         Left = Unwrap.CreateUnwrapped (Left);
669                                         UnwrapLeft = Left as Unwrap;
670                                 }
671
672                                 if (UnwrapRight == null && Right != null && Right.Type.IsNullableType) {
673                                         Right = Unwrap.CreateUnwrapped (Right);
674                                         UnwrapRight = Right as Unwrap;
675                                 }
676                         }
677
678                         type = Binary.Type;
679                         eclass = Binary.eclass; 
680
681                         return this;
682                 }
683
684                 public override void Emit (EmitContext ec)
685                 {
686                         if (IsBitwiseBoolean && UserOperator == null) {
687                                 EmitBitwiseBoolean (ec);
688                                 return;
689                         }
690
691                         if ((Binary.Oper & Binary.Operator.EqualityMask) != 0) {
692                                 EmitEquality (ec);
693                                 return;
694                         }
695
696                         Label is_null_label = ec.DefineLabel ();
697                         Label end_label = ec.DefineLabel ();
698
699                         if (ec.HasSet (BuilderContext.Options.AsyncBody) && Right.ContainsEmitWithAwait ()) {
700                                 Left = Left.EmitToField (ec);
701                                 Right = Right.EmitToField (ec);
702                         }
703
704                         if (UnwrapLeft != null) {
705                                 UnwrapLeft.EmitCheck (ec);
706                         }
707
708                         //
709                         // Don't emit HasValue check when left and right expressions are same
710                         //
711                         if (UnwrapRight != null && !Binary.Left.Equals (Binary.Right)) {
712                                 UnwrapRight.EmitCheck (ec);
713                                 if (UnwrapLeft != null) {
714                                         ec.Emit (OpCodes.And);
715                                 }
716                         }
717
718                         ec.Emit (OpCodes.Brfalse, is_null_label);
719
720                         if (UserOperator != null) {
721                                 var args = new Arguments (2);
722                                 args.Add (new Argument (Left));
723                                 args.Add (new Argument (Right));
724
725                                 var call = new CallEmitter ();
726                                 call.EmitPredefined (ec, UserOperator, args);
727                         } else {
728                                 Binary.EmitOperator (ec, Left, Right);
729                         }
730
731                         //
732                         // Wrap the result when the operator return type is nullable type
733                         //
734                         if (type.IsNullableType)
735                                 ec.Emit (OpCodes.Newobj, NullableInfo.GetConstructor (type));
736
737                         ec.Emit (OpCodes.Br_S, end_label);
738                         ec.MarkLabel (is_null_label);
739
740                         if ((Binary.Oper & Binary.Operator.ComparisonMask) != 0) {
741                                 ec.EmitInt (0);
742                         } else {
743                                 LiftedNull.Create (type, loc).Emit (ec);
744                         }
745
746                         ec.MarkLabel (end_label);
747                 }
748
749                 void EmitBitwiseBoolean (EmitContext ec)
750                 {
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 ();
755
756                         bool or = Binary.Oper == Binary.Operator.BitwiseOr;
757
758                         //
759                         // Both operands are bool? types
760                         //
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);
765                                 }
766
767                                 Left.Emit (ec);
768                                 ec.Emit (OpCodes.Brtrue_S, load_right);
769
770                                 Right.Emit (ec);
771                                 ec.Emit (OpCodes.Brtrue_S, load_left);
772
773                                 UnwrapLeft.EmitCheck (ec);
774                                 ec.Emit (OpCodes.Brfalse_S, load_right);
775
776                                 // load left
777                                 ec.MarkLabel (load_left);
778                                 if (or)
779                                         UnwrapRight.Load (ec);
780                                 else
781                                         UnwrapLeft.Load (ec);
782
783                                 ec.Emit (OpCodes.Br_S, end_label);
784
785                                 // load right
786                                 ec.MarkLabel (load_right);
787                                 if (or)
788                                         UnwrapLeft.Load (ec);
789                                 else
790                                         UnwrapRight.Load (ec);
791
792                                 ec.MarkLabel (end_label);
793                                 return;
794                         }
795
796                         //
797                         // Faster version when one operand is bool
798                         //
799                         if (UnwrapLeft == null) {
800                                 //
801                                 // (bool, bool?)
802                                 //
803                                 // Optimizes remaining (false & bool?), (true | bool?) which are not easy to handle
804                                 // in binary expression reduction
805                                 //
806                                 var c = Left as BoolConstant;
807                                 if (c != null) {
808                                         // Keep evaluation order
809                                         UnwrapRight.Store (ec);
810
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);
816
817                                         UnwrapRight.Load (ec);
818                                         ec.Emit (OpCodes.Br_S, end_label);
819
820                                         ec.MarkLabel (is_null_label);
821                                         LiftedNull.Create (type, loc).Emit (ec);
822                                 } else {
823                                         Left.Emit (ec);
824                                         ec.Emit (or ? OpCodes.Brfalse_S : OpCodes.Brtrue_S, load_right);
825
826                                         ec.EmitInt (or ? 1 : 0);
827                                         ec.Emit (OpCodes.Newobj, NullableInfo.GetConstructor (type));
828
829                                         ec.Emit (OpCodes.Br_S, end_label);
830
831                                         ec.MarkLabel (load_right);
832                                         UnwrapRight.Original.Emit (ec);
833                                 }
834                         } else {
835                                 //
836                                 // (bool?, bool)
837                                 //
838                                 // Keep left-right evaluation order
839                                 UnwrapLeft.Store (ec);
840
841                                 //
842                                 // Optimizes remaining (bool? & false), (bool? | true) which are not easy to handle
843                                 // in binary expression reduction
844                                 //
845                                 var c = Right as BoolConstant;
846                                 if (c != null) {
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);
852
853                                         UnwrapLeft.Load (ec);
854                                         ec.Emit (OpCodes.Br_S, end_label);
855
856                                         ec.MarkLabel (is_null_label);
857                                         LiftedNull.Create (type, loc).Emit (ec);
858                                 } else {
859                                         Right.Emit (ec);
860                                         ec.Emit (or ? OpCodes.Brfalse_S : OpCodes.Brtrue_S, load_right);
861
862                                         ec.EmitInt (or ? 1 : 0);
863                                         ec.Emit (OpCodes.Newobj, NullableInfo.GetConstructor (type));
864
865                                         ec.Emit (OpCodes.Br_S, end_label);
866
867                                         ec.MarkLabel (load_right);
868
869                                         UnwrapLeft.Load (ec);
870                                 }
871                         }
872
873                         ec.MarkLabel (end_label);
874                 }
875
876                 //
877                 // Emits optimized equality or inequality operator when possible
878                 //
879                 void EmitEquality (EmitContext ec)
880                 {
881                         //
882                         // Either left or right is null
883                         // 
884                         if (UnwrapLeft != null && Binary.Right.IsNull) { // TODO: Optimize for EmitBranchable
885                                 //
886                                 // left.HasValue == false 
887                                 //
888                                 UnwrapLeft.EmitCheck (ec);
889                                 if (Binary.Oper == Binary.Operator.Equality) {
890                                         ec.EmitInt (0);
891                                         ec.Emit (OpCodes.Ceq);
892                                 }
893                                 return;
894                         }
895
896                         if (UnwrapRight != null && Binary.Left.IsNull) {
897                                 //
898                                 // right.HasValue == false 
899                                 //
900                                 UnwrapRight.EmitCheck (ec);
901                                 if (Binary.Oper == Binary.Operator.Equality) {
902                                         ec.EmitInt (0);
903                                         ec.Emit (OpCodes.Ceq);
904                                 }
905                                 return;
906                         }
907
908                         Label dissimilar_label = ec.DefineLabel ();
909                         Label end_label = ec.DefineLabel ();
910
911                         if (UserOperator != null) {
912                                 var left = Left;
913
914                                 if (UnwrapLeft != null) {
915                                         UnwrapLeft.EmitCheck (ec);
916                                 } else {
917                                         // Keep evaluation order same
918                                         if (!(Left is VariableReference)) {
919                                                 Left.Emit (ec);
920                                                 var lt = new LocalTemporary (Left.Type);
921                                                 lt.Store (ec);
922                                                 left = lt;
923                                         }
924                                 }
925
926                                 if (UnwrapRight != null) {
927                                         UnwrapRight.EmitCheck (ec);
928
929                                         if (UnwrapLeft != null) {
930                                                 ec.Emit (OpCodes.Bne_Un, dissimilar_label);
931
932                                                 Label compare_label = ec.DefineLabel ();
933                                                 UnwrapLeft.EmitCheck (ec);
934                                                 ec.Emit (OpCodes.Brtrue, compare_label);
935
936                                                 if (Binary.Oper == Binary.Operator.Equality)
937                                                         ec.EmitInt (1);
938                                                 else
939                                                         ec.EmitInt (0);
940
941                                                 ec.Emit (OpCodes.Br, end_label);
942
943                                                 ec.MarkLabel (compare_label);
944                                         } else {
945                                                 ec.Emit (OpCodes.Brfalse, dissimilar_label);
946                                         }
947                                 } else {
948                                         ec.Emit (OpCodes.Brfalse, dissimilar_label);
949                                 }
950
951                                 var args = new Arguments (2);
952                                 args.Add (new Argument (left));
953                                 args.Add (new Argument (Right));
954
955                                 var call = new CallEmitter ();
956                                 call.EmitPredefined (ec, UserOperator, args);
957                         } else {
958                                 if (ec.HasSet (BuilderContext.Options.AsyncBody) && Binary.Right.ContainsEmitWithAwait ()) {
959                                         Left = Left.EmitToField (ec);
960                                         Right = Right.EmitToField (ec);
961                                 }
962
963                                 //
964                                 // Emit underlying value comparison first.
965                                 //
966                                 // For this code: int? a = 1; bool b = a == 1;
967                                 //
968                                 // We emit something similar to this. Expressions with side effects have local
969                                 // variable created by Unwrap expression
970                                 //
971                                 //      left.GetValueOrDefault ()
972                                 //      right
973                                 //      bne.un.s   dissimilar_label
974                                 //  left.HasValue
975                                 //      br.s       end_label
976                                 // dissimilar_label:
977                                 //      ldc.i4.0
978                                 // end_label:
979                                 //
980
981                                 Left.Emit (ec);
982                                 Right.Emit (ec);
983
984                                 ec.Emit (OpCodes.Bne_Un_S, dissimilar_label);
985
986                                 //
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
990                                 //
991                                 if (UnwrapLeft != null)
992                                         UnwrapLeft.EmitCheck (ec);
993
994                                 if (UnwrapRight != null)
995                                         UnwrapRight.EmitCheck (ec);
996
997                                 if (UnwrapLeft != null && UnwrapRight != null) {
998                                         if (Binary.Oper == Binary.Operator.Inequality)
999                                                 ec.Emit (OpCodes.Xor);
1000                                         else
1001                                                 ec.Emit (OpCodes.Ceq);
1002                                 } else {
1003                                         if (Binary.Oper == Binary.Operator.Inequality) {
1004                                                 ec.EmitInt (0);
1005                                                 ec.Emit (OpCodes.Ceq);
1006                                         }
1007                                 }
1008                         }
1009
1010                         ec.Emit (OpCodes.Br_S, end_label);
1011
1012                         ec.MarkLabel (dissimilar_label);
1013                         if (Binary.Oper == Binary.Operator.Inequality)
1014                                 ec.EmitInt (1);
1015                         else
1016                                 ec.EmitInt (0);
1017
1018                         ec.MarkLabel (end_label);
1019                 }
1020
1021                 public override void FlowAnalysis (FlowAnalysisContext fc)
1022                 {
1023                         Binary.FlowAnalysis (fc);
1024                 }
1025
1026                 public override SLE.Expression MakeExpression (BuilderContext ctx)
1027                 {
1028                         return Binary.MakeExpression (ctx, Left, Right);
1029                 }
1030         }
1031
1032         public class NullCoalescingOperator : Expression
1033         {
1034                 Expression left, right;
1035                 Unwrap unwrap;
1036
1037                 public NullCoalescingOperator (Expression left, Expression right)
1038                 {
1039                         this.left = left;
1040                         this.right = right;
1041                         this.loc = left.Location;
1042                 }
1043
1044                 public Expression LeftExpression {
1045                         get {
1046                                 return left;
1047                         }
1048                 }
1049
1050                 public Expression RightExpression {
1051                         get {
1052                                 return right;
1053                         }
1054                 }
1055                 
1056                 public override Expression CreateExpressionTree (ResolveContext ec)
1057                 {
1058                         if (left is NullLiteral)
1059                                 ec.Report.Error (845, loc, "An expression tree cannot contain a coalescing operator with null left side");
1060
1061                         UserCast uc = left as UserCast;
1062                         Expression conversion = null;
1063                         if (uc != null) {
1064                                 left = uc.Source;
1065
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);
1070                         }
1071
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));
1077                         
1078                         return CreateExpressionFactoryCall (ec, "Coalesce", args);
1079                 }
1080
1081                 Expression ConvertExpression (ResolveContext ec)
1082                 {
1083                         // TODO: ImplicitConversionExists should take care of this
1084                         if (left.eclass == ExprClass.MethodGroup)
1085                                 return null;
1086
1087                         TypeSpec ltype = left.Type;
1088
1089                         //
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
1092                         //
1093                         if (ltype.IsNullableType) {
1094                                 unwrap = Unwrap.Create (left, false);
1095                                 if (unwrap == null)
1096                                         return null;
1097
1098                                 //
1099                                 // Reduce (left ?? null) to left
1100                                 //
1101                                 if (right.IsNull)
1102                                         return ReducedExpression.Create (left, this);
1103
1104                                 if (Convert.ImplicitConversionExists (ec, right, unwrap.Type)) {
1105                                         left = unwrap;
1106                                         ltype = left.Type;
1107
1108                                         //
1109                                         // If right is a dynamic expression, the result type is dynamic
1110                                         //
1111                                         if (right.Type.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
1112                                                 type = right.Type;
1113
1114                                                 // Need to box underlying value type
1115                                                 left = Convert.ImplicitBoxingConversion (left, ltype, type);
1116                                                 return this;
1117                                         }
1118
1119                                         right = Convert.ImplicitConversion (ec, right, ltype, loc);
1120                                         type = ltype;
1121                                         return this;
1122                                 }
1123                         } else if (TypeSpec.IsReferenceType (ltype)) {
1124                                 if (Convert.ImplicitConversionExists (ec, right, ltype)) {
1125                                         //
1126                                         // If right is a dynamic expression, the result type is dynamic
1127                                         //
1128                                         if (right.Type.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
1129                                                 type = right.Type;
1130                                                 return this;
1131                                         }
1132
1133                                         //
1134                                         // Reduce ("foo" ?? expr) to expression
1135                                         //
1136                                         Constant lc = left as Constant;
1137                                         if (lc != null && !lc.IsDefaultValue)
1138                                                 return ReducedExpression.Create (lc, this);
1139
1140                                         //
1141                                         // Reduce (left ?? null) to left OR (null-constant ?? right) to right
1142                                         //
1143                                         if (right.IsNull || lc != null)
1144                                                 return ReducedExpression.Create (lc != null ? right : left, this);
1145
1146                                         right = Convert.ImplicitConversion (ec, right, ltype, loc);
1147                                         type = ltype;
1148                                         return this;
1149                                 }
1150
1151                                 //
1152                                 // Special case null ?? null
1153                                 //
1154                                 if (ltype == right.Type) {
1155                                         type = ltype;
1156                                         return this;
1157                                 }
1158                         } else {
1159                                 return null;
1160                         }
1161
1162                         TypeSpec rtype = right.Type;
1163                         if (!Convert.ImplicitConversionExists (ec, unwrap ?? left, rtype) || right.eclass == ExprClass.MethodGroup)
1164                                 return null;
1165
1166                         //
1167                         // Reduce (null ?? right) to right
1168                         //
1169                         if (left.IsNull)
1170                                 return ReducedExpression.Create (right, this).Resolve (ec);
1171
1172                         left = Convert.ImplicitConversion (ec, unwrap ?? left, rtype, loc);
1173                         type = rtype;
1174                         return this;
1175                 }
1176
1177                 public override bool ContainsEmitWithAwait ()
1178                 {
1179                         if (unwrap != null)
1180                                 return unwrap.ContainsEmitWithAwait () || right.ContainsEmitWithAwait ();
1181
1182                         return left.ContainsEmitWithAwait () || right.ContainsEmitWithAwait ();
1183                 }
1184
1185                 protected override Expression DoResolve (ResolveContext ec)
1186                 {
1187                         left = left.Resolve (ec);
1188                         right = right.Resolve (ec);
1189
1190                         if (left == null || right == null)
1191                                 return null;
1192
1193                         eclass = ExprClass.Value;
1194
1195                         Expression e = ConvertExpression (ec);
1196                         if (e == null) {
1197                                 Binary.Error_OperatorCannotBeApplied (ec, left, right, "??", loc);
1198                                 return null;
1199                         }
1200
1201                         return e;
1202                 }
1203
1204                 public override void Emit (EmitContext ec)
1205                 {
1206                         Label end_label = ec.DefineLabel ();
1207
1208                         if (unwrap != null) {
1209                                 Label is_null_label = ec.DefineLabel ();
1210
1211                                 unwrap.EmitCheck (ec);
1212                                 ec.Emit (OpCodes.Brfalse, is_null_label);
1213
1214                                 left.Emit (ec);
1215                                 ec.Emit (OpCodes.Br, end_label);
1216
1217                                 ec.MarkLabel (is_null_label);
1218                                 right.Emit (ec);
1219
1220                                 ec.MarkLabel (end_label);
1221                                 return;
1222                         }
1223
1224                         left.Emit (ec);
1225                         ec.Emit (OpCodes.Dup);
1226
1227                         // Only to make verifier happy
1228                         if (left.Type.IsGenericParameter)
1229                                 ec.Emit (OpCodes.Box, left.Type);
1230
1231                         ec.Emit (OpCodes.Brtrue, end_label);
1232
1233                         ec.Emit (OpCodes.Pop);
1234                         right.Emit (ec);
1235
1236                         ec.MarkLabel (end_label);
1237                 }
1238
1239                 public override void FlowAnalysis (FlowAnalysisContext fc)
1240                 {
1241                         left.FlowAnalysis (fc);
1242                         var left_da = fc.BranchDefiniteAssignment ();
1243                         right.FlowAnalysis (fc);
1244                         fc.DefiniteAssignment = left_da;
1245                 }
1246
1247                 protected override void CloneTo (CloneContext clonectx, Expression t)
1248                 {
1249                         NullCoalescingOperator target = (NullCoalescingOperator) t;
1250
1251                         target.left = left.Clone (clonectx);
1252                         target.right = right.Clone (clonectx);
1253                 }
1254                 
1255                 public override object Accept (StructuralVisitor visitor)
1256                 {
1257                         return visitor.Visit (this);
1258                 }
1259         }
1260
1261         class LiftedUnaryMutator : UnaryMutator
1262         {
1263                 public LiftedUnaryMutator (Mode mode, Expression expr, Location loc)
1264                         : base (mode, expr, loc)
1265                 {
1266                 }
1267
1268                 protected override Expression DoResolve (ResolveContext ec)
1269                 {
1270                         var orig_expr = expr;
1271
1272                         expr = Unwrap.Create (expr);
1273
1274                         var res = base.DoResolveOperation (ec);
1275
1276                         expr = orig_expr;
1277                         type = expr.Type;
1278
1279                         return res;
1280                 }
1281
1282                 protected override void EmitOperation (EmitContext ec)
1283                 {
1284                         Label is_null_label = ec.DefineLabel ();
1285                         Label end_label = ec.DefineLabel ();
1286
1287                         LocalTemporary lt = new LocalTemporary (type);
1288
1289                         // Value is on the stack
1290                         lt.Store (ec);
1291
1292                         var call = new CallEmitter ();
1293                         call.InstanceExpression = lt;
1294                         call.EmitPredefined (ec, NullableInfo.GetHasValue (expr.Type), null);
1295
1296                         ec.Emit (OpCodes.Brfalse, is_null_label);
1297
1298                         call = new CallEmitter ();
1299                         call.InstanceExpression = lt;
1300                         call.EmitPredefined (ec, NullableInfo.GetGetValueOrDefault (expr.Type), null);
1301
1302                         lt.Release (ec);
1303
1304                         base.EmitOperation (ec);
1305
1306                         ec.Emit (OpCodes.Newobj, NullableInfo.GetConstructor (type));
1307                         ec.Emit (OpCodes.Br_S, end_label);
1308
1309                         ec.MarkLabel (is_null_label);
1310                         LiftedNull.Create (type, loc).Emit (ec);
1311
1312                         ec.MarkLabel (end_label);
1313                 }
1314         }
1315 }
1316