Merge branch 'master' of github.com:mono/mono
[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 //
13
14 using System;
15 using System.Reflection;
16 using System.Reflection.Emit;
17         
18 namespace Mono.CSharp.Nullable
19 {
20         public class NullableType : TypeExpr
21         {
22                 TypeExpr underlying;
23
24                 public NullableType (TypeExpr underlying, Location l)
25                 {
26                         this.underlying = underlying;
27                         loc = l;
28
29                         eclass = ExprClass.Type;
30                 }
31
32                 public NullableType (TypeSpec type, Location loc)
33                         : this (new TypeExpression (type, loc), loc)
34                 { }
35
36                 protected override TypeExpr DoResolveAsTypeStep (IMemberContext ec)
37                 {
38                         if (TypeManager.generic_nullable_type == null) {
39                                 TypeManager.generic_nullable_type = TypeManager.CoreLookupType (ec.Compiler,
40                                         "System", "Nullable", 1, MemberKind.Struct, true);
41                         }
42
43                         TypeArguments args = new TypeArguments (underlying);
44                         GenericTypeExpr ctype = new GenericTypeExpr (TypeManager.generic_nullable_type, args, loc);
45                         return ctype.ResolveAsTypeTerminal (ec, false);
46                 }
47         }
48
49         static class NullableInfo
50         {
51                 public static MethodSpec GetConstructor (TypeSpec nullableType)
52                 {
53                         return TypeManager.GetPredefinedConstructor (nullableType, Location.Null, GetUnderlyingType (nullableType));
54                 }
55
56                 public static MethodSpec GetHasValue (TypeSpec nullableType)
57                 {
58                         return (MethodSpec) MemberCache.FindMember (nullableType,
59                                 MemberFilter.Method ("get_HasValue", 0, ParametersCompiled.EmptyReadOnlyParameters, null), BindingRestriction.None);
60                 }
61
62                 public static MethodSpec GetGetValueOrDefault (TypeSpec nullableType)
63                 {
64                         return (MethodSpec) MemberCache.FindMember (nullableType,
65                                 MemberFilter.Method ("GetValueOrDefault", 0, ParametersCompiled.EmptyReadOnlyParameters, null), BindingRestriction.None);
66                 }
67
68                 public static MethodSpec GetValue (TypeSpec nullableType)
69                 {
70                         return (MethodSpec) MemberCache.FindMember (nullableType,
71                                 MemberFilter.Method ("get_Value", 0, ParametersCompiled.EmptyReadOnlyParameters, null), BindingRestriction.None);
72                 }
73
74                 public static TypeSpec GetUnderlyingType (TypeSpec nullableType)
75                 {
76                         return ((InflatedTypeSpec) nullableType).TypeArguments[0];
77                 }
78
79                 public static bool IsNullableType (TypeSpec type)
80                 {
81                         throw new NotImplementedException ("net");
82                 }
83         }
84
85         public class Unwrap : Expression, IMemoryLocation, IAssignMethod
86         {
87                 Expression expr;
88
89                 LocalTemporary temp;
90                 readonly bool useDefaultValue;
91
92                 Unwrap (Expression expr, bool useDefaultValue)
93                 {
94                         this.expr = expr;
95                         this.loc = expr.Location;
96                         this.useDefaultValue = useDefaultValue;
97
98                         type = NullableInfo.GetUnderlyingType (expr.Type);
99                         eclass = expr.eclass;
100                 }
101
102                 public static Expression Create (Expression expr)
103                 {
104                         //
105                         // Avoid unwraping and wraping of same type
106                         //
107                         Wrap wrap = expr as Wrap;
108                         if (wrap != null)
109                                 return wrap.Child;
110
111                         return Create (expr, false);
112                 }
113
114                 public static Unwrap Create (Expression expr, bool useDefaultValue)
115                 {
116                         return new Unwrap (expr, useDefaultValue);
117                 }
118                 
119                 public override Expression CreateExpressionTree (ResolveContext ec)
120                 {
121                         return expr.CreateExpressionTree (ec);
122                 }
123
124                 protected override Expression DoResolve (ResolveContext ec)
125                 {
126                         return this;
127                 }
128
129                 public override Expression DoResolveLValue (ResolveContext ec, Expression right_side)
130                 {
131                         expr = expr.DoResolveLValue (ec, right_side);
132                         return this;
133                 }
134
135                 public override void Emit (EmitContext ec)
136                 {
137                         Store (ec);
138                         if (useDefaultValue)
139                                 Invocation.EmitCall (ec, this, NullableInfo.GetGetValueOrDefault (expr.Type), null, loc);
140                         else
141                                 Invocation.EmitCall (ec, this, NullableInfo.GetValue (expr.Type), null, loc);
142                 }
143
144                 public void EmitCheck (EmitContext ec)
145                 {
146                         Store (ec);
147                         Invocation.EmitCall (ec, this, NullableInfo.GetHasValue (expr.Type), null, loc);
148                 }
149
150                 public override bool Equals (object obj)
151                 {
152                         Unwrap uw = obj as Unwrap;
153                         return uw != null && expr.Equals (uw.expr);
154                 }
155
156                 public Expression Original {
157                         get {
158                                 return expr;
159                         }
160                 }
161                 
162                 public override int GetHashCode ()
163                 {
164                         return expr.GetHashCode ();
165                 }
166
167                 public override bool IsNull {
168                         get {
169                                 return expr.IsNull;
170                         }
171                 }
172
173                 void Store (EmitContext ec)
174                 {
175                         if (expr is VariableReference)
176                                 return;
177
178                         if (temp != null)
179                                 return;
180
181                         expr.Emit (ec);
182                         LocalVariable.Store (ec);
183                 }
184
185                 public void Load (EmitContext ec)
186                 {
187                         if (expr is VariableReference)
188                                 expr.Emit (ec);
189                         else
190                                 LocalVariable.Emit (ec);
191                 }
192
193                 public override System.Linq.Expressions.Expression MakeExpression (BuilderContext ctx)
194                 {
195                         return expr.MakeExpression (ctx);
196                 }
197
198                 public void AddressOf (EmitContext ec, AddressOp mode)
199                 {
200                         IMemoryLocation ml = expr as VariableReference;
201                         if (ml != null) 
202                                 ml.AddressOf (ec, mode);
203                         else
204                                 LocalVariable.AddressOf (ec, mode);
205                 }
206
207                 //
208                 // Keeps result of non-variable expression
209                 //
210                 LocalTemporary LocalVariable {
211                         get {
212                                 if (temp == null)
213                                         temp = new LocalTemporary (expr.Type);
214                                 return temp;
215                         }
216                 }
217
218                 public void Emit (EmitContext ec, bool leave_copy)
219                 {
220                         if (leave_copy)
221                                 Load (ec);
222
223                         Emit (ec);
224                 }
225
226                 public void EmitAssign (EmitContext ec, Expression source,
227                                         bool leave_copy, bool prepare_for_load)
228                 {
229                         InternalWrap wrap = new InternalWrap (source, expr.Type, loc);
230                         ((IAssignMethod) expr).EmitAssign (ec, wrap, leave_copy, false);
231                 }
232
233                 class InternalWrap : Expression
234                 {
235                         public Expression expr;
236
237                         public InternalWrap (Expression expr, TypeSpec type, Location loc)
238                         {
239                                 this.expr = expr;
240                                 this.loc = loc;
241                                 this.type = type;
242
243                                 eclass = ExprClass.Value;
244                         }
245
246                         public override Expression CreateExpressionTree (ResolveContext ec)
247                         {
248                                 throw new NotSupportedException ("ET");
249                         }
250
251                         protected override Expression DoResolve (ResolveContext ec)
252                         {
253                                 return this;
254                         }
255
256                         public override void Emit (EmitContext ec)
257                         {
258                                 expr.Emit (ec);
259                                 ec.Emit (OpCodes.Newobj, NullableInfo.GetConstructor (type));
260                         }
261                 }
262         }
263
264         public class Wrap : TypeCast
265         {
266                 private Wrap (Expression expr, TypeSpec type)
267                         : base (expr, type)
268                 {
269                         eclass = ExprClass.Value;
270                 }
271
272                 public override Expression CreateExpressionTree (ResolveContext ec)
273                 {
274                         TypeCast child_cast = child as TypeCast;
275                         if (child_cast != null) {
276                                 child.Type = type;
277                                 return child_cast.CreateExpressionTree (ec);
278                         }
279
280                         return base.CreateExpressionTree (ec);
281                 }
282
283                 public static Expression Create (Expression expr, TypeSpec type)
284                 {
285                         //
286                         // Avoid unwraping and wraping of the same type
287                         //
288                         Unwrap unwrap = expr as Unwrap;
289                         if (unwrap != null && expr.Type == NullableInfo.GetUnderlyingType (type))
290                                 return unwrap.Original;
291                 
292                         return new Wrap (expr, type);
293                 }
294                 
295                 public override void Emit (EmitContext ec)
296                 {
297                         child.Emit (ec);
298                         ec.Emit (OpCodes.Newobj, NullableInfo.GetConstructor (type));
299                 }
300         }
301
302         //
303         // Represents null literal lifted to nullable type
304         //
305         public class LiftedNull : NullConstant, IMemoryLocation
306         {
307                 private LiftedNull (TypeSpec nullable_type, Location loc)
308                         : base (nullable_type, loc)
309                 {
310                         eclass = ExprClass.Value;
311                 }
312
313                 public static Constant Create (TypeSpec nullable, Location loc)
314                 {
315                         return new LiftedNull (nullable, loc);
316                 }
317
318                 public static Expression CreateFromExpression (ResolveContext ec, Expression e)
319                 {
320                         ec.Report.Warning (458, 2, e.Location, "The result of the expression is always `null' of type `{0}'",
321                                 TypeManager.CSharpName (e.Type));
322
323                         return ReducedExpression.Create (Create (e.Type, e.Location), e);
324                 }
325
326                 public override void Emit (EmitContext ec)
327                 {
328                         // TODO: generate less temporary variables
329                         LocalTemporary value_target = new LocalTemporary (type);
330
331                         value_target.AddressOf (ec, AddressOp.Store);
332                         ec.Emit (OpCodes.Initobj, type);
333                         value_target.Emit (ec);
334                 }
335
336                 public void AddressOf (EmitContext ec, AddressOp Mode)
337                 {
338                         LocalTemporary value_target = new LocalTemporary (type);
339                                 
340                         value_target.AddressOf (ec, AddressOp.Store);
341                         ec.Emit (OpCodes.Initobj, type);
342                         ((IMemoryLocation) value_target).AddressOf (ec, Mode);
343                 }
344         }
345
346         //
347         // Generic lifting expression, supports all S/S? -> T/T? cases
348         //
349         public class Lifted : Expression, IMemoryLocation
350         {
351                 Expression expr, null_value;
352                 Unwrap unwrap;
353
354                 public Lifted (Expression expr, Unwrap unwrap, TypeSpec type)
355                 {
356                         this.expr = expr;
357                         this.unwrap = unwrap;
358                         this.loc = expr.Location;
359                         this.type = type;
360                 }
361
362                 public Lifted (Expression expr, Expression unwrap, TypeSpec type)
363                         : this (expr, unwrap as Unwrap, type)
364                 {
365                 }
366                 
367                 public override Expression CreateExpressionTree (ResolveContext ec)
368                 {
369                         return expr.CreateExpressionTree (ec);
370                 }                       
371
372                 protected override Expression DoResolve (ResolveContext ec)
373                 {
374                         //
375                         // It's null when lifting non-nullable type
376                         //
377                         if (unwrap == null) {
378                                 // S -> T? is wrap only
379                                 if (TypeManager.IsNullableType (type))
380                                         return Wrap.Create (expr, type);
381
382                                 // S -> T can be simplified
383                                 return expr;
384                         }
385
386                         // Wrap target for T?
387                         if (TypeManager.IsNullableType (type)) {
388                                 expr = Wrap.Create (expr, type);
389                                 if (expr == null)
390                                         return null;
391
392                                 null_value = LiftedNull.Create (type, loc);
393                         } else if (TypeManager.IsValueType (type)) {
394                                 null_value = LiftedNull.Create (type, loc);
395                         } else {
396                                 null_value = new NullConstant (type, loc);
397                         }
398
399                         eclass = ExprClass.Value;
400                         return this;
401                 }
402
403                 public override void Emit (EmitContext ec)
404                 {
405                         Label is_null_label = ec.DefineLabel ();
406                         Label end_label = ec.DefineLabel ();
407
408                         unwrap.EmitCheck (ec);
409                         ec.Emit (OpCodes.Brfalse, is_null_label);
410
411                         expr.Emit (ec);
412
413                         ec.Emit (OpCodes.Br, end_label);
414                         ec.MarkLabel (is_null_label);
415
416                         null_value.Emit (ec);
417                         ec.MarkLabel (end_label);
418                 }
419
420                 public void AddressOf (EmitContext ec, AddressOp mode)
421                 {
422                         unwrap.AddressOf (ec, mode);
423                 }
424         }
425
426         public class LiftedUnaryOperator : Unary, IMemoryLocation
427         {
428                 Unwrap unwrap;
429                 Expression user_operator;
430
431                 public LiftedUnaryOperator (Unary.Operator op, Expression expr, Location loc)
432                         : base (op, expr, loc)
433                 {
434                 }
435
436                 public void AddressOf (EmitContext ec, AddressOp mode)
437                 {
438                         unwrap.AddressOf (ec, mode);
439                 }
440
441                 public override Expression CreateExpressionTree (ResolveContext ec)
442                 {
443                         if (user_operator != null)
444                                 return user_operator.CreateExpressionTree (ec);
445
446                         if (Oper == Operator.UnaryPlus)
447                                 return Expr.CreateExpressionTree (ec);
448
449                         return base.CreateExpressionTree (ec);
450                 }
451
452                 protected override Expression DoResolve (ResolveContext ec)
453                 {
454                         unwrap = Unwrap.Create (Expr, false);
455                         if (unwrap == null)
456                                 return null;
457
458                         Expression res = base.ResolveOperator (ec, unwrap);
459                         if (res != this) {
460                                 if (user_operator == null)
461                                         return res;
462                         } else {
463                                 res = Expr = LiftExpression (ec, Expr);
464                         }
465
466                         if (res == null)
467                                 return null;
468
469                         eclass = ExprClass.Value;
470                         type = res.Type;
471                         return this;
472                 }
473
474                 public override void Emit (EmitContext ec)
475                 {
476                         Label is_null_label = ec.DefineLabel ();
477                         Label end_label = ec.DefineLabel ();
478
479                         unwrap.EmitCheck (ec);
480                         ec.Emit (OpCodes.Brfalse, is_null_label);
481
482                         if (user_operator != null) {
483                                 user_operator.Emit (ec);
484                         } else {
485                                 EmitOperator (ec, NullableInfo.GetUnderlyingType (type));
486                         }
487
488                         ec.Emit (OpCodes.Newobj, NullableInfo.GetConstructor (type));
489                         ec.Emit (OpCodes.Br_S, end_label);
490
491                         ec.MarkLabel (is_null_label);
492                         LiftedNull.Create (type, loc).Emit (ec);
493
494                         ec.MarkLabel (end_label);
495                 }
496
497                 Expression LiftExpression (ResolveContext ec, Expression expr)
498                 {
499                         TypeExpr lifted_type = new NullableType (expr.Type, expr.Location);
500                         lifted_type = lifted_type.ResolveAsTypeTerminal (ec, false);
501                         if (lifted_type == null)
502                                 return null;
503
504                         expr.Type = lifted_type.Type;
505                         return expr;
506                 }
507
508                 protected override Expression ResolveEnumOperator (ResolveContext ec, Expression expr)
509                 {
510                         expr = base.ResolveEnumOperator (ec, expr);
511                         if (expr == null)
512                                 return null;
513
514                         Expr = LiftExpression (ec, Expr);
515                         return LiftExpression (ec, expr);
516                 }
517
518                 protected override Expression ResolveUserOperator (ResolveContext ec, Expression expr)
519                 {
520                         expr = base.ResolveUserOperator (ec, expr);
521                         if (expr == null)
522                                 return null;
523
524                         //
525                         // When a user operator is of non-nullable type
526                         //
527                         if (Expr is Unwrap) {
528                                 user_operator = LiftExpression (ec, expr);
529                                 return user_operator;
530                         }
531
532                         return expr;
533                 }
534         }
535
536         public class LiftedBinaryOperator : Binary
537         {
538                 Unwrap left_unwrap, right_unwrap;
539                 bool left_null_lifted, right_null_lifted;
540                 Expression left_orig, right_orig;
541                 Expression user_operator;
542                 MethodSpec wrap_ctor;
543
544                 public LiftedBinaryOperator (Binary.Operator op, Expression left, Expression right, Location loc)
545                         : base (op, left, right, loc)
546                 {
547                 }
548
549                 public override Expression CreateExpressionTree (ResolveContext ec)
550                 {
551                         if (user_operator != null)
552                                 return user_operator.CreateExpressionTree (ec);
553
554                         return base.CreateExpressionTree (ec);
555                 }
556
557                 //
558                 // CSC 2 has this behavior, it allows structs to be compared
559                 // with the null literal *outside* of a generics context and
560                 // inlines that as true or false.
561                 //
562                 Expression CreateNullConstant (ResolveContext ec, Expression expr)
563                 {
564                         // FIXME: Handle side effect constants
565                         Constant c = new BoolConstant (Oper == Operator.Inequality, loc).Resolve (ec);
566
567                         if ((Oper & Operator.EqualityMask) != 0) {
568                                 ec.Report.Warning (472, 2, loc, "The result of comparing value type `{0}' with null is `{1}'",
569                                         TypeManager.CSharpName (expr.Type), c.AsString ());
570                         } else {
571                                 ec.Report.Warning (464, 2, loc, "The result of comparing type `{0}' with null is always `{1}'",
572                                         TypeManager.CSharpName (expr.Type), c.AsString ());
573                         }
574
575                         return ReducedExpression.Create (c, this);
576                 }
577
578                 protected override Expression DoResolve (ResolveContext ec)
579                 {
580                         if ((Oper & Operator.LogicalMask) != 0) {
581                                 Error_OperatorCannotBeApplied (ec, left, right);
582                                 return null;
583                         }
584
585                         bool use_default_call = (Oper & (Operator.BitwiseMask | Operator.EqualityMask)) != 0;
586                         left_orig = left;
587                         if (TypeManager.IsNullableType (left.Type)) {
588                                 left = left_unwrap = Unwrap.Create (left, use_default_call);
589                                 if (left == null)
590                                         return null;
591                         }
592
593                         right_orig = right;
594                         if (TypeManager.IsNullableType (right.Type)) {
595                                 right = right_unwrap = Unwrap.Create (right, use_default_call);
596                                 if (right == null)
597                                         return null;
598                         }
599
600                         //
601                         // Some details are in 6.4.2, 7.2.7
602                         // Arguments can be lifted for equal operators when the return type is bool and both
603                         // arguments are of same type
604                         //      
605                         if (left_orig.IsNull) {
606                                 left = right;
607                                 left_null_lifted = true;
608                                 type = TypeManager.bool_type;
609                         }
610
611                         if (right_orig.IsNull) {
612                                 right = left;
613                                 right_null_lifted = true;
614                                 type = TypeManager.bool_type;
615                         }
616
617                         eclass = ExprClass.Value;
618                         return DoResolveCore (ec, left_orig, right_orig);
619                 }
620
621                 void EmitBitwiseBoolean (EmitContext ec)
622                 {
623                         Label load_left = ec.DefineLabel ();
624                         Label load_right = ec.DefineLabel ();
625                         Label end_label = ec.DefineLabel ();
626
627                         left_unwrap.Emit (ec);
628                         ec.Emit (OpCodes.Brtrue_S, load_right);
629
630                         right_unwrap.Emit (ec);
631                         ec.Emit (OpCodes.Brtrue_S, load_left);
632
633                         left_unwrap.EmitCheck (ec);
634                         ec.Emit (OpCodes.Brfalse_S, load_right);
635
636                         // load left
637                         ec.MarkLabel (load_left);
638
639                         if (Oper == Operator.BitwiseAnd) {
640                                 left_unwrap.Load (ec);
641                         } else {
642                                 right_unwrap.Load (ec);
643                                 right_unwrap = left_unwrap;
644                         }
645                         ec.Emit (OpCodes.Br_S, end_label);
646
647                         // load right
648                         ec.MarkLabel (load_right);
649                         right_unwrap.Load (ec);
650
651                         ec.MarkLabel (end_label);
652                 }
653
654                 //
655                 // Emits optimized equality or inequality operator when possible
656                 //
657                 void EmitEquality (EmitContext ec)
658                 {
659                         //
660                         // Either left or right is null
661                         //
662                         if (left_unwrap != null && (right_null_lifted || right.IsNull)) {
663                                 left_unwrap.EmitCheck (ec);
664                                 if (Oper == Binary.Operator.Equality) {
665                                         ec.Emit (OpCodes.Ldc_I4_0);
666                                         ec.Emit (OpCodes.Ceq);
667                                 }
668                                 return;
669                         }
670
671                         if (right_unwrap != null && (left_null_lifted || left.IsNull)) {
672                                 right_unwrap.EmitCheck (ec);
673                                 if (Oper == Binary.Operator.Equality) {
674                                         ec.Emit (OpCodes.Ldc_I4_0);
675                                         ec.Emit (OpCodes.Ceq);
676                                 }
677                                 return;
678                         }
679
680                         Label dissimilar_label = ec.DefineLabel ();
681                         Label end_label = ec.DefineLabel ();
682
683                         if (user_operator != null) {
684                                 user_operator.Emit (ec);
685                                 ec.Emit (Oper == Operator.Equality ? OpCodes.Brfalse_S : OpCodes.Brtrue_S, dissimilar_label);
686                         } else {
687                                 left.Emit (ec);
688                                 right.Emit (ec);
689
690                                 ec.Emit (OpCodes.Bne_Un_S, dissimilar_label);
691                         }
692
693                         if (left_unwrap != null)
694                                 left_unwrap.EmitCheck (ec);
695
696                         if (right_unwrap != null)
697                                 right_unwrap.EmitCheck (ec);
698
699                         if (left_unwrap != null && right_unwrap != null) {
700                                 if (Oper == Operator.Inequality)
701                                         ec.Emit (OpCodes.Xor);
702                                 else
703                                         ec.Emit (OpCodes.Ceq);
704                         } else {
705                                 if (Oper == Operator.Inequality) {
706                                         ec.Emit (OpCodes.Ldc_I4_0);
707                                         ec.Emit (OpCodes.Ceq);
708                                 }
709                         }
710
711                         ec.Emit (OpCodes.Br_S, end_label);
712
713                         ec.MarkLabel (dissimilar_label);
714                         if (Oper == Operator.Inequality)
715                                 ec.Emit (OpCodes.Ldc_I4_1);
716                         else
717                                 ec.Emit (OpCodes.Ldc_I4_0);
718
719                         ec.MarkLabel (end_label);
720                 }
721                 
722                 public override void EmitBranchable (EmitContext ec, Label target, bool onTrue)
723                 {
724                         Emit (ec);
725                         ec.Emit (onTrue ? OpCodes.Brtrue : OpCodes.Brfalse, target);
726                 }                       
727
728                 public override void Emit (EmitContext ec)
729                 {
730                         //
731                         // Optimize same expression operation
732                         //
733                         if (right_unwrap != null && right.Equals (left))
734                                 right_unwrap = left_unwrap;
735
736                         if (user_operator == null && IsBitwiseBoolean) {
737                                 EmitBitwiseBoolean (ec);
738                                 return;
739                         }
740
741                         if ((Oper & Operator.EqualityMask) != 0) {
742                                 EmitEquality (ec);
743                                 return;
744                         }
745
746                         Label is_null_label = ec.DefineLabel ();
747                         Label end_label = ec.DefineLabel ();
748
749                         if (left_unwrap != null) {
750                                 left_unwrap.EmitCheck (ec);
751                                 ec.Emit (OpCodes.Brfalse, is_null_label);
752                         }
753
754                         //
755                         // Don't emit HasValue check when left and right expressions are same
756                         //
757                         if (right_unwrap != null && !left.Equals (right)) {
758                                 right_unwrap.EmitCheck (ec);
759                                 ec.Emit (OpCodes.Brfalse, is_null_label);
760                         }
761
762                         EmitOperator (ec, left.Type);
763
764                         if (wrap_ctor != null)
765                                 ec.Emit (OpCodes.Newobj, wrap_ctor);
766
767                         ec.Emit (OpCodes.Br_S, end_label);
768                         ec.MarkLabel (is_null_label);
769
770                         if ((Oper & Operator.ComparisonMask) != 0) {
771                                 ec.Emit (OpCodes.Ldc_I4_0);
772                         } else {
773                                 LiftedNull.Create (type, loc).Emit (ec);
774                         }
775
776                         ec.MarkLabel (end_label);
777                 }
778
779                 protected override void EmitOperator (EmitContext ec, TypeSpec l)
780                 {
781                         if (user_operator != null) {
782                                 user_operator.Emit (ec);
783                                 return;
784                         }
785
786                         if (TypeManager.IsNullableType (l))
787                                 l = TypeManager.GetTypeArguments (l) [0];
788
789                         base.EmitOperator (ec, l);
790                 }
791
792                 bool IsBitwiseBoolean {
793                         get {
794                                 return (Oper & Operator.BitwiseMask) != 0 && left_unwrap != null && right_unwrap != null &&
795                                 left_unwrap.Type == TypeManager.bool_type && right_unwrap.Type == TypeManager.bool_type;
796                         }
797                 }
798
799                 Expression LiftResult (ResolveContext ec, Expression res_expr)
800                 {
801                         TypeExpr lifted_type;
802
803                         //
804                         // Avoid double conversion
805                         //
806                         if (left_unwrap == null || left_null_lifted || left_unwrap.Type != left.Type || (left_unwrap != null && right_null_lifted)) {
807                                 lifted_type = new NullableType (left.Type, loc);
808                                 lifted_type = lifted_type.ResolveAsTypeTerminal (ec, false);
809                                 if (lifted_type == null)
810                                         return null;
811
812                                 if (left is UserCast || left is TypeCast)
813                                         left.Type = lifted_type.Type;
814                                 else
815                                         left = EmptyCast.Create (left, lifted_type.Type);
816                         }
817
818                         if (left != right && (right_unwrap == null || right_null_lifted || right_unwrap.Type != right.Type || (right_unwrap != null && left_null_lifted))) {
819                                 lifted_type = new NullableType (right.Type, loc);
820                                 lifted_type = lifted_type.ResolveAsTypeTerminal (ec, false);
821                                 if (lifted_type == null)
822                                         return null;
823
824                                 if (right is UserCast || right is TypeCast)
825                                         right.Type = lifted_type.Type;
826                                 else
827                                         right = EmptyCast.Create (right, lifted_type.Type);
828                         }
829
830                         if ((Oper & Operator.ComparisonMask) == 0) {
831                                 lifted_type = new NullableType (res_expr.Type, loc);
832                                 lifted_type = lifted_type.ResolveAsTypeTerminal (ec, false);
833                                 if (lifted_type == null)
834                                         return null;
835
836                                 wrap_ctor = NullableInfo.GetConstructor (lifted_type.Type);
837                                 type = res_expr.Type = lifted_type.Type;
838                         }
839
840                         if (left_null_lifted) {
841                                 left = LiftedNull.Create (right.Type, left.Location);
842
843                                 if ((Oper & (Operator.ArithmeticMask | Operator.ShiftMask | Operator.BitwiseMask)) != 0)
844                                         return LiftedNull.CreateFromExpression (ec, res_expr);
845
846                                 //
847                                 // Value types and null comparison
848                                 //
849                                 if (right_unwrap == null || (Oper & Operator.RelationalMask) != 0)
850                                         return CreateNullConstant (ec, right_orig).Resolve (ec);
851                         }
852
853                         if (right_null_lifted) {
854                                 right = LiftedNull.Create (left.Type, right.Location);
855
856                                 if ((Oper & (Operator.ArithmeticMask | Operator.ShiftMask | Operator.BitwiseMask)) != 0)
857                                         return LiftedNull.CreateFromExpression (ec, res_expr);
858
859                                 //
860                                 // Value types and null comparison
861                                 //
862                                 if (left_unwrap == null || (Oper & Operator.RelationalMask) != 0)
863                                         return CreateNullConstant (ec, left_orig);
864                         }
865
866                         return res_expr;
867                 }
868
869                 protected override Expression ResolveOperatorPredefined (ResolveContext ec, Binary.PredefinedOperator [] operators, bool primitives_only, TypeSpec enum_type)
870                 {
871                         Expression e = base.ResolveOperatorPredefined (ec, operators, primitives_only, enum_type);
872
873                         if (e == this || enum_type != null)
874                                 return LiftResult (ec, e);
875
876                         //
877                         // 7.9.9 Equality operators and null
878                         //
879                         // The == and != operators permit one operand to be a value of a nullable type and
880                         // the other to be the null literal, even if no predefined or user-defined operator
881                         // (in unlifted or lifted form) exists for the operation.
882                         //
883                         if (e == null && (Oper & Operator.EqualityMask) != 0) {
884                                 if ((left_null_lifted && right_unwrap != null) || (right_null_lifted && left_unwrap != null))
885                                         return LiftResult (ec, this);
886                         }
887
888                         return e;
889                 }
890
891                 protected override Expression ResolveUserOperator (ResolveContext ec, TypeSpec l, TypeSpec r)
892                 {
893                         Expression expr = base.ResolveUserOperator (ec, l, r);
894                         if (expr == null)
895                                 return null;
896
897                         expr = LiftResult (ec, expr);
898                         if (expr is Constant)
899                                 return expr;
900
901                         type = expr.Type;
902                         user_operator = expr;
903                         return this;
904                 }
905         }
906
907         public class NullCoalescingOperator : Expression
908         {
909                 Expression left, right;
910                 Unwrap unwrap;
911
912                 public NullCoalescingOperator (Expression left, Expression right, Location loc)
913                 {
914                         this.left = left;
915                         this.right = right;
916                         this.loc = loc;
917                 }
918                 
919                 public override Expression CreateExpressionTree (ResolveContext ec)
920                 {
921                         if (left is NullLiteral)
922                                 ec.Report.Error (845, loc, "An expression tree cannot contain a coalescing operator with null left side");
923
924                         UserCast uc = left as UserCast;
925                         Expression conversion = null;
926                         if (uc != null) {
927                                 left = uc.Source;
928
929                                 Arguments c_args = new Arguments (2);
930                                 c_args.Add (new Argument (uc.CreateExpressionTree (ec)));
931                                 c_args.Add (new Argument (left.CreateExpressionTree (ec)));
932                                 conversion = CreateExpressionFactoryCall (ec, "Lambda", c_args);
933                         }
934
935                         Arguments args = new Arguments (3);
936                         args.Add (new Argument (left.CreateExpressionTree (ec)));
937                         args.Add (new Argument (right.CreateExpressionTree (ec)));
938                         if (conversion != null)
939                                 args.Add (new Argument (conversion));
940                         
941                         return CreateExpressionFactoryCall (ec, "Coalesce", args);
942                 }
943
944                 Expression ConvertExpression (ResolveContext ec)
945                 {
946                         // TODO: ImplicitConversionExists should take care of this
947                         if (left.eclass == ExprClass.MethodGroup)
948                                 return null;
949
950                         TypeSpec ltype = left.Type;
951
952                         //
953                         // If left is a nullable type and an implicit conversion exists from right to underlying type of left,
954                         // the result is underlying type of left
955                         //
956                         if (TypeManager.IsNullableType (ltype)) {
957                                 unwrap = Unwrap.Create (left, false);
958                                 if (unwrap == null)
959                                         return null;
960
961                                 if (Convert.ImplicitConversionExists (ec, right, unwrap.Type)) {
962                                         left = unwrap;
963                                         type = left.Type;
964                                         right = Convert.ImplicitConversion (ec, right, type, loc);
965                                         return this;
966                                 }
967                         } else if (TypeManager.IsReferenceType (ltype)) {
968                                 if (Convert.ImplicitConversionExists (ec, right, ltype)) {
969                                         //
970                                         // Reduce (constant ?? expr) to constant
971                                         //
972                                         Constant lc = left as Constant;
973                                         if (lc != null && !lc.IsDefaultValue)
974                                                 return new SideEffectConstant (lc, right, loc).Resolve (ec);
975
976                                         //
977                                         // Reduce (left ?? null) to left OR (null-constant ?? right) to right
978                                         //
979                                         if (right.IsNull || lc != null)
980                                                 return ReducedExpression.Create (lc != null ? right : left, this);
981
982                                         right = Convert.ImplicitConversion (ec, right, ltype, loc);
983                                         type = left.Type;
984                                         return this;
985                                 }
986                         } else {
987                                 return null;
988                         }
989
990                         TypeSpec rtype = right.Type;
991                         if (!Convert.ImplicitConversionExists (ec, unwrap != null ? unwrap : left, rtype) || right.eclass == ExprClass.MethodGroup)
992                                 return null;
993
994                         //
995                         // Reduce (null ?? right) to right
996                         //
997                         if (left.IsNull)
998                                 return ReducedExpression.Create (right, this);
999
1000                         left = Convert.ImplicitConversion (ec, unwrap != null ? unwrap : left, rtype, loc);
1001                         type = rtype;
1002                         return this;
1003                 }
1004
1005                 protected override Expression DoResolve (ResolveContext ec)
1006                 {
1007                         left = left.Resolve (ec);
1008                         right = right.Resolve (ec);
1009
1010                         if (left == null || right == null)
1011                                 return null;
1012
1013                         eclass = ExprClass.Value;
1014
1015                         Expression e = ConvertExpression (ec);
1016                         if (e == null) {
1017                                 Binary.Error_OperatorCannotBeApplied (ec, left, right, "??", loc);
1018                                 return null;
1019                         }
1020
1021                         return e;
1022                 }
1023
1024                 public override void Emit (EmitContext ec)
1025                 {
1026                         Label end_label = ec.DefineLabel ();
1027
1028                         if (unwrap != null) {
1029                                 Label is_null_label = ec.DefineLabel ();
1030
1031                                 unwrap.EmitCheck (ec);
1032                                 ec.Emit (OpCodes.Brfalse, is_null_label);
1033
1034                                 left.Emit (ec);
1035                                 ec.Emit (OpCodes.Br, end_label);
1036
1037                                 ec.MarkLabel (is_null_label);
1038                                 right.Emit (ec);
1039
1040                                 ec.MarkLabel (end_label);
1041                                 return;
1042                         }
1043
1044                         left.Emit (ec);
1045                         ec.Emit (OpCodes.Dup);
1046
1047                         // Only to make verifier happy
1048                         if (left.Type.IsGenericParameter)
1049                                 ec.Emit (OpCodes.Box, left.Type);
1050
1051                         ec.Emit (OpCodes.Brtrue, end_label);
1052
1053                         ec.Emit (OpCodes.Pop);
1054                         right.Emit (ec);
1055
1056                         ec.MarkLabel (end_label);
1057                 }
1058
1059                 protected override void CloneTo (CloneContext clonectx, Expression t)
1060                 {
1061                         NullCoalescingOperator target = (NullCoalescingOperator) t;
1062
1063                         target.left = left.Clone (clonectx);
1064                         target.right = right.Clone (clonectx);
1065                 }
1066         }
1067
1068         public class LiftedUnaryMutator : ExpressionStatement
1069         {
1070                 public readonly UnaryMutator.Mode Mode;
1071                 Expression expr;
1072                 UnaryMutator underlying;
1073                 Unwrap unwrap;
1074
1075                 public LiftedUnaryMutator (UnaryMutator.Mode mode, Expression expr, Location loc)
1076                 {
1077                         this.expr = expr;
1078                         this.Mode = mode;
1079                         this.loc = loc;
1080                 }
1081
1082                 public override Expression CreateExpressionTree (ResolveContext ec)
1083                 {
1084                         return new SimpleAssign (this, this).CreateExpressionTree (ec);
1085                 }
1086
1087                 protected override Expression DoResolve (ResolveContext ec)
1088                 {
1089                         expr = expr.Resolve (ec);
1090                         if (expr == null)
1091                                 return null;
1092
1093                         unwrap = Unwrap.Create (expr, false);
1094                         if (unwrap == null)
1095                                 return null;
1096
1097                         underlying = (UnaryMutator) new UnaryMutator (Mode, unwrap, loc).Resolve (ec);
1098                         if (underlying == null)
1099                                 return null;
1100
1101
1102                         eclass = ExprClass.Value;
1103                         type = expr.Type;
1104                         return this;
1105                 }
1106
1107                 void DoEmit (EmitContext ec, bool is_expr)
1108                 {
1109                         Label is_null_label = ec.DefineLabel ();
1110                         Label end_label = ec.DefineLabel ();
1111
1112                         unwrap.EmitCheck (ec);
1113                         ec.Emit (OpCodes.Brfalse, is_null_label);
1114
1115                         if (is_expr) {
1116                                 underlying.Emit (ec);
1117                                 ec.Emit (OpCodes.Br_S, end_label);
1118                         } else {
1119                                 underlying.EmitStatement (ec);
1120                         }
1121
1122                         ec.MarkLabel (is_null_label);
1123                         if (is_expr)
1124                                 LiftedNull.Create (type, loc).Emit (ec);
1125
1126                         ec.MarkLabel (end_label);
1127                 }
1128
1129                 public override void Emit (EmitContext ec)
1130                 {
1131                         DoEmit (ec, true);
1132                 }
1133
1134                 public override void EmitStatement (EmitContext ec)
1135                 {
1136                         DoEmit (ec, false);
1137                 }
1138         }
1139 }
1140