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