Merge pull request #2366 from xmcclure/scripts-babysitter
[mono.git] / mcs / mcs / expression.cs
1 //
2 // expression.cs: Expression representation for the IL tree.
3 //
4 // Author:
5 //   Miguel de Icaza (miguel@ximian.com)
6 //   Marek Safar (marek.safar@gmail.com)
7 //
8 // Copyright 2001, 2002, 2003 Ximian, Inc.
9 // Copyright 2003-2008 Novell, Inc.
10 // Copyright 2011 Xamarin Inc.
11 //
12
13 using System;
14 using System.Collections.Generic;
15 using System.Linq;
16 using SLE = System.Linq.Expressions;
17 using System.Text;
18
19 #if STATIC
20 using MetaType = IKVM.Reflection.Type;
21 using IKVM.Reflection;
22 using IKVM.Reflection.Emit;
23 #else
24 using MetaType = System.Type;
25 using System.Reflection;
26 using System.Reflection.Emit;
27 #endif
28
29 namespace Mono.CSharp
30 {
31         //
32         // This is an user operator expression, automatically created during
33         // resolve phase
34         //
35         public class UserOperatorCall : Expression {
36                 protected readonly Arguments arguments;
37                 protected readonly MethodSpec oper;
38                 readonly Func<ResolveContext, Expression, Expression> expr_tree;
39
40                 public UserOperatorCall (MethodSpec oper, Arguments args, Func<ResolveContext, Expression, Expression> expr_tree, Location loc)
41                 {
42                         this.oper = oper;
43                         this.arguments = args;
44                         this.expr_tree = expr_tree;
45
46                         type = oper.ReturnType;
47                         eclass = ExprClass.Value;
48                         this.loc = loc;
49                 }
50
51                 public override bool ContainsEmitWithAwait ()
52                 {
53                         return arguments.ContainsEmitWithAwait ();
54                 }
55
56                 public override Expression CreateExpressionTree (ResolveContext ec)
57                 {
58                         if (expr_tree != null)
59                                 return expr_tree (ec, new TypeOfMethod (oper, loc));
60
61                         Arguments args = Arguments.CreateForExpressionTree (ec, arguments,
62                                 new NullLiteral (loc),
63                                 new TypeOfMethod (oper, loc));
64
65                         return CreateExpressionFactoryCall (ec, "Call", args);
66                 }
67
68                 protected override void CloneTo (CloneContext context, Expression target)
69                 {
70                         // Nothing to clone
71                 }
72                 
73                 protected override Expression DoResolve (ResolveContext ec)
74                 {
75                         //
76                         // We are born fully resolved
77                         //
78                         return this;
79                 }
80
81                 public override void Emit (EmitContext ec)
82                 {
83                         var call = new CallEmitter ();
84                         call.Emit (ec, oper, arguments, loc);
85                 }
86
87                 public override void FlowAnalysis (FlowAnalysisContext fc)
88                 {
89                         arguments.FlowAnalysis (fc);
90                 }
91
92                 public override SLE.Expression MakeExpression (BuilderContext ctx)
93                 {
94 #if STATIC
95                         return base.MakeExpression (ctx);
96 #else
97                         return SLE.Expression.Call ((MethodInfo) oper.GetMetaInfo (), Arguments.MakeExpression (arguments, ctx));
98 #endif
99                 }
100         }
101
102         public class ParenthesizedExpression : ShimExpression
103         {
104                 public ParenthesizedExpression (Expression expr, Location loc)
105                         : base (expr)
106                 {
107                         this.loc = loc;
108                 }
109
110                 protected override Expression DoResolve (ResolveContext rc)
111                 {
112                         Expression res = null;
113
114                         res = expr.Resolve (rc);
115
116                         var constant = res as Constant;
117                         if (constant != null && constant.IsLiteral) {
118                                 if (res is NullLiteral)
119                                         return res;
120                                 
121                                 return Constant.CreateConstantFromValue (res.Type, constant.GetValue (), expr.Location);
122                         }
123
124                         return res;
125                 }
126
127                 public override Expression DoResolveLValue (ResolveContext ec, Expression right_side)
128                 {
129                         return expr.DoResolveLValue (ec, right_side);
130                 }
131                 
132                 public override object Accept (StructuralVisitor visitor)
133                 {
134                         return visitor.Visit (this);
135                 }
136
137                 public override bool HasConditionalAccess ()
138                 {
139                         return false;
140                 }
141         }
142         
143         //
144         //   Unary implements unary expressions.
145         //
146         public class Unary : Expression
147         {
148                 public enum Operator : byte {
149                         UnaryPlus, UnaryNegation, LogicalNot, OnesComplement,
150                         AddressOf,  TOP
151                 }
152
153                 public readonly Operator Oper;
154                 public Expression Expr;
155                 ConvCast.Mode enum_conversion;
156
157                 public Unary (Operator op, Expression expr, Location loc)
158                 {
159                         Oper = op;
160                         Expr = expr;
161                         this.loc = loc;
162                 }
163
164                 // <summary>
165                 //   This routine will attempt to simplify the unary expression when the
166                 //   argument is a constant.
167                 // </summary>
168                 Constant TryReduceConstant (ResolveContext ec, Constant constant)
169                 {
170                         var e = constant;
171
172                         while (e is EmptyConstantCast)
173                                 e = ((EmptyConstantCast) e).child;
174                         
175                         if (e is SideEffectConstant) {
176                                 Constant r = TryReduceConstant (ec, ((SideEffectConstant) e).value);
177                                 return r == null ? null : new SideEffectConstant (r, e, r.Location);
178                         }
179
180                         TypeSpec expr_type = e.Type;
181                         
182                         switch (Oper){
183                         case Operator.UnaryPlus:
184                                 // Unary numeric promotions
185                                 switch (expr_type.BuiltinType) {
186                                 case BuiltinTypeSpec.Type.Byte:
187                                         return new IntConstant (ec.BuiltinTypes, ((ByteConstant) e).Value, e.Location);
188                                 case BuiltinTypeSpec.Type.SByte:
189                                         return new IntConstant (ec.BuiltinTypes, ((SByteConstant) e).Value, e.Location);
190                                 case BuiltinTypeSpec.Type.Short:
191                                         return new IntConstant (ec.BuiltinTypes, ((ShortConstant) e).Value, e.Location);
192                                 case BuiltinTypeSpec.Type.UShort:
193                                         return new IntConstant (ec.BuiltinTypes, ((UShortConstant) e).Value, e.Location);
194                                 case BuiltinTypeSpec.Type.Char:
195                                         return new IntConstant (ec.BuiltinTypes, ((CharConstant) e).Value, e.Location);
196                                 
197                                 // Predefined operators
198                                 case BuiltinTypeSpec.Type.Int:
199                                 case BuiltinTypeSpec.Type.UInt:
200                                 case BuiltinTypeSpec.Type.Long:
201                                 case BuiltinTypeSpec.Type.ULong:
202                                 case BuiltinTypeSpec.Type.Float:
203                                 case BuiltinTypeSpec.Type.Double:
204                                 case BuiltinTypeSpec.Type.Decimal:
205                                         return e;
206                                 }
207                                 
208                                 return null;
209                                 
210                         case Operator.UnaryNegation:
211                                 // Unary numeric promotions
212                                 switch (expr_type.BuiltinType) {
213                                 case BuiltinTypeSpec.Type.Byte:
214                                         return new IntConstant (ec.BuiltinTypes, -((ByteConstant) e).Value, e.Location);
215                                 case BuiltinTypeSpec.Type.SByte:
216                                         return new IntConstant (ec.BuiltinTypes, -((SByteConstant) e).Value, e.Location);
217                                 case BuiltinTypeSpec.Type.Short:
218                                         return new IntConstant (ec.BuiltinTypes, -((ShortConstant) e).Value, e.Location);
219                                 case BuiltinTypeSpec.Type.UShort:
220                                         return new IntConstant (ec.BuiltinTypes, -((UShortConstant) e).Value, e.Location);
221                                 case BuiltinTypeSpec.Type.Char:
222                                         return new IntConstant (ec.BuiltinTypes, -((CharConstant) e).Value, e.Location);
223
224                                 // Predefined operators
225                                 case BuiltinTypeSpec.Type.Int:
226                                         int ivalue = ((IntConstant) e).Value;
227                                         if (ivalue == int.MinValue) {
228                                                 if (ec.ConstantCheckState) {
229                                                         ConstantFold.Error_CompileTimeOverflow (ec, loc);
230                                                         return null;
231                                                 }
232                                                 return e;
233                                         }
234                                         return new IntConstant (ec.BuiltinTypes, -ivalue, e.Location);
235
236                                 case BuiltinTypeSpec.Type.Long:
237                                         long lvalue = ((LongConstant) e).Value;
238                                         if (lvalue == long.MinValue) {
239                                                 if (ec.ConstantCheckState) {
240                                                         ConstantFold.Error_CompileTimeOverflow (ec, loc);
241                                                         return null;
242                                                 }
243                                                 return e;
244                                         }
245                                         return new LongConstant (ec.BuiltinTypes, -lvalue, e.Location);
246
247                                 case BuiltinTypeSpec.Type.UInt:
248                                         UIntLiteral uil = constant as UIntLiteral;
249                                         if (uil != null) {
250                                                 if (uil.Value == int.MaxValue + (uint) 1)
251                                                         return new IntLiteral (ec.BuiltinTypes, int.MinValue, e.Location);
252                                                 return new LongLiteral (ec.BuiltinTypes, -uil.Value, e.Location);
253                                         }
254                                         return new LongConstant (ec.BuiltinTypes, -((UIntConstant) e).Value, e.Location);
255
256
257                                 case BuiltinTypeSpec.Type.ULong:
258                                         ULongLiteral ull = constant as ULongLiteral;
259                                         if (ull != null && ull.Value == 9223372036854775808)
260                                                 return new LongLiteral (ec.BuiltinTypes, long.MinValue, e.Location);
261                                         return null;
262
263                                 case BuiltinTypeSpec.Type.Float:
264                                         FloatLiteral fl = constant as FloatLiteral;
265                                         // For better error reporting
266                                         if (fl != null)
267                                                 return new FloatLiteral (ec.BuiltinTypes, -fl.Value, e.Location);
268
269                                         return new FloatConstant (ec.BuiltinTypes, -((FloatConstant) e).Value, e.Location);
270
271                                 case BuiltinTypeSpec.Type.Double:
272                                         DoubleLiteral dl = constant as DoubleLiteral;
273                                         // For better error reporting
274                                         if (dl != null)
275                                                 return new DoubleLiteral (ec.BuiltinTypes, -dl.Value, e.Location);
276
277                                         return new DoubleConstant (ec.BuiltinTypes, -((DoubleConstant) e).Value, e.Location);
278
279                                 case BuiltinTypeSpec.Type.Decimal:
280                                         return new DecimalConstant (ec.BuiltinTypes, -((DecimalConstant) e).Value, e.Location);
281                                 }
282
283                                 return null;
284                                 
285                         case Operator.LogicalNot:
286                                 if (expr_type.BuiltinType != BuiltinTypeSpec.Type.Bool)
287                                         return null;
288                                 
289                                 bool b = (bool)e.GetValue ();
290                                 return new BoolConstant (ec.BuiltinTypes, !b, e.Location);
291                                 
292                         case Operator.OnesComplement:
293                                 // Unary numeric promotions
294                                 switch (expr_type.BuiltinType) {
295                                 case BuiltinTypeSpec.Type.Byte:
296                                         return new IntConstant (ec.BuiltinTypes, ~((ByteConstant) e).Value, e.Location);
297                                 case BuiltinTypeSpec.Type.SByte:
298                                         return new IntConstant (ec.BuiltinTypes, ~((SByteConstant) e).Value, e.Location);
299                                 case BuiltinTypeSpec.Type.Short:
300                                         return new IntConstant (ec.BuiltinTypes, ~((ShortConstant) e).Value, e.Location);
301                                 case BuiltinTypeSpec.Type.UShort:
302                                         return new IntConstant (ec.BuiltinTypes, ~((UShortConstant) e).Value, e.Location);
303                                 case BuiltinTypeSpec.Type.Char:
304                                         return new IntConstant (ec.BuiltinTypes, ~((CharConstant) e).Value, e.Location);
305                                 
306                                 // Predefined operators
307                                 case BuiltinTypeSpec.Type.Int:
308                                         return new IntConstant (ec.BuiltinTypes, ~((IntConstant)e).Value, e.Location);
309                                 case BuiltinTypeSpec.Type.UInt:
310                                         return new UIntConstant (ec.BuiltinTypes, ~((UIntConstant) e).Value, e.Location);
311                                 case BuiltinTypeSpec.Type.Long:
312                                         return new LongConstant (ec.BuiltinTypes, ~((LongConstant) e).Value, e.Location);
313                                 case BuiltinTypeSpec.Type.ULong:
314                                         return new ULongConstant (ec.BuiltinTypes, ~((ULongConstant) e).Value, e.Location);
315                                 }
316                                 if (e is EnumConstant) {
317                                         var res = TryReduceConstant (ec, ((EnumConstant)e).Child);
318                                         if (res != null) {
319                                                 //
320                                                 // Numeric promotion upgraded types to int but for enum constant
321                                                 // original underlying constant type is needed
322                                                 //
323                                                 if (res.Type.BuiltinType == BuiltinTypeSpec.Type.Int) {
324                                                         int v = ((IntConstant) res).Value;
325                                                         switch (((EnumConstant) e).Child.Type.BuiltinType) {
326                                                                 case BuiltinTypeSpec.Type.UShort:
327                                                                 res = new UShortConstant (ec.BuiltinTypes, (ushort) v, e.Location);
328                                                                 break;
329                                                                 case BuiltinTypeSpec.Type.Short:
330                                                                 res = new ShortConstant (ec.BuiltinTypes, (short) v, e.Location);
331                                                                 break;
332                                                                 case BuiltinTypeSpec.Type.Byte:
333                                                                 res = new ByteConstant (ec.BuiltinTypes, (byte) v, e.Location);
334                                                                 break;
335                                                                 case BuiltinTypeSpec.Type.SByte:
336                                                                 res = new SByteConstant (ec.BuiltinTypes, (sbyte) v, e.Location);
337                                                                 break;
338                                                         }
339                                                 }
340
341                                                 res = new EnumConstant (res, expr_type);
342                                         }
343                                         return res;
344                                 }
345                                 return null;
346                         }
347                         throw new Exception ("Can not constant fold: " + Oper.ToString());
348                 }
349                 
350                 protected virtual Expression ResolveOperator (ResolveContext ec, Expression expr)
351                 {
352                         eclass = ExprClass.Value;
353
354                         TypeSpec expr_type = expr.Type;
355                         Expression best_expr;
356
357                         TypeSpec[] predefined = ec.BuiltinTypes.OperatorsUnary [(int) Oper];
358
359                         //
360                         // Primitive types first
361                         //
362                         if (BuiltinTypeSpec.IsPrimitiveType (expr_type)) {
363                                 best_expr = ResolvePrimitivePredefinedType (ec, expr, predefined);
364                                 if (best_expr == null)
365                                         return null;
366
367                                 type = best_expr.Type;
368                                 Expr = best_expr;
369                                 return this;
370                         }
371
372                         //
373                         // E operator ~(E x);
374                         //
375                         if (Oper == Operator.OnesComplement && expr_type.IsEnum)
376                                 return ResolveEnumOperator (ec, expr, predefined);
377
378                         return ResolveUserType (ec, expr, predefined);
379                 }
380
381                 protected virtual Expression ResolveEnumOperator (ResolveContext ec, Expression expr, TypeSpec[] predefined)
382                 {
383                         TypeSpec underlying_type = EnumSpec.GetUnderlyingType (expr.Type);
384                         Expression best_expr = ResolvePrimitivePredefinedType (ec, EmptyCast.Create (expr, underlying_type), predefined);
385                         if (best_expr == null)
386                                 return null;
387
388                         Expr = best_expr;
389                         enum_conversion = Binary.GetEnumResultCast (underlying_type);
390                         type = expr.Type;
391                         return EmptyCast.Create (this, type);
392                 }
393
394                 public override bool ContainsEmitWithAwait ()
395                 {
396                         return Expr.ContainsEmitWithAwait ();
397                 }
398
399                 public override Expression CreateExpressionTree (ResolveContext ec)
400                 {
401                         return CreateExpressionTree (ec, null);
402                 }
403
404                 Expression CreateExpressionTree (ResolveContext ec, Expression user_op)
405                 {
406                         string method_name;
407                         switch (Oper) {
408                         case Operator.AddressOf:
409                                 Error_PointerInsideExpressionTree (ec);
410                                 return null;
411                         case Operator.UnaryNegation:
412                                 if (ec.HasSet (ResolveContext.Options.CheckedScope) && user_op == null && !IsFloat (type))
413                                         method_name = "NegateChecked";
414                                 else
415                                         method_name = "Negate";
416                                 break;
417                         case Operator.OnesComplement:
418                         case Operator.LogicalNot:
419                                 method_name = "Not";
420                                 break;
421                         case Operator.UnaryPlus:
422                                 method_name = "UnaryPlus";
423                                 break;
424                         default:
425                                 throw new InternalErrorException ("Unknown unary operator " + Oper.ToString ());
426                         }
427
428                         Arguments args = new Arguments (2);
429                         args.Add (new Argument (Expr.CreateExpressionTree (ec)));
430                         if (user_op != null)
431                                 args.Add (new Argument (user_op));
432
433                         return CreateExpressionFactoryCall (ec, method_name, args);
434                 }
435
436                 public static TypeSpec[][] CreatePredefinedOperatorsTable (BuiltinTypes types)
437                 {
438                         var predefined_operators = new TypeSpec[(int) Operator.TOP][];
439
440                         //
441                         // 7.6.1 Unary plus operator
442                         //
443                         predefined_operators [(int) Operator.UnaryPlus] = new TypeSpec [] {
444                                 types.Int, types.UInt,
445                                 types.Long, types.ULong,
446                                 types.Float, types.Double,
447                                 types.Decimal
448                         };
449
450                         //
451                         // 7.6.2 Unary minus operator
452                         //
453                         predefined_operators [(int) Operator.UnaryNegation] = new TypeSpec [] {
454                                 types.Int,  types.Long,
455                                 types.Float, types.Double,
456                                 types.Decimal
457                         };
458
459                         //
460                         // 7.6.3 Logical negation operator
461                         //
462                         predefined_operators [(int) Operator.LogicalNot] = new TypeSpec [] {
463                                 types.Bool
464                         };
465
466                         //
467                         // 7.6.4 Bitwise complement operator
468                         //
469                         predefined_operators [(int) Operator.OnesComplement] = new TypeSpec [] {
470                                 types.Int, types.UInt,
471                                 types.Long, types.ULong
472                         };
473
474                         return predefined_operators;
475                 }
476
477                 //
478                 // Unary numeric promotions
479                 //
480                 static Expression DoNumericPromotion (ResolveContext rc, Operator op, Expression expr)
481                 {
482                         TypeSpec expr_type = expr.Type;
483                         if (op == Operator.UnaryPlus || op == Operator.UnaryNegation || op == Operator.OnesComplement) {
484                                 switch (expr_type.BuiltinType) {
485                                 case BuiltinTypeSpec.Type.Byte:
486                                 case BuiltinTypeSpec.Type.SByte:
487                                 case BuiltinTypeSpec.Type.Short:
488                                 case BuiltinTypeSpec.Type.UShort:
489                                 case BuiltinTypeSpec.Type.Char:
490                                         return Convert.ImplicitNumericConversion (expr, rc.BuiltinTypes.Int);
491                                 }
492                         }
493
494                         if (op == Operator.UnaryNegation && expr_type.BuiltinType == BuiltinTypeSpec.Type.UInt)
495                                 return Convert.ImplicitNumericConversion (expr, rc.BuiltinTypes.Long);
496
497                         return expr;
498                 }
499
500                 protected override Expression DoResolve (ResolveContext ec)
501                 {
502                         if (Oper == Operator.AddressOf) {
503                                 return ResolveAddressOf (ec);
504                         }
505
506                         Expr = Expr.Resolve (ec);
507                         if (Expr == null)
508                                 return null;
509
510                         if (Expr.Type.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
511                                 Arguments args = new Arguments (1);
512                                 args.Add (new Argument (Expr));
513                                 return new DynamicUnaryConversion (GetOperatorExpressionTypeName (), args, loc).Resolve (ec);
514                         }
515
516                         if (Expr.Type.IsNullableType)
517                                 return new Nullable.LiftedUnaryOperator (Oper, Expr, loc).Resolve (ec);
518
519                         //
520                         // Attempt to use a constant folding operation.
521                         //
522                         Constant cexpr = Expr as Constant;
523                         if (cexpr != null) {
524                                 cexpr = TryReduceConstant (ec, cexpr);
525                                 if (cexpr != null)
526                                         return cexpr;
527                         }
528
529                         Expression expr = ResolveOperator (ec, Expr);
530                         if (expr == null)
531                                 Error_OperatorCannotBeApplied (ec, loc, OperName (Oper), Expr.Type);
532                         
533                         //
534                         // Reduce unary operator on predefined types
535                         //
536                         if (expr == this && Oper == Operator.UnaryPlus)
537                                 return Expr;
538
539                         return expr;
540                 }
541
542                 public override Expression DoResolveLValue (ResolveContext ec, Expression right)
543                 {
544                         return null;
545                 }
546
547                 public override void Emit (EmitContext ec)
548                 {
549                         EmitOperator (ec, type);
550                 }
551
552                 protected void EmitOperator (EmitContext ec, TypeSpec type)
553                 {
554                         switch (Oper) {
555                         case Operator.UnaryPlus:
556                                 Expr.Emit (ec);
557                                 break;
558                                 
559                         case Operator.UnaryNegation:
560                                 if (ec.HasSet (EmitContext.Options.CheckedScope) && !IsFloat (type)) {
561                                         if (ec.HasSet (BuilderContext.Options.AsyncBody) && Expr.ContainsEmitWithAwait ())
562                                                 Expr = Expr.EmitToField (ec);
563
564                                         ec.EmitInt (0);
565                                         if (type.BuiltinType == BuiltinTypeSpec.Type.Long)
566                                                 ec.Emit (OpCodes.Conv_U8);
567                                         Expr.Emit (ec);
568                                         ec.Emit (OpCodes.Sub_Ovf);
569                                 } else {
570                                         Expr.Emit (ec);
571                                         ec.Emit (OpCodes.Neg);
572                                 }
573                                 
574                                 break;
575                                 
576                         case Operator.LogicalNot:
577                                 Expr.Emit (ec);
578                                 ec.EmitInt (0);
579                                 ec.Emit (OpCodes.Ceq);
580                                 break;
581                                 
582                         case Operator.OnesComplement:
583                                 Expr.Emit (ec);
584                                 ec.Emit (OpCodes.Not);
585                                 break;
586                                 
587                         case Operator.AddressOf:
588                                 ((IMemoryLocation)Expr).AddressOf (ec, AddressOp.LoadStore);
589                                 break;
590                                 
591                         default:
592                                 throw new Exception ("This should not happen: Operator = "
593                                                      + Oper.ToString ());
594                         }
595
596                         //
597                         // Same trick as in Binary expression
598                         //
599                         if (enum_conversion != 0) {
600                                 using (ec.With (BuilderContext.Options.CheckedScope, false)) {
601                                         ConvCast.Emit (ec, enum_conversion);
602                                 }
603                         }
604                 }
605
606                 public override void EmitBranchable (EmitContext ec, Label target, bool on_true)
607                 {
608                         if (Oper == Operator.LogicalNot)
609                                 Expr.EmitBranchable (ec, target, !on_true);
610                         else
611                                 base.EmitBranchable (ec, target, on_true);
612                 }
613
614                 public override void EmitSideEffect (EmitContext ec)
615                 {
616                         Expr.EmitSideEffect (ec);
617                 }
618
619                 public static void Error_Ambiguous (ResolveContext rc, string oper, TypeSpec type, Location loc)
620                 {
621                         rc.Report.Error (35, loc, "Operator `{0}' is ambiguous on an operand of type `{1}'",
622                                 oper, type.GetSignatureForError ());
623                 }
624
625                 public override void FlowAnalysis (FlowAnalysisContext fc)
626                 {
627                         FlowAnalysis (fc, false);
628                 }
629
630                 public override void FlowAnalysisConditional (FlowAnalysisContext fc)
631                 {
632                         FlowAnalysis (fc, true);
633                 }
634
635                 void FlowAnalysis (FlowAnalysisContext fc, bool conditional)
636                 {
637                         if (Oper == Operator.AddressOf) {
638                                 var vr = Expr as VariableReference;
639                                 if (vr != null && vr.VariableInfo != null)
640                                         fc.SetVariableAssigned (vr.VariableInfo);
641
642                                 return;
643                         }
644
645                         if (Oper == Operator.LogicalNot && conditional) {
646                                 Expr.FlowAnalysisConditional (fc);
647
648                                 var temp = fc.DefiniteAssignmentOnTrue;
649                                 fc.DefiniteAssignmentOnTrue = fc.DefiniteAssignmentOnFalse;
650                                 fc.DefiniteAssignmentOnFalse = temp;
651                         } else {
652                                 Expr.FlowAnalysis (fc);
653                         }
654                 }
655
656                 //
657                 // Converts operator to System.Linq.Expressions.ExpressionType enum name
658                 //
659                 string GetOperatorExpressionTypeName ()
660                 {
661                         switch (Oper) {
662                         case Operator.OnesComplement:
663                                 return "OnesComplement";
664                         case Operator.LogicalNot:
665                                 return "Not";
666                         case Operator.UnaryNegation:
667                                 return "Negate";
668                         case Operator.UnaryPlus:
669                                 return "UnaryPlus";
670                         default:
671                                 throw new NotImplementedException ("Unknown express type operator " + Oper.ToString ());
672                         }
673                 }
674
675                 static bool IsFloat (TypeSpec t)
676                 {
677                         return t.BuiltinType == BuiltinTypeSpec.Type.Double || t.BuiltinType == BuiltinTypeSpec.Type.Float;
678                 }
679
680                 //
681                 // Returns a stringified representation of the Operator
682                 //
683                 public static string OperName (Operator oper)
684                 {
685                         switch (oper) {
686                         case Operator.UnaryPlus:
687                                 return "+";
688                         case Operator.UnaryNegation:
689                                 return "-";
690                         case Operator.LogicalNot:
691                                 return "!";
692                         case Operator.OnesComplement:
693                                 return "~";
694                         case Operator.AddressOf:
695                                 return "&";
696                         }
697
698                         throw new NotImplementedException (oper.ToString ());
699                 }
700
701                 public override SLE.Expression MakeExpression (BuilderContext ctx)
702                 {
703                         var expr = Expr.MakeExpression (ctx);
704                         bool is_checked = ctx.HasSet (BuilderContext.Options.CheckedScope);
705
706                         switch (Oper) {
707                         case Operator.UnaryNegation:
708                                 return is_checked ? SLE.Expression.NegateChecked (expr) : SLE.Expression.Negate (expr);
709                         case Operator.LogicalNot:
710                                 return SLE.Expression.Not (expr);
711                         case Operator.OnesComplement:
712                                 return SLE.Expression.OnesComplement (expr);
713                         default:
714                                 throw new NotImplementedException (Oper.ToString ());
715                         }
716                 }
717
718                 Expression ResolveAddressOf (ResolveContext ec)
719                 {
720                         if (!ec.IsUnsafe)
721                                 UnsafeError (ec, loc);
722
723                         Expr = Expr.DoResolveLValue (ec, EmptyExpression.UnaryAddress);
724                         if (Expr == null || Expr.eclass != ExprClass.Variable) {
725                                 ec.Report.Error (211, loc, "Cannot take the address of the given expression");
726                                 return null;
727                         }
728
729                         if (!TypeManager.VerifyUnmanaged (ec.Module, Expr.Type, loc)) {
730                                 return null;
731                         }
732
733                         IVariableReference vr = Expr as IVariableReference;
734                         bool is_fixed;
735                         if (vr != null) {
736                                 is_fixed = vr.IsFixed;
737                                 vr.SetHasAddressTaken ();
738
739                                 if (vr.IsHoisted) {
740                                         AnonymousMethodExpression.Error_AddressOfCapturedVar (ec, vr, loc);
741                                 }
742                         } else {
743                                 IFixedExpression fe = Expr as IFixedExpression;
744                                 is_fixed = fe != null && fe.IsFixed;
745                         }
746
747                         if (!is_fixed && !ec.HasSet (ResolveContext.Options.FixedInitializerScope)) {
748                                 ec.Report.Error (212, loc, "You can only take the address of unfixed expression inside of a fixed statement initializer");
749                         }
750
751                         type = PointerContainer.MakeType (ec.Module, Expr.Type);
752                         eclass = ExprClass.Value;
753                         return this;
754                 }
755
756                 Expression ResolvePrimitivePredefinedType (ResolveContext rc, Expression expr, TypeSpec[] predefined)
757                 {
758                         expr = DoNumericPromotion (rc, Oper, expr);
759                         TypeSpec expr_type = expr.Type;
760                         foreach (TypeSpec t in predefined) {
761                                 if (t == expr_type)
762                                         return expr;
763                         }
764                         return null;
765                 }
766
767                 //
768                 // Perform user-operator overload resolution
769                 //
770                 protected virtual Expression ResolveUserOperator (ResolveContext ec, Expression expr)
771                 {
772                         CSharp.Operator.OpType op_type;
773                         switch (Oper) {
774                         case Operator.LogicalNot:
775                                 op_type = CSharp.Operator.OpType.LogicalNot; break;
776                         case Operator.OnesComplement:
777                                 op_type = CSharp.Operator.OpType.OnesComplement; break;
778                         case Operator.UnaryNegation:
779                                 op_type = CSharp.Operator.OpType.UnaryNegation; break;
780                         case Operator.UnaryPlus:
781                                 op_type = CSharp.Operator.OpType.UnaryPlus; break;
782                         default:
783                                 throw new InternalErrorException (Oper.ToString ());
784                         }
785
786                         var methods = MemberCache.GetUserOperator (expr.Type, op_type, false);
787                         if (methods == null)
788                                 return null;
789
790                         Arguments args = new Arguments (1);
791                         args.Add (new Argument (expr));
792
793                         var res = new OverloadResolver (methods, OverloadResolver.Restrictions.BaseMembersIncluded | OverloadResolver.Restrictions.NoBaseMembers, loc);
794                         var oper = res.ResolveOperator (ec, ref args);
795
796                         if (oper == null)
797                                 return null;
798
799                         Expr = args [0].Expr;
800                         return new UserOperatorCall (oper, args, CreateExpressionTree, expr.Location);
801                 }
802
803                 //
804                 // Unary user type overload resolution
805                 //
806                 Expression ResolveUserType (ResolveContext ec, Expression expr, TypeSpec[] predefined)
807                 {
808                         Expression best_expr = ResolveUserOperator (ec, expr);
809                         if (best_expr != null)
810                                 return best_expr;
811
812                         foreach (TypeSpec t in predefined) {
813                                 Expression oper_expr = Convert.ImplicitUserConversion (ec, expr, t, expr.Location);
814                                 if (oper_expr == null)
815                                         continue;
816
817                                 if (oper_expr == ErrorExpression.Instance)
818                                         return oper_expr;
819
820                                 //
821                                 // decimal type is predefined but has user-operators
822                                 //
823                                 if (oper_expr.Type.BuiltinType == BuiltinTypeSpec.Type.Decimal)
824                                         oper_expr = ResolveUserType (ec, oper_expr, predefined);
825                                 else
826                                         oper_expr = ResolvePrimitivePredefinedType (ec, oper_expr, predefined);
827
828                                 if (oper_expr == null)
829                                         continue;
830
831                                 if (best_expr == null) {
832                                         best_expr = oper_expr;
833                                         continue;
834                                 }
835
836                                 int result = OverloadResolver.BetterTypeConversion (ec, best_expr.Type, t);
837                                 if (result == 0) {
838                                         if ((oper_expr is UserOperatorCall || oper_expr is UserCast) && (best_expr is UserOperatorCall || best_expr is UserCast)) {
839                                                 Error_Ambiguous (ec, OperName (Oper), expr.Type, loc);
840                                         } else {
841                                                 Error_OperatorCannotBeApplied (ec, loc, OperName (Oper), expr.Type);
842                                         }
843
844                                         break;
845                                 }
846
847                                 if (result == 2)
848                                         best_expr = oper_expr;
849                         }
850                         
851                         if (best_expr == null)
852                                 return null;
853                         
854                         //
855                         // HACK: Decimal user-operator is included in standard operators
856                         //
857                         if (best_expr.Type.BuiltinType == BuiltinTypeSpec.Type.Decimal)
858                                 return best_expr;
859
860                         Expr = best_expr;
861                         type = best_expr.Type;
862                         return this;                    
863                 }
864
865                 protected override void CloneTo (CloneContext clonectx, Expression t)
866                 {
867                         Unary target = (Unary) t;
868
869                         target.Expr = Expr.Clone (clonectx);
870                 }
871                 
872                 public override object Accept (StructuralVisitor visitor)
873                 {
874                         return visitor.Visit (this);
875                 }
876
877         }
878
879         //
880         // Unary operators are turned into Indirection expressions
881         // after semantic analysis (this is so we can take the address
882         // of an indirection).
883         //
884         public class Indirection : Expression, IMemoryLocation, IAssignMethod, IFixedExpression {
885                 Expression expr;
886                 LocalTemporary temporary;
887                 bool prepared;
888                 
889                 public Indirection (Expression expr, Location l)
890                 {
891                         this.expr = expr;
892                         loc = l;
893                 }
894
895                 public Expression Expr {
896                         get {
897                                 return expr;
898                         }
899                 }
900
901                 public bool IsFixed {
902                         get { return true; }
903                 }
904
905                 public override Location StartLocation {
906                         get {
907                                 return expr.StartLocation;
908                         }
909                 }
910
911                 protected override void CloneTo (CloneContext clonectx, Expression t)
912                 {
913                         Indirection target = (Indirection) t;
914                         target.expr = expr.Clone (clonectx);
915                 }
916
917                 public override bool ContainsEmitWithAwait ()
918                 {
919                         throw new NotImplementedException ();
920                 }
921
922                 public override Expression CreateExpressionTree (ResolveContext ec)
923                 {
924                         Error_PointerInsideExpressionTree (ec);
925                         return null;
926                 }
927                 
928                 public override void Emit (EmitContext ec)
929                 {
930                         if (!prepared)
931                                 expr.Emit (ec);
932                         
933                         ec.EmitLoadFromPtr (Type);
934                 }
935
936                 public void Emit (EmitContext ec, bool leave_copy)
937                 {
938                         Emit (ec);
939                         if (leave_copy) {
940                                 ec.Emit (OpCodes.Dup);
941                                 temporary = new LocalTemporary (expr.Type);
942                                 temporary.Store (ec);
943                         }
944                 }
945                 
946                 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool isCompound)
947                 {
948                         prepared = isCompound;
949                         
950                         expr.Emit (ec);
951
952                         if (isCompound)
953                                 ec.Emit (OpCodes.Dup);
954                         
955                         source.Emit (ec);
956                         if (leave_copy) {
957                                 ec.Emit (OpCodes.Dup);
958                                 temporary = new LocalTemporary (source.Type);
959                                 temporary.Store (ec);
960                         }
961                         
962                         ec.EmitStoreFromPtr (type);
963                         
964                         if (temporary != null) {
965                                 temporary.Emit (ec);
966                                 temporary.Release (ec);
967                         }
968                 }
969                 
970                 public void AddressOf (EmitContext ec, AddressOp Mode)
971                 {
972                         expr.Emit (ec);
973                 }
974
975                 public override Expression DoResolveLValue (ResolveContext ec, Expression right_side)
976                 {
977                         return DoResolve (ec);
978                 }
979
980                 protected override Expression DoResolve (ResolveContext ec)
981                 {
982                         expr = expr.Resolve (ec);
983                         if (expr == null)
984                                 return null;
985
986                         if (!ec.IsUnsafe)
987                                 UnsafeError (ec, loc);
988
989                         var pc = expr.Type as PointerContainer;
990
991                         if (pc == null) {
992                                 ec.Report.Error (193, loc, "The * or -> operator must be applied to a pointer");
993                                 return null;
994                         }
995
996                         type = pc.Element;
997
998                         if (type.Kind == MemberKind.Void) {
999                                 Error_VoidPointerOperation (ec);
1000                                 return null;
1001                         }
1002
1003                         eclass = ExprClass.Variable;
1004                         return this;
1005                 }
1006
1007                 public override object Accept (StructuralVisitor visitor)
1008                 {
1009                         return visitor.Visit (this);
1010                 }
1011         }
1012         
1013         /// <summary>
1014         ///   Unary Mutator expressions (pre and post ++ and --)
1015         /// </summary>
1016         ///
1017         /// <remarks>
1018         ///   UnaryMutator implements ++ and -- expressions.   It derives from
1019         ///   ExpressionStatement becuase the pre/post increment/decrement
1020         ///   operators can be used in a statement context.
1021         ///
1022         /// FIXME: Idea, we could split this up in two classes, one simpler
1023         /// for the common case, and one with the extra fields for more complex
1024         /// classes (indexers require temporary access;  overloaded require method)
1025         ///
1026         /// </remarks>
1027         public class UnaryMutator : ExpressionStatement
1028         {
1029                 class DynamicPostMutator : Expression, IAssignMethod
1030                 {
1031                         LocalTemporary temp;
1032                         Expression expr;
1033
1034                         public DynamicPostMutator (Expression expr)
1035                         {
1036                                 this.expr = expr;
1037                                 this.type = expr.Type;
1038                                 this.loc = expr.Location;
1039                         }
1040
1041                         public override Expression CreateExpressionTree (ResolveContext ec)
1042                         {
1043                                 throw new NotImplementedException ("ET");
1044                         }
1045
1046                         protected override Expression DoResolve (ResolveContext rc)
1047                         {
1048                                 eclass = expr.eclass;
1049                                 return this;
1050                         }
1051
1052                         public override Expression DoResolveLValue (ResolveContext ec, Expression right_side)
1053                         {
1054                                 expr.DoResolveLValue (ec, right_side);
1055                                 return DoResolve (ec);
1056                         }
1057
1058                         public override void Emit (EmitContext ec)
1059                         {
1060                                 temp.Emit (ec);
1061                         }
1062
1063                         public void Emit (EmitContext ec, bool leave_copy)
1064                         {
1065                                 throw new NotImplementedException ();
1066                         }
1067
1068                         //
1069                         // Emits target assignment using unmodified source value
1070                         //
1071                         public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool isCompound)
1072                         {
1073                                 //
1074                                 // Allocate temporary variable to keep original value before it's modified
1075                                 //
1076                                 temp = new LocalTemporary (type);
1077                                 expr.Emit (ec);
1078                                 temp.Store (ec);
1079
1080                                 ((IAssignMethod) expr).EmitAssign (ec, source, false, isCompound);
1081
1082                                 if (leave_copy)
1083                                         Emit (ec);
1084
1085                                 temp.Release (ec);
1086                                 temp = null;
1087                         }
1088                 }
1089
1090                 [Flags]
1091                 public enum Mode : byte {
1092                         IsIncrement    = 0,
1093                         IsDecrement    = 1,
1094                         IsPre          = 0,
1095                         IsPost         = 2,
1096                         
1097                         PreIncrement   = 0,
1098                         PreDecrement   = IsDecrement,
1099                         PostIncrement  = IsPost,
1100                         PostDecrement  = IsPost | IsDecrement
1101                 }
1102
1103                 Mode mode;
1104                 bool is_expr, recurse;
1105
1106                 protected Expression expr;
1107
1108                 // Holds the real operation
1109                 Expression operation;
1110
1111                 public UnaryMutator (Mode m, Expression e, Location loc)
1112                 {
1113                         mode = m;
1114                         this.loc = loc;
1115                         expr = e;
1116                 }
1117
1118                 public Mode UnaryMutatorMode {
1119                         get {
1120                                 return mode;
1121                         }
1122                 }
1123                 
1124                 public Expression Expr {
1125                         get {
1126                                 return expr;
1127                         }
1128                 }
1129
1130                 public override Location StartLocation {
1131                         get {
1132                                 return (mode & Mode.IsPost) != 0 ? expr.Location : loc;
1133                         }
1134                 }
1135
1136                 public override bool ContainsEmitWithAwait ()
1137                 {
1138                         return expr.ContainsEmitWithAwait ();
1139                 }
1140
1141                 public override Expression CreateExpressionTree (ResolveContext ec)
1142                 {
1143                         return new SimpleAssign (this, this).CreateExpressionTree (ec);
1144                 }
1145
1146                 public static TypeSpec[] CreatePredefinedOperatorsTable (BuiltinTypes types)
1147                 {
1148                         //
1149                         // Predefined ++ and -- operators exist for the following types: 
1150                         // sbyte, byte, short, ushort, int, uint, long, ulong, char, float, double, decimal
1151                         //
1152                         return new TypeSpec[] {
1153                                 types.Int,
1154                                 types.Long,
1155
1156                                 types.SByte,
1157                                 types.Byte,
1158                                 types.Short,
1159                                 types.UInt,
1160                                 types.ULong,
1161                                 types.Char,
1162                                 types.Float,
1163                                 types.Double,
1164                                 types.Decimal
1165                         };
1166                 }
1167
1168                 protected override Expression DoResolve (ResolveContext ec)
1169                 {
1170                         expr = expr.Resolve (ec);
1171                         
1172                         if (expr == null || expr.Type == InternalType.ErrorType)
1173                                 return null;
1174
1175                         if (expr.Type.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
1176                                 //
1177                                 // Handle postfix unary operators using local
1178                                 // temporary variable
1179                                 //
1180                                 if ((mode & Mode.IsPost) != 0)
1181                                         expr = new DynamicPostMutator (expr);
1182
1183                                 Arguments args = new Arguments (1);
1184                                 args.Add (new Argument (expr));
1185                                 return new SimpleAssign (expr, new DynamicUnaryConversion (GetOperatorExpressionTypeName (), args, loc)).Resolve (ec);
1186                         }
1187
1188                         if (expr.Type.IsNullableType)
1189                                 return new Nullable.LiftedUnaryMutator (mode, expr, loc).Resolve (ec);
1190
1191                         return DoResolveOperation (ec);
1192                 }
1193
1194                 protected Expression DoResolveOperation (ResolveContext ec)
1195                 {
1196                         eclass = ExprClass.Value;
1197                         type = expr.Type;
1198
1199                         if (expr is RuntimeValueExpression) {
1200                                 operation = expr;
1201                         } else {
1202                                 // Use itself at the top of the stack
1203                                 operation = new EmptyExpression (type);
1204                         }
1205
1206                         //
1207                         // The operand of the prefix/postfix increment decrement operators
1208                         // should be an expression that is classified as a variable,
1209                         // a property access or an indexer access
1210                         //
1211                         // TODO: Move to parser, expr is ATypeNameExpression
1212                         if (expr.eclass == ExprClass.Variable || expr.eclass == ExprClass.IndexerAccess || expr.eclass == ExprClass.PropertyAccess) {
1213                                 expr = expr.ResolveLValue (ec, expr);
1214                         } else {
1215                                 ec.Report.Error (1059, loc, "The operand of an increment or decrement operator must be a variable, property or indexer");
1216                         }
1217
1218                         //
1219                         // Step 1: Try to find a user operator, it has priority over predefined ones
1220                         //
1221                         var user_op = IsDecrement ? Operator.OpType.Decrement : Operator.OpType.Increment;
1222                         var methods = MemberCache.GetUserOperator (type, user_op, false);
1223
1224                         if (methods != null) {
1225                                 Arguments args = new Arguments (1);
1226                                 args.Add (new Argument (expr));
1227
1228                                 var res = new OverloadResolver (methods, OverloadResolver.Restrictions.BaseMembersIncluded | OverloadResolver.Restrictions.NoBaseMembers, loc);
1229                                 var method = res.ResolveOperator (ec, ref args);
1230                                 if (method == null)
1231                                         return null;
1232
1233                                 args[0].Expr = operation;
1234                                 operation = new UserOperatorCall (method, args, null, loc);
1235                                 operation = Convert.ImplicitConversionRequired (ec, operation, type, loc);
1236                                 return this;
1237                         }
1238
1239                         //
1240                         // Step 2: Try predefined types
1241                         //
1242
1243                         Expression source = null;
1244                         bool primitive_type;
1245
1246                         //
1247                         // Predefined without user conversion first for speed-up
1248                         //
1249                         // Predefined ++ and -- operators exist for the following types: 
1250                         // sbyte, byte, short, ushort, int, uint, long, ulong, char, float, double, decimal
1251                         //
1252                         switch (type.BuiltinType) {
1253                         case BuiltinTypeSpec.Type.Byte:
1254                         case BuiltinTypeSpec.Type.SByte:
1255                         case BuiltinTypeSpec.Type.Short:
1256                         case BuiltinTypeSpec.Type.UShort:
1257                         case BuiltinTypeSpec.Type.Int:
1258                         case BuiltinTypeSpec.Type.UInt:
1259                         case BuiltinTypeSpec.Type.Long:
1260                         case BuiltinTypeSpec.Type.ULong:
1261                         case BuiltinTypeSpec.Type.Char:
1262                         case BuiltinTypeSpec.Type.Float:
1263                         case BuiltinTypeSpec.Type.Double:
1264                         case BuiltinTypeSpec.Type.Decimal:
1265                                 source = operation;
1266                                 primitive_type = true;
1267                                 break;
1268                         default:
1269                                 primitive_type = false;
1270
1271                                 // ++/-- on pointer variables of all types except void*
1272                                 if (type.IsPointer) {
1273                                         if (((PointerContainer) type).Element.Kind == MemberKind.Void) {
1274                                                 Error_VoidPointerOperation (ec);
1275                                                 return null;
1276                                         }
1277
1278                                         source = operation;
1279                                 } else {
1280                                         Expression best_source = null;
1281                                         foreach (var t in ec.BuiltinTypes.OperatorsUnaryMutator) {
1282                                                 source = Convert.ImplicitUserConversion (ec, operation, t, loc);
1283
1284                                                 // LAMESPEC: It should error on ambiguous operators but that would make us incompatible
1285                                                 if (source == null)
1286                                                         continue;
1287
1288                                                 if (best_source == null) {
1289                                                         best_source = source;
1290                                                         continue;
1291                                                 }
1292
1293                                                 var better = OverloadResolver.BetterTypeConversion (ec, best_source.Type, source.Type);
1294                                                 if (better == 1)
1295                                                         continue;
1296
1297                                                 if (better == 2) {
1298                                                         best_source = source;
1299                                                         continue;
1300                                                 }
1301
1302                                                 Unary.Error_Ambiguous (ec, OperName (mode), type, loc);
1303                                                 break;
1304                                         }
1305
1306                                         source = best_source;
1307                                 }
1308
1309                                 // ++/-- on enum types
1310                                 if (source == null && type.IsEnum)
1311                                         source = operation;
1312
1313                                 if (source == null) {
1314                                         expr.Error_OperatorCannotBeApplied (ec, loc, Operator.GetName (user_op), type);
1315                                         return null;
1316                                 }
1317
1318                                 break;
1319                         }
1320
1321                         var one = new IntConstant (ec.BuiltinTypes, 1, loc);
1322                         var op = IsDecrement ? Binary.Operator.Subtraction : Binary.Operator.Addition;
1323                         operation = new Binary (op, source, one);
1324                         operation = operation.Resolve (ec);
1325                         if (operation == null)
1326                                 throw new NotImplementedException ("should not be reached");
1327
1328                         if (operation.Type != type) {
1329                                 if (primitive_type)
1330                                         operation = Convert.ExplicitNumericConversion (ec, operation, type);
1331                                 else
1332                                         operation = Convert.ImplicitConversionRequired (ec, operation, type, loc);
1333                         }
1334
1335                         return this;
1336                 }
1337
1338                 void EmitCode (EmitContext ec, bool is_expr)
1339                 {
1340                         recurse = true;
1341                         this.is_expr = is_expr;
1342                         ((IAssignMethod) expr).EmitAssign (ec, this, is_expr && (mode == Mode.PreIncrement || mode == Mode.PreDecrement), true);
1343                 }
1344
1345                 public override void Emit (EmitContext ec)
1346                 {
1347                         //
1348                         // We use recurse to allow ourselfs to be the source
1349                         // of an assignment. This little hack prevents us from
1350                         // having to allocate another expression
1351                         //
1352                         if (recurse) {
1353                                 ((IAssignMethod) expr).Emit (ec, is_expr && (mode == Mode.PostIncrement || mode == Mode.PostDecrement));
1354
1355                                 EmitOperation (ec);
1356
1357                                 recurse = false;
1358                                 return;
1359                         }
1360
1361                         EmitCode (ec, true);
1362                 }
1363
1364                 protected virtual void EmitOperation (EmitContext ec)
1365                 {
1366                         operation.Emit (ec);
1367                 }
1368
1369                 public override void EmitStatement (EmitContext ec)
1370                 {
1371                         EmitCode (ec, false);
1372                 }
1373
1374                 public override void FlowAnalysis (FlowAnalysisContext fc)
1375                 {
1376                         expr.FlowAnalysis (fc);
1377                 }
1378
1379                 //
1380                 // Converts operator to System.Linq.Expressions.ExpressionType enum name
1381                 //
1382                 string GetOperatorExpressionTypeName ()
1383                 {
1384                         return IsDecrement ? "Decrement" : "Increment";
1385                 }
1386
1387                 bool IsDecrement {
1388                         get { return (mode & Mode.IsDecrement) != 0; }
1389                 }
1390
1391
1392                 public override SLE.Expression MakeExpression (BuilderContext ctx)
1393                 {
1394                         var target = ((RuntimeValueExpression) expr).MetaObject.Expression;
1395                         var source = SLE.Expression.Convert (operation.MakeExpression (ctx), target.Type);
1396                         return SLE.Expression.Assign (target, source);
1397                 }
1398
1399                 public static string OperName (Mode oper)
1400                 {
1401                         return (oper & Mode.IsDecrement) != 0 ? "--" : "++";
1402                 }
1403
1404                 protected override void CloneTo (CloneContext clonectx, Expression t)
1405                 {
1406                         UnaryMutator target = (UnaryMutator) t;
1407
1408                         target.expr = expr.Clone (clonectx);
1409                 }
1410
1411                 public override object Accept (StructuralVisitor visitor)
1412                 {
1413                         return visitor.Visit (this);
1414                 }
1415
1416         }
1417
1418         //
1419         // Base class for the `is' and `as' operators
1420         //
1421         public abstract class Probe : Expression
1422         {
1423                 public Expression ProbeType;
1424                 protected Expression expr;
1425                 protected TypeSpec probe_type_expr;
1426                 
1427                 protected Probe (Expression expr, Expression probe_type, Location l)
1428                 {
1429                         ProbeType = probe_type;
1430                         loc = l;
1431                         this.expr = expr;
1432                 }
1433
1434                 public Expression Expr {
1435                         get {
1436                                 return expr;
1437                         }
1438                 }
1439
1440                 public override bool ContainsEmitWithAwait ()
1441                 {
1442                         return expr.ContainsEmitWithAwait ();
1443                 }
1444
1445                 protected Expression ResolveCommon (ResolveContext rc)
1446                 {
1447                         expr = expr.Resolve (rc);
1448                         if (expr == null)
1449                                 return null;
1450
1451                         ResolveProbeType (rc);
1452                         if (probe_type_expr == null)
1453                                 return this;
1454
1455                         if (probe_type_expr.IsStatic) {
1456                                 rc.Report.Error (7023, loc, "The second operand of `is' or `as' operator cannot be static type `{0}'",
1457                                         probe_type_expr.GetSignatureForError ());
1458                                 return null;
1459                         }
1460                         
1461                         if (expr.Type.IsPointer || probe_type_expr.IsPointer) {
1462                                 rc.Report.Error (244, loc, "The `{0}' operator cannot be applied to an operand of pointer type",
1463                                         OperatorName);
1464                                 return null;
1465                         }
1466
1467                         if (expr.Type == InternalType.AnonymousMethod || expr.Type == InternalType.MethodGroup) {
1468                                 rc.Report.Error (837, loc, "The `{0}' operator cannot be applied to a lambda expression, anonymous method, or method group",
1469                                         OperatorName);
1470                                 return null;
1471                         }
1472
1473                         return this;
1474                 }
1475
1476                 protected virtual void ResolveProbeType (ResolveContext rc)
1477                 {
1478                         probe_type_expr = ProbeType.ResolveAsType (rc);
1479                 }
1480
1481                 public override void EmitSideEffect (EmitContext ec)
1482                 {
1483                         expr.EmitSideEffect (ec);
1484                 }
1485
1486                 public override void FlowAnalysis (FlowAnalysisContext fc)
1487                 {
1488                         expr.FlowAnalysis (fc);
1489                 }
1490
1491                 public override bool HasConditionalAccess ()
1492                 {
1493                         return expr.HasConditionalAccess ();
1494                 }
1495
1496                 protected abstract string OperatorName { get; }
1497
1498                 protected override void CloneTo (CloneContext clonectx, Expression t)
1499                 {
1500                         Probe target = (Probe) t;
1501
1502                         target.expr = expr.Clone (clonectx);
1503                         target.ProbeType = ProbeType.Clone (clonectx);
1504                 }
1505
1506         }
1507
1508         /// <summary>
1509         ///   Implementation of the `is' operator.
1510         /// </summary>
1511         public class Is : Probe
1512         {
1513                 Nullable.Unwrap expr_unwrap;
1514                 MethodSpec number_mg;
1515                 Arguments number_args;
1516
1517                 public Is (Expression expr, Expression probe_type, Location l)
1518                         : base (expr, probe_type, l)
1519                 {
1520                 }
1521
1522                 protected override string OperatorName {
1523                         get { return "is"; }
1524                 }
1525
1526                 public LocalVariable Variable { get; set; }
1527
1528                 public override Expression CreateExpressionTree (ResolveContext ec)
1529                 {
1530                         if (Variable != null)
1531                                 throw new NotSupportedException ();
1532
1533                         Arguments args = Arguments.CreateForExpressionTree (ec, null,
1534                                 expr.CreateExpressionTree (ec),
1535                                 new TypeOf (probe_type_expr, loc));
1536
1537                         return CreateExpressionFactoryCall (ec, "TypeIs", args);
1538                 }
1539
1540                 Expression CreateConstantResult (ResolveContext rc, bool result)
1541                 {
1542                         if (result)
1543                                 rc.Report.Warning (183, 1, loc, "The given expression is always of the provided (`{0}') type",
1544                                         probe_type_expr.GetSignatureForError ());
1545                         else
1546                                 rc.Report.Warning (184, 1, loc, "The given expression is never of the provided (`{0}') type",
1547                                         probe_type_expr.GetSignatureForError ());
1548
1549                         var c = new BoolConstant (rc.BuiltinTypes, result, loc);
1550                         return expr.IsSideEffectFree ?
1551                                 ReducedExpression.Create (c, this) :
1552                                 new SideEffectConstant (c, this, loc);
1553                 }
1554
1555                 public override void Emit (EmitContext ec)
1556                 {
1557                         if (probe_type_expr == null) {
1558                                 if (ProbeType is WildcardPattern) {
1559                                         expr.EmitSideEffect (ec);
1560                                         ProbeType.Emit (ec);
1561                                 } else {
1562                                         EmitPatternMatch (ec);
1563                                 }
1564                                 return;
1565                         }
1566
1567                         EmitLoad (ec);
1568
1569                         if (expr_unwrap == null) {
1570                                 ec.EmitNull ();
1571                                 ec.Emit (OpCodes.Cgt_Un);
1572                         }
1573                 }
1574
1575                 public override void EmitBranchable (EmitContext ec, Label target, bool on_true)
1576                 {
1577                         if (probe_type_expr == null) {
1578                                 EmitPatternMatch (ec);
1579                         } else {
1580                                 EmitLoad (ec);
1581                         }
1582
1583                         ec.Emit (on_true ? OpCodes.Brtrue : OpCodes.Brfalse, target);
1584                 }
1585
1586                 void EmitPatternMatch (EmitContext ec)
1587                 {
1588                         var no_match = ec.DefineLabel ();
1589                         var end = ec.DefineLabel ();
1590
1591                         if (expr_unwrap != null) {
1592                                 expr_unwrap.EmitCheck (ec);
1593
1594                                 if (ProbeType.IsNull) {
1595                                         ec.EmitInt (0);
1596                                         ec.Emit (OpCodes.Ceq);
1597                                         return;
1598                                 }
1599
1600                                 ec.Emit (OpCodes.Brfalse_S, no_match);
1601                                 expr_unwrap.Emit (ec);
1602                                 ProbeType.Emit (ec);
1603                                 ec.Emit (OpCodes.Ceq);
1604                                 ec.Emit (OpCodes.Br_S, end);
1605                                 ec.MarkLabel (no_match);
1606                                 ec.EmitInt (0);
1607                                 ec.MarkLabel (end);
1608                                 return;
1609                         }
1610
1611                         if (number_args != null && number_args.Count == 3) {
1612                                 var ce = new CallEmitter ();
1613                                 ce.Emit (ec, number_mg, number_args, loc);
1614                                 return;
1615                         }
1616
1617                         var probe_type = ProbeType.Type;
1618
1619                         Expr.Emit (ec);
1620                         ec.Emit (OpCodes.Isinst, probe_type);
1621                         ec.Emit (OpCodes.Dup);
1622                         ec.Emit (OpCodes.Brfalse, no_match);
1623
1624                         bool complex_pattern = ProbeType is ComplexPatternExpression;
1625                         Label prev = ec.RecursivePatternLabel;
1626                         if (complex_pattern)
1627                                 ec.RecursivePatternLabel = ec.DefineLabel ();
1628
1629                         if (number_mg != null) {
1630                                 var ce = new CallEmitter ();
1631                                 ce.Emit (ec, number_mg, number_args, loc);
1632                         } else {
1633                                 if (TypeSpec.IsValueType (probe_type))
1634                                         ec.Emit (OpCodes.Unbox_Any, probe_type);
1635
1636                                 ProbeType.Emit (ec);
1637                                 if (complex_pattern) {
1638                                         ec.EmitInt (1);
1639                                 } else {
1640                                         ec.Emit (OpCodes.Ceq);
1641                                 }
1642                         }
1643                         ec.Emit (OpCodes.Br_S, end);
1644                         ec.MarkLabel (no_match);
1645
1646                         ec.Emit (OpCodes.Pop);
1647
1648                         if (complex_pattern)
1649                                 ec.MarkLabel (ec.RecursivePatternLabel);
1650
1651                         ec.RecursivePatternLabel = prev;
1652
1653                         ec.EmitInt (0);
1654                         ec.MarkLabel (end);
1655                 }
1656
1657                 void EmitLoad (EmitContext ec)
1658                 {
1659                         Label no_value_label = new Label ();
1660
1661                         if (expr_unwrap != null) {
1662                                 expr_unwrap.EmitCheck (ec);
1663
1664                                 if (Variable == null)
1665                                         return;
1666
1667                                 ec.Emit (OpCodes.Dup);
1668                                 no_value_label = ec.DefineLabel ();
1669                                 ec.Emit (OpCodes.Brfalse_S, no_value_label);
1670                                 expr_unwrap.Emit (ec);
1671                         } else {
1672                                 expr.Emit (ec);
1673
1674                                 // Only to make verifier happy
1675                                 if (probe_type_expr.IsGenericParameter && TypeSpec.IsValueType (expr.Type))
1676                                         ec.Emit (OpCodes.Box, expr.Type);
1677
1678                                 ec.Emit (OpCodes.Isinst, probe_type_expr);
1679                         }
1680
1681                         if (Variable != null) {
1682                                 bool value_on_stack;
1683                                 if (probe_type_expr.IsGenericParameter || probe_type_expr.IsNullableType) {
1684                                         ec.Emit (OpCodes.Dup);
1685                                         ec.Emit (OpCodes.Unbox_Any, probe_type_expr);
1686                                         value_on_stack = true;
1687                                 } else {
1688                                         value_on_stack = false;
1689                                 }
1690
1691                                 Variable.CreateBuilder (ec);
1692                                 Variable.EmitAssign (ec);
1693
1694                                 if (expr_unwrap != null) {
1695                                         ec.MarkLabel (no_value_label);
1696                                 } else if (!value_on_stack) {
1697                                         Variable.Emit (ec);
1698                                 }
1699                         }
1700                 }
1701
1702                 protected override Expression DoResolve (ResolveContext rc)
1703                 {
1704                         if (ResolveCommon (rc) == null)
1705                                 return null;
1706
1707                         type = rc.BuiltinTypes.Bool;
1708                         eclass = ExprClass.Value;
1709
1710                         if (probe_type_expr == null)
1711                                 return ResolveMatchingExpression (rc);
1712
1713                         var res = ResolveResultExpression (rc);
1714                         if (Variable != null) {
1715                                 if (res is Constant)
1716                                         throw new NotImplementedException ("constant in type pattern matching");
1717
1718                                 Variable.Type = probe_type_expr;
1719                                 var bc = rc as BlockContext;
1720                                 if (bc != null)
1721                                         Variable.PrepareAssignmentAnalysis (bc);
1722                         }
1723
1724                         return res;
1725                 }
1726
1727                 public override void FlowAnalysis (FlowAnalysisContext fc)
1728                 {
1729                         base.FlowAnalysis (fc);
1730
1731                         if (Variable != null)
1732                                 fc.SetVariableAssigned (Variable.VariableInfo, true);
1733                 }
1734
1735                 protected override void ResolveProbeType (ResolveContext rc)
1736                 {
1737                         if (!(ProbeType is TypeExpr) && rc.Module.Compiler.Settings.Version == LanguageVersion.Experimental) {
1738                                 if (ProbeType is PatternExpression) {
1739                                         ProbeType.Resolve (rc);
1740                                         return;
1741                                 }
1742
1743                                 //
1744                                 // Have to use session recording because we don't have reliable type probing
1745                                 // mechanism (similar issue as in attributes resolving)
1746                                 //
1747                                 // TODO: This is still wrong because ResolveAsType can be destructive
1748                                 //
1749                                 var type_printer = new SessionReportPrinter ();
1750                                 var prev_recorder = rc.Report.SetPrinter (type_printer);
1751
1752                                 probe_type_expr = ProbeType.ResolveAsType (rc);
1753                                 type_printer.EndSession ();
1754
1755                                 if (probe_type_expr != null) {
1756                                         type_printer.Merge (rc.Report.Printer);
1757                                         rc.Report.SetPrinter (prev_recorder);
1758                                         return;
1759                                 }
1760
1761                                 var vexpr = ProbeType as VarExpr;
1762                                 if (vexpr != null && vexpr.InferType (rc, expr)) {
1763                                         probe_type_expr = vexpr.Type;
1764                                         rc.Report.SetPrinter (prev_recorder);
1765                                         return;
1766                                 }
1767
1768                                 var expr_printer = new SessionReportPrinter ();
1769                                 rc.Report.SetPrinter (expr_printer);
1770                                 ProbeType = ProbeType.Resolve (rc);
1771                                 expr_printer.EndSession ();
1772
1773                                 if (ProbeType != null) {
1774                                         expr_printer.Merge (rc.Report.Printer);
1775                                 } else {
1776                                         type_printer.Merge (rc.Report.Printer);
1777                                 }
1778
1779                                 rc.Report.SetPrinter (prev_recorder);
1780                                 return;
1781                         }
1782
1783                         base.ResolveProbeType (rc);
1784                 }
1785
1786                 Expression ResolveMatchingExpression (ResolveContext rc)
1787                 {
1788                         var mc = ProbeType as Constant;
1789                         if (mc != null) {
1790                                 if (!Convert.ImplicitConversionExists (rc, ProbeType, Expr.Type)) {
1791                                         ProbeType.Error_ValueCannotBeConverted (rc, Expr.Type, false);
1792                                         return null;
1793                                 }
1794
1795                                 if (mc.IsNull)
1796                                         return new Binary (Binary.Operator.Equality, Expr, mc).Resolve (rc);
1797
1798                                 var c = Expr as Constant;
1799                                 if (c != null) {
1800                                         c = ConstantFold.BinaryFold (rc, Binary.Operator.Equality, c, mc, loc);
1801                                         if (c != null)
1802                                                 return c;
1803                                 }
1804
1805                                 if (Expr.Type.IsNullableType) {
1806                                         expr_unwrap = new Nullable.Unwrap (Expr);
1807                                         expr_unwrap.Resolve (rc);
1808                                         ProbeType = Convert.ImplicitConversion (rc, ProbeType, expr_unwrap.Type, loc);
1809                                 } else if (ProbeType.Type == Expr.Type) {
1810                                         // TODO: Better error handling
1811                                         return new Binary (Binary.Operator.Equality, Expr, mc, loc).Resolve (rc);
1812                                 } else if (ProbeType.Type.IsEnum || (ProbeType.Type.BuiltinType >= BuiltinTypeSpec.Type.Byte && ProbeType.Type.BuiltinType <= BuiltinTypeSpec.Type.Decimal)) {
1813                                         var helper = rc.Module.CreatePatterMatchingHelper ();
1814                                         number_mg = helper.NumberMatcher.Spec;
1815
1816                                         //
1817                                         // There are actually 3 arguments but the first one is already on the stack
1818                                         //
1819                                         number_args = new Arguments (3);
1820                                         if (!ProbeType.Type.IsEnum)
1821                                                 number_args.Add (new Argument (Expr));
1822
1823                                         number_args.Add (new Argument (Convert.ImplicitConversion (rc, ProbeType, rc.BuiltinTypes.Object, loc)));
1824                                         number_args.Add (new Argument (new BoolLiteral (rc.BuiltinTypes, ProbeType.Type.IsEnum, loc)));
1825                                 }
1826
1827                                 return this;
1828                         }
1829
1830                         if (ProbeType is PatternExpression) {
1831                                 if (!(ProbeType is WildcardPattern) && !Convert.ImplicitConversionExists (rc, ProbeType, Expr.Type)) {
1832                                         ProbeType.Error_ValueCannotBeConverted (rc, Expr.Type, false);
1833                                 }
1834
1835                                 return this;
1836                         }
1837
1838                         // TODO: Better error message
1839                         rc.Report.Error (150, ProbeType.Location, "A constant value is expected");
1840                         return this;
1841                 }
1842
1843                 Expression ResolveResultExpression (ResolveContext ec)
1844                 {
1845                         TypeSpec d = expr.Type;
1846                         bool d_is_nullable = false;
1847
1848                         //
1849                         // If E is a method group or the null literal, or if the type of E is a reference
1850                         // type or a nullable type and the value of E is null, the result is false
1851                         //
1852                         if (expr.IsNull || expr.eclass == ExprClass.MethodGroup)
1853                                 return CreateConstantResult (ec, false);
1854
1855                         if (d.IsNullableType) {
1856                                 var ut = Nullable.NullableInfo.GetUnderlyingType (d);
1857                                 if (!ut.IsGenericParameter) {
1858                                         d = ut;
1859                                         d_is_nullable = true;
1860                                 }
1861                         }
1862                                 
1863                         TypeSpec t = probe_type_expr;
1864                         bool t_is_nullable = false;
1865                         if (t.IsNullableType) {
1866                                 var ut = Nullable.NullableInfo.GetUnderlyingType (t);
1867                                 if (!ut.IsGenericParameter) {
1868                                         t = ut;
1869                                         t_is_nullable = true;
1870                                 }
1871                         }
1872
1873                         if (t.IsStruct) {
1874                                 if (d == t) {
1875                                         //
1876                                         // D and T are the same value types but D can be null
1877                                         //
1878                                         if (d_is_nullable && !t_is_nullable) {
1879                                                 expr_unwrap = Nullable.Unwrap.Create (expr, true);
1880                                                 return this;
1881                                         }
1882                                         
1883                                         //
1884                                         // The result is true if D and T are the same value types
1885                                         //
1886                                         return CreateConstantResult (ec, true);
1887                                 }
1888
1889                                 var tp = d as TypeParameterSpec;
1890                                 if (tp != null)
1891                                         return ResolveGenericParameter (ec, t, tp);
1892
1893                                 //
1894                                 // An unboxing conversion exists
1895                                 //
1896                                 if (Convert.ExplicitReferenceConversionExists (d, t))
1897                                         return this;
1898
1899                                 //
1900                                 // open generic type
1901                                 //
1902                                 if (d is InflatedTypeSpec && InflatedTypeSpec.ContainsTypeParameter (d))
1903                                         return this;
1904                         } else {
1905                                 var tps = t as TypeParameterSpec;
1906                                 if (tps != null)
1907                                         return ResolveGenericParameter (ec, d, tps);
1908
1909                                 if (t.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
1910                                         ec.Report.Warning (1981, 3, loc,
1911                                                 "Using `{0}' to test compatibility with `{1}' is identical to testing compatibility with `object'",
1912                                                 OperatorName, t.GetSignatureForError ());
1913                                 }
1914
1915                                 if (TypeManager.IsGenericParameter (d))
1916                                         return ResolveGenericParameter (ec, t, (TypeParameterSpec) d);
1917
1918                                 if (TypeSpec.IsValueType (d)) {
1919                                         if (Convert.ImplicitBoxingConversion (null, d, t) != null) {
1920                                                 if (d_is_nullable && !t_is_nullable) {
1921                                                         expr_unwrap = Nullable.Unwrap.Create (expr, false);
1922                                                         return this;
1923                                                 }
1924
1925                                                 return CreateConstantResult (ec, true);
1926                                         }
1927                                 } else {
1928                                         if (Convert.ImplicitReferenceConversionExists (d, t)) {
1929                                                 var c = expr as Constant;
1930                                                 if (c != null)
1931                                                         return CreateConstantResult (ec, !c.IsNull);
1932
1933                                                 //
1934                                                 // Do not optimize for imported type or dynamic type
1935                                                 //
1936                                                 if (d.MemberDefinition.IsImported && d.BuiltinType != BuiltinTypeSpec.Type.None &&
1937                                                         d.MemberDefinition.DeclaringAssembly != t.MemberDefinition.DeclaringAssembly) {
1938                                                         return this;
1939                                                 }
1940
1941                                                 if (d.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
1942                                                         return this;
1943                                                 
1944                                                 //
1945                                                 // Turn is check into simple null check for implicitly convertible reference types
1946                                                 //
1947                                                 return ReducedExpression.Create (
1948                                                         new Binary (Binary.Operator.Inequality, expr, new NullLiteral (loc), Binary.State.UserOperatorsExcluded).Resolve (ec),
1949                                                         this).Resolve (ec);
1950                                         }
1951
1952                                         if (Convert.ExplicitReferenceConversionExists (d, t))
1953                                                 return this;
1954
1955                                         //
1956                                         // open generic type
1957                                         //
1958                                         if ((d is InflatedTypeSpec || d.IsArray) && InflatedTypeSpec.ContainsTypeParameter (d))
1959                                                 return this;
1960                                 }
1961                         }
1962
1963                         return CreateConstantResult (ec, false);
1964                 }
1965
1966                 Expression ResolveGenericParameter (ResolveContext ec, TypeSpec d, TypeParameterSpec t)
1967                 {
1968                         if (t.IsReferenceType) {
1969                                 if (d.IsStruct)
1970                                         return CreateConstantResult (ec, false);
1971                         }
1972
1973                         if (expr.Type.IsGenericParameter) {
1974                                 if (expr.Type == d && TypeSpec.IsValueType (t) && TypeSpec.IsValueType (d))
1975                                         return CreateConstantResult (ec, true);
1976
1977                                 expr = new BoxedCast (expr, d);
1978                         }
1979
1980                         return this;
1981                 }
1982                 
1983                 public override object Accept (StructuralVisitor visitor)
1984                 {
1985                         return visitor.Visit (this);
1986                 }
1987         }
1988
1989         class WildcardPattern : PatternExpression
1990         {
1991                 public WildcardPattern (Location loc)
1992                         : base (loc)
1993                 {
1994                 }
1995
1996                 protected override Expression DoResolve (ResolveContext rc)
1997                 {
1998                         eclass = ExprClass.Value;
1999                         type = rc.BuiltinTypes.Object;
2000                         return this;
2001                 }
2002
2003                 public override void Emit (EmitContext ec)
2004                 {
2005                         ec.EmitInt (1);
2006                 }
2007         }
2008
2009         class RecursivePattern : ComplexPatternExpression
2010         {
2011                 MethodGroupExpr operator_mg;
2012                 Arguments operator_args;
2013
2014                 public RecursivePattern (ATypeNameExpression typeExpresion, Arguments arguments, Location loc)
2015                         : base (typeExpresion, loc)
2016                 {
2017                         Arguments = arguments;
2018                 }
2019
2020                 public Arguments Arguments { get; private set; }
2021
2022                 protected override Expression DoResolve (ResolveContext rc)
2023                 {
2024                         type = TypeExpression.ResolveAsType (rc);
2025                         if (type == null)
2026                                 return null;
2027
2028                         var operators = MemberCache.GetUserOperator (type, Operator.OpType.Is, true);
2029                         if (operators == null) {
2030                                 Error_TypeDoesNotContainDefinition (rc, type, Operator.GetName (Operator.OpType.Is) + " operator");
2031                                 return null;
2032                         }
2033
2034                         var ops = FindMatchingOverloads (operators);
2035                         if (ops == null) {
2036                                 // TODO: better error message
2037                                 Error_TypeDoesNotContainDefinition (rc, type, Operator.GetName (Operator.OpType.Is) + " operator");
2038                                 return null;
2039                         }
2040
2041                         bool dynamic_args;
2042                         Arguments.Resolve (rc, out dynamic_args);
2043                         if (dynamic_args)
2044                                 throw new NotImplementedException ("dynamic argument");
2045
2046                         var op = FindBestOverload (rc, ops);
2047                         if (op == null) {
2048                                 // TODO: better error message
2049                                 Error_TypeDoesNotContainDefinition (rc, type, Operator.GetName (Operator.OpType.Is) + " operator");
2050                                 return null;
2051                         }
2052
2053                         var op_types = op.Parameters.Types;
2054                         operator_args = new Arguments (op_types.Length);
2055                         operator_args.Add (new Argument (new EmptyExpression (type)));
2056
2057                         for (int i = 0; i < Arguments.Count; ++i) {
2058                                 // TODO: Needs releasing optimization
2059                                 var lt = new LocalTemporary (op_types [i + 1]);
2060                                 operator_args.Add (new Argument (lt, Argument.AType.Out));
2061
2062                                 if (comparisons == null)
2063                                         comparisons = new Expression[Arguments.Count];
2064
2065                                 int arg_comp_index;
2066                                 Expression expr;
2067
2068                                 var arg = Arguments [i];
2069                                 var named = arg as NamedArgument;
2070                                 if (named != null) {
2071                                         arg_comp_index = op.Parameters.GetParameterIndexByName (named.Name) - 1;
2072                                         expr = Arguments [arg_comp_index].Expr;
2073                                 } else {
2074                                         arg_comp_index = i;
2075                                         expr = arg.Expr;
2076                                 }
2077
2078                                 comparisons [arg_comp_index] = ResolveComparison (rc, expr, lt);
2079                         }
2080
2081                         operator_mg = MethodGroupExpr.CreatePredefined (op, type, loc);
2082
2083                         eclass = ExprClass.Value;
2084                         return this;
2085                 }
2086
2087                 List<MethodSpec> FindMatchingOverloads (IList<MemberSpec> members)
2088                 {
2089                         int arg_count = Arguments.Count + 1;
2090                         List<MethodSpec> best = null;
2091                         foreach (MethodSpec method in members) {
2092                                 var pm = method.Parameters;
2093                                 if (pm.Count != arg_count)
2094                                         continue;
2095
2096                                 // TODO: Needs more thorough operator checks elsewhere to avoid doing this every time
2097                                 bool ok = true;
2098                                 for (int ii = 1; ii < pm.Count; ++ii) {
2099                                         if ((pm.FixedParameters [ii].ModFlags & Parameter.Modifier.OUT) == 0) {
2100                                                 ok = false;
2101                                                 break;
2102                                         }
2103                                 }
2104
2105                                 if (!ok)
2106                                         continue;
2107
2108                                 if (best == null)
2109                                         best = new List<MethodSpec> ();
2110
2111                                 best.Add (method);
2112                         }
2113
2114                         return best;
2115                 }
2116
2117                 MethodSpec FindBestOverload (ResolveContext rc, List<MethodSpec> methods)
2118                 {
2119                         for (int ii = 0; ii < Arguments.Count; ++ii) {
2120                                 var arg = Arguments [ii];
2121                                 var expr = arg.Expr;
2122                                 if (expr is WildcardPattern)
2123                                         continue;
2124
2125                                 var na = arg as NamedArgument;
2126                                 for (int i = 0; i < methods.Count; ++i) {
2127                                         var pd = methods [i].Parameters;
2128
2129                                         int index;
2130                                         if (na != null) {
2131                                                 index = pd.GetParameterIndexByName (na.Name);
2132                                                 if (index < 1) {
2133                                                         methods.RemoveAt (i--);
2134                                                         continue;
2135                                                 }
2136                                         } else {
2137                                                 index = ii + 1;
2138                                         }
2139
2140                                         var m = pd.Types [index];
2141                                         if (!Convert.ImplicitConversionExists (rc, expr, m))
2142                                                 methods.RemoveAt (i--);
2143                                 }
2144                         }
2145
2146                         if (methods.Count != 1)
2147                                 return null;
2148
2149                         return methods [0];
2150                 }
2151
2152                 public override void EmitBranchable (EmitContext ec, Label target, bool on_true)
2153                 {
2154                         operator_mg.EmitCall (ec, operator_args, false);
2155                         ec.Emit (OpCodes.Brfalse, target);
2156
2157                         base.EmitBranchable (ec, target, on_true);
2158                 }
2159
2160                 static Expression ResolveComparison (ResolveContext rc, Expression expr, LocalTemporary lt)
2161                 {
2162                         if (expr is WildcardPattern)
2163                                 return new EmptyExpression (expr.Type);
2164
2165                         var recursive = expr as RecursivePattern;
2166                         expr = Convert.ImplicitConversionRequired (rc, expr, lt.Type, expr.Location);
2167                         if (expr == null)
2168                                 return null;
2169
2170                         if (recursive != null) {
2171                                 recursive.SetParentInstance (lt);
2172                                 return expr;
2173                         }
2174
2175                         // TODO: Better error handling
2176                         return new Binary (Binary.Operator.Equality, lt, expr, expr.Location).Resolve (rc);
2177                 }
2178
2179                 public void SetParentInstance (Expression instance)
2180                 {
2181                         operator_args [0] = new Argument (instance);
2182                 }
2183         }
2184
2185         class PropertyPattern : ComplexPatternExpression
2186         {
2187                 LocalTemporary instance;
2188
2189                 public PropertyPattern (ATypeNameExpression typeExpresion, List<PropertyPatternMember> members, Location loc)
2190                         : base (typeExpresion, loc)
2191                 {
2192                         Members = members;
2193                 }
2194
2195                 public List<PropertyPatternMember> Members { get; private set; }
2196
2197                 protected override Expression DoResolve (ResolveContext rc)
2198                 {
2199                         type = TypeExpression.ResolveAsType (rc);
2200                         if (type == null)
2201                                 return null;
2202
2203                         comparisons = new Expression[Members.Count];
2204
2205                         // TODO: optimize when source is VariableReference, it'd save dup+pop
2206                         instance = new LocalTemporary (type);
2207
2208                         for (int i = 0; i < Members.Count; i++) {
2209                                 var lookup = Members [i];
2210
2211                                 var member = MemberLookup (rc, false, type, lookup.Name, 0, Expression.MemberLookupRestrictions.ExactArity, loc);
2212                                 if (member == null) {
2213                                         member = MemberLookup (rc, true, type, lookup.Name, 0, Expression.MemberLookupRestrictions.ExactArity, loc);
2214                                         if (member != null) {
2215                                                 Expression.ErrorIsInaccesible (rc, member.GetSignatureForError (), loc);
2216                                                 continue;
2217                                         }
2218                                 }
2219
2220                                 if (member == null) {
2221                                         Expression.Error_TypeDoesNotContainDefinition (rc, Location, Type, lookup.Name);
2222                                         continue;
2223                                 }
2224
2225                                 var pe = member as PropertyExpr;
2226                                 if (pe == null || member is FieldExpr) {
2227                                         rc.Report.Error (-2001, lookup.Location, "`{0}' is not a valid pattern member", lookup.Name);
2228                                         continue;
2229                                 }
2230
2231                                 // TODO: Obsolete checks
2232                                 // TODO: check accessibility
2233                                 if (pe != null && !pe.PropertyInfo.HasGet) {
2234                                         rc.Report.Error (-2002, lookup.Location, "Property `{0}.get' accessor is required", pe.GetSignatureForError ());
2235                                         continue;
2236                                 }
2237
2238                                 var expr = lookup.Expr.Resolve (rc);
2239                                 if (expr == null)
2240                                         continue;
2241
2242                                 var me = (MemberExpr)member;
2243                                 me.InstanceExpression = instance;
2244
2245                                 comparisons [i] = ResolveComparison (rc, expr, me);
2246                         }
2247
2248                         eclass = ExprClass.Value;
2249                         return this;
2250                 }
2251
2252                 static Expression ResolveComparison (ResolveContext rc, Expression expr, Expression instance)
2253                 {
2254                         if (expr is WildcardPattern)
2255                                 return new EmptyExpression (expr.Type);
2256
2257                         return new Is (instance, expr, expr.Location).Resolve (rc);
2258                 }
2259
2260                 public override void EmitBranchable (EmitContext ec, Label target, bool on_true)
2261                 {
2262                         instance.Store (ec);
2263
2264                         base.EmitBranchable (ec, target, on_true);
2265                 }
2266         }
2267
2268         class PropertyPatternMember
2269         {
2270                 public PropertyPatternMember (string name, Expression expr, Location loc)
2271                 {
2272                         Name = name;
2273                         Expr = expr;
2274                         Location = loc;
2275                 }
2276
2277                 public string Name { get; private set; }
2278                 public Expression Expr { get; private set; }
2279                 public Location Location { get; private set; }
2280         }
2281
2282         abstract class PatternExpression : Expression
2283         {
2284                 protected PatternExpression (Location loc)
2285                 {
2286                         this.loc = loc;
2287                 }
2288
2289                 public override Expression CreateExpressionTree (ResolveContext ec)
2290                 {
2291                         throw new NotImplementedException ();
2292                 }
2293         }
2294
2295         abstract class ComplexPatternExpression : PatternExpression
2296         {
2297                 protected Expression[] comparisons;
2298
2299                 protected ComplexPatternExpression (ATypeNameExpression typeExpresion, Location loc)
2300                         : base (loc)
2301                 {
2302                         TypeExpression = typeExpresion;
2303                 }
2304
2305                 public ATypeNameExpression TypeExpression { get; private set; }
2306
2307                 public override void Emit (EmitContext ec)
2308                 {
2309                         EmitBranchable (ec, ec.RecursivePatternLabel, false);
2310                 }
2311
2312                 public override void EmitBranchable (EmitContext ec, Label target, bool on_true)
2313                 {
2314                         if (comparisons != null) {
2315                                 foreach (var comp in comparisons) {
2316                                         comp.EmitBranchable (ec, target, false);
2317                                 }
2318                         }
2319                 }
2320         }
2321
2322         /// <summary>
2323         ///   Implementation of the `as' operator.
2324         /// </summary>
2325         public class As : Probe {
2326
2327                 public As (Expression expr, Expression probe_type, Location l)
2328                         : base (expr, probe_type, l)
2329                 {
2330                 }
2331
2332                 protected override string OperatorName {
2333                         get { return "as"; }
2334                 }
2335
2336                 public override Expression CreateExpressionTree (ResolveContext ec)
2337                 {
2338                         Arguments args = Arguments.CreateForExpressionTree (ec, null,
2339                                 expr.CreateExpressionTree (ec),
2340                                 new TypeOf (probe_type_expr, loc));
2341
2342                         return CreateExpressionFactoryCall (ec, "TypeAs", args);
2343                 }
2344
2345                 public override void Emit (EmitContext ec)
2346                 {
2347                         expr.Emit (ec);
2348
2349                         ec.Emit (OpCodes.Isinst, type);
2350
2351                         if (TypeManager.IsGenericParameter (type) || type.IsNullableType)
2352                                 ec.Emit (OpCodes.Unbox_Any, type);
2353                 }
2354
2355                 protected override Expression DoResolve (ResolveContext ec)
2356                 {
2357                         if (ResolveCommon (ec) == null)
2358                                 return null;
2359
2360                         type = probe_type_expr;
2361                         eclass = ExprClass.Value;
2362                         TypeSpec etype = expr.Type;
2363
2364                         if (!TypeSpec.IsReferenceType (type) && !type.IsNullableType) {
2365                                 if (TypeManager.IsGenericParameter (type)) {
2366                                         ec.Report.Error (413, loc,
2367                                                 "The `as' operator cannot be used with a non-reference type parameter `{0}'. Consider adding `class' or a reference type constraint",
2368                                                 probe_type_expr.GetSignatureForError ());
2369                                 } else {
2370                                         ec.Report.Error (77, loc,
2371                                                 "The `as' operator cannot be used with a non-nullable value type `{0}'",
2372                                                 type.GetSignatureForError ());
2373                                 }
2374                                 return null;
2375                         }
2376
2377                         if (expr.IsNull && type.IsNullableType) {
2378                                 return Nullable.LiftedNull.CreateFromExpression (ec, this);
2379                         }
2380
2381                         // If the compile-time type of E is dynamic, unlike the cast operator the as operator is not dynamically bound
2382                         if (etype.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
2383                                 return this;
2384                         }
2385                         
2386                         Expression e = Convert.ImplicitConversionStandard (ec, expr, type, loc);
2387                         if (e != null) {
2388                                 e = EmptyCast.Create (e, type);
2389                                 return ReducedExpression.Create (e, this).Resolve (ec);
2390                         }
2391
2392                         if (Convert.ExplicitReferenceConversionExists (etype, type)){
2393                                 if (TypeManager.IsGenericParameter (etype))
2394                                         expr = new BoxedCast (expr, etype);
2395
2396                                 return this;
2397                         }
2398
2399                         if (InflatedTypeSpec.ContainsTypeParameter (etype) || InflatedTypeSpec.ContainsTypeParameter (type)) {
2400                                 expr = new BoxedCast (expr, etype);
2401                                 return this;
2402                         }
2403
2404                         if (etype != InternalType.ErrorType) {
2405                                 ec.Report.Error (39, loc, "Cannot convert type `{0}' to `{1}' via a built-in conversion",
2406                                         etype.GetSignatureForError (), type.GetSignatureForError ());
2407                         }
2408
2409                         return null;
2410                 }
2411
2412                 public override object Accept (StructuralVisitor visitor)
2413                 {
2414                         return visitor.Visit (this);
2415                 }
2416         }
2417         
2418         //
2419         // This represents a typecast in the source language.
2420         //
2421         public class Cast : ShimExpression {
2422                 Expression target_type;
2423
2424                 public Cast (Expression cast_type, Expression expr, Location loc)
2425                         : base (expr)
2426                 {
2427                         this.target_type = cast_type;
2428                         this.loc = loc;
2429                 }
2430
2431                 public Expression TargetType {
2432                         get { return target_type; }
2433                 }
2434
2435                 protected override Expression DoResolve (ResolveContext ec)
2436                 {
2437                         expr = expr.Resolve (ec);
2438                         if (expr == null)
2439                                 return null;
2440
2441                         type = target_type.ResolveAsType (ec);
2442                         if (type == null)
2443                                 return null;
2444
2445                         if (type.IsStatic) {
2446                                 ec.Report.Error (716, loc, "Cannot convert to static type `{0}'", type.GetSignatureForError ());
2447                                 return null;
2448                         }
2449
2450                         if (type.IsPointer && !ec.IsUnsafe) {
2451                                 UnsafeError (ec, loc);
2452                         }
2453
2454                         eclass = ExprClass.Value;
2455                         
2456                         Constant c = expr as Constant;
2457                         if (c != null) {
2458                                 c = c.Reduce (ec, type);
2459                                 if (c != null)
2460                                         return c;
2461                         }
2462
2463                         var res = Convert.ExplicitConversion (ec, expr, type, loc);
2464                         if (res == expr)
2465                                 return EmptyCast.Create (res, type);
2466
2467                         return res;
2468                 }
2469                 
2470                 protected override void CloneTo (CloneContext clonectx, Expression t)
2471                 {
2472                         Cast target = (Cast) t;
2473
2474                         target.target_type = target_type.Clone (clonectx);
2475                         target.expr = expr.Clone (clonectx);
2476                 }
2477
2478                 public override object Accept (StructuralVisitor visitor)
2479                 {
2480                         return visitor.Visit (this);
2481                 }
2482         }
2483
2484         public class ImplicitCast : ShimExpression
2485         {
2486                 bool arrayAccess;
2487
2488                 public ImplicitCast (Expression expr, TypeSpec target, bool arrayAccess)
2489                         : base (expr)
2490                 {
2491                         this.loc = expr.Location;
2492                         this.type = target;
2493                         this.arrayAccess = arrayAccess;
2494                 }
2495
2496                 protected override Expression DoResolve (ResolveContext ec)
2497                 {
2498                         expr = expr.Resolve (ec);
2499                         if (expr == null)
2500                                 return null;
2501
2502                         if (arrayAccess)
2503                                 expr = ConvertExpressionToArrayIndex (ec, expr);
2504                         else
2505                                 expr = Convert.ImplicitConversionRequired (ec, expr, type, loc);
2506
2507                         return expr;
2508                 }
2509         }
2510
2511         public class DeclarationExpression : Expression, IMemoryLocation
2512         {
2513                 LocalVariableReference lvr;
2514
2515                 public DeclarationExpression (FullNamedExpression variableType, LocalVariable variable)
2516                 {
2517                         VariableType = variableType;
2518                         Variable = variable;
2519                         this.loc = variable.Location;
2520                 }
2521
2522                 public LocalVariable Variable { get; set; }
2523                 public Expression Initializer { get; set; }
2524                 public FullNamedExpression VariableType { get; set; }
2525
2526                 public void AddressOf (EmitContext ec, AddressOp mode)
2527                 {
2528                         Variable.CreateBuilder (ec);
2529
2530                         if (Initializer != null) {
2531                                 lvr.EmitAssign (ec, Initializer, false, false);
2532                         }
2533
2534                         lvr.AddressOf (ec, mode);
2535                 }
2536
2537                 protected override void CloneTo (CloneContext clonectx, Expression t)
2538                 {
2539                         var target = (DeclarationExpression) t;
2540
2541                         target.VariableType = (FullNamedExpression) VariableType.Clone (clonectx);
2542
2543                         if (Initializer != null)
2544                                 target.Initializer = Initializer.Clone (clonectx);
2545                 }
2546
2547                 public override Expression CreateExpressionTree (ResolveContext rc)
2548                 {
2549                         rc.Report.Error (8046, loc, "An expression tree cannot contain a declaration expression");
2550                         return null;
2551                 }
2552
2553                 bool DoResolveCommon (ResolveContext rc)
2554                 {
2555                         var var_expr = VariableType as VarExpr;
2556                         if (var_expr != null) {
2557                                 type = InternalType.VarOutType;
2558                         } else {
2559                                 type = VariableType.ResolveAsType (rc);
2560                                 if (type == null)
2561                                         return false;
2562                         }
2563
2564                         if (Initializer != null) {
2565                                 Initializer = Initializer.Resolve (rc);
2566
2567                                 if (var_expr != null && Initializer != null && var_expr.InferType (rc, Initializer)) {
2568                                         type = var_expr.Type;
2569                                 }
2570                         }
2571
2572                         Variable.Type = type;
2573                         lvr = new LocalVariableReference (Variable, loc);
2574
2575                         eclass = ExprClass.Variable;
2576                         return true;
2577                 }
2578
2579                 protected override Expression DoResolve (ResolveContext rc)
2580                 {
2581                         if (DoResolveCommon (rc))
2582                                 lvr.Resolve (rc);
2583
2584                         return this;
2585                 }
2586
2587                 public override Expression DoResolveLValue (ResolveContext rc, Expression right_side)
2588                 {
2589                         if (lvr == null && DoResolveCommon (rc))
2590                                 lvr.ResolveLValue (rc, right_side);
2591
2592                         return this;
2593                 }
2594
2595                 public override void Emit (EmitContext ec)
2596                 {
2597                         throw new NotImplementedException ();
2598                 }
2599         }
2600         
2601         //
2602         // C# 2.0 Default value expression
2603         //
2604         public class DefaultValueExpression : Expression
2605         {
2606                 Expression expr;
2607
2608                 public DefaultValueExpression (Expression expr, Location loc)
2609                 {
2610                         this.expr = expr;
2611                         this.loc = loc;
2612                 }
2613
2614                 public Expression Expr {
2615                         get {
2616                                 return this.expr; 
2617                         }
2618                 }
2619
2620                 public override bool IsSideEffectFree {
2621                         get {
2622                                 return true;
2623                         }
2624                 }
2625
2626                 public override bool ContainsEmitWithAwait ()
2627                 {
2628                         return false;
2629                 }
2630
2631                 public override Expression CreateExpressionTree (ResolveContext ec)
2632                 {
2633                         Arguments args = new Arguments (2);
2634                         args.Add (new Argument (this));
2635                         args.Add (new Argument (new TypeOf (type, loc)));
2636                         return CreateExpressionFactoryCall (ec, "Constant", args);
2637                 }
2638
2639                 protected override Expression DoResolve (ResolveContext ec)
2640                 {
2641                         type = expr.ResolveAsType (ec);
2642                         if (type == null)
2643                                 return null;
2644
2645                         if (type.IsStatic) {
2646                                 ec.Report.Error (-244, loc, "The `default value' operator cannot be applied to an operand of a static type");
2647                         }
2648
2649                         if (type.IsPointer)
2650                                 return new NullLiteral (Location).ConvertImplicitly (type);
2651
2652                         if (TypeSpec.IsReferenceType (type))
2653                                 return new NullConstant (type, loc);
2654
2655                         Constant c = New.Constantify (type, expr.Location);
2656                         if (c != null)
2657                                 return c;
2658
2659                         eclass = ExprClass.Variable;
2660                         return this;
2661                 }
2662
2663                 public override void Emit (EmitContext ec)
2664                 {
2665                         LocalTemporary temp_storage = new LocalTemporary(type);
2666
2667                         temp_storage.AddressOf(ec, AddressOp.LoadStore);
2668                         ec.Emit(OpCodes.Initobj, type);
2669                         temp_storage.Emit(ec);
2670                         temp_storage.Release (ec);
2671                 }
2672
2673 #if !STATIC
2674                 public override SLE.Expression MakeExpression (BuilderContext ctx)
2675                 {
2676                         return SLE.Expression.Default (type.GetMetaInfo ());
2677                 }
2678 #endif
2679
2680                 protected override void CloneTo (CloneContext clonectx, Expression t)
2681                 {
2682                         DefaultValueExpression target = (DefaultValueExpression) t;
2683                         
2684                         target.expr = expr.Clone (clonectx);
2685                 }
2686                 
2687                 public override object Accept (StructuralVisitor visitor)
2688                 {
2689                         return visitor.Visit (this);
2690                 }
2691         }
2692
2693         /// <summary>
2694         ///   Binary operators
2695         /// </summary>
2696         public class Binary : Expression, IDynamicBinder
2697         {
2698                 public class PredefinedOperator
2699                 {
2700                         protected readonly TypeSpec left;
2701                         protected readonly TypeSpec right;
2702                         protected readonly TypeSpec left_unwrap;
2703                         protected readonly TypeSpec right_unwrap;
2704                         public readonly Operator OperatorsMask;
2705                         public TypeSpec ReturnType;
2706
2707                         public PredefinedOperator (TypeSpec ltype, TypeSpec rtype, Operator op_mask)
2708                                 : this (ltype, rtype, op_mask, ltype)
2709                         {
2710                         }
2711
2712                         public PredefinedOperator (TypeSpec type, Operator op_mask, TypeSpec return_type)
2713                                 : this (type, type, op_mask, return_type)
2714                         {
2715                         }
2716
2717                         public PredefinedOperator (TypeSpec type, Operator op_mask)
2718                                 : this (type, type, op_mask, type)
2719                         {
2720                         }
2721
2722                         public PredefinedOperator (TypeSpec ltype, TypeSpec rtype, Operator op_mask, TypeSpec return_type)
2723                         {
2724                                 if ((op_mask & Operator.ValuesOnlyMask) != 0)
2725                                         throw new InternalErrorException ("Only masked values can be used");
2726
2727                                 if ((op_mask & Operator.NullableMask) != 0) {
2728                                         left_unwrap = Nullable.NullableInfo.GetUnderlyingType (ltype);
2729                                         right_unwrap = Nullable.NullableInfo.GetUnderlyingType (rtype);
2730                                 } else {
2731                                         left_unwrap = ltype;
2732                                         right_unwrap = rtype;
2733                                 }
2734
2735                                 this.left = ltype;
2736                                 this.right = rtype;
2737                                 this.OperatorsMask = op_mask;
2738                                 this.ReturnType = return_type;
2739                         }
2740
2741                         public bool IsLifted {
2742                                 get {
2743                                         return (OperatorsMask & Operator.NullableMask) != 0;
2744                                 }
2745                         }
2746
2747                         public virtual Expression ConvertResult (ResolveContext rc, Binary b)
2748                         {
2749                                 Constant c;
2750
2751                                 var left_expr = b.left;
2752                                 var right_expr = b.right;
2753
2754                                 b.type = ReturnType;
2755
2756                                 if (IsLifted) {
2757                                         if (rc.HasSet (ResolveContext.Options.ExpressionTreeConversion)) {
2758                                                 b.left = Convert.ImplicitConversion (rc, b.left, left, b.left.Location);
2759                                                 b.right = Convert.ImplicitConversion (rc, b.right, right, b.right.Location);
2760                                         }
2761
2762                                         if (right_expr.IsNull) {
2763                                                 if ((b.oper & Operator.EqualityMask) != 0) {
2764                                                         if (!left_expr.Type.IsNullableType && BuiltinTypeSpec.IsPrimitiveType (left_expr.Type))
2765                                                                 return b.CreateLiftedValueTypeResult (rc, left_expr.Type);
2766                                                 } else if ((b.oper & Operator.BitwiseMask) != 0) {
2767                                                         if (left_unwrap.BuiltinType != BuiltinTypeSpec.Type.Bool)
2768                                                                 return Nullable.LiftedNull.CreateFromExpression (rc, b);
2769                                                 } else {
2770                                                         b.left = Convert.ImplicitConversion (rc, b.left, left, b.left.Location);
2771                                                         b.right = Convert.ImplicitConversion (rc, b.right, right, b.right.Location);
2772
2773                                                         if ((b.Oper & (Operator.ArithmeticMask | Operator.ShiftMask)) != 0)
2774                                                                 return Nullable.LiftedNull.CreateFromExpression (rc, b);
2775
2776                                                         return b.CreateLiftedValueTypeResult (rc, left);
2777                                                 }
2778                                         } else if (left_expr.IsNull) {
2779                                                 if ((b.oper & Operator.EqualityMask) != 0) {
2780                                                         if (!right_expr.Type.IsNullableType && BuiltinTypeSpec.IsPrimitiveType (right_expr.Type))
2781                                                                 return b.CreateLiftedValueTypeResult (rc, right_expr.Type);
2782                                                 } else if ((b.oper & Operator.BitwiseMask) != 0) {
2783                                                         if (right_unwrap.BuiltinType != BuiltinTypeSpec.Type.Bool)
2784                                                                 return Nullable.LiftedNull.CreateFromExpression (rc, b);
2785                                                 } else {
2786                                                         b.left = Convert.ImplicitConversion (rc, b.left, left, b.left.Location);
2787                                                         b.right = Convert.ImplicitConversion (rc, b.right, right, b.right.Location);
2788
2789                                                         if ((b.Oper & (Operator.ArithmeticMask | Operator.ShiftMask)) != 0)
2790                                                                 return Nullable.LiftedNull.CreateFromExpression (rc, b);
2791
2792                                                         return b.CreateLiftedValueTypeResult (rc, right);
2793                                                 }
2794                                         }
2795                                 }
2796
2797                                 //
2798                                 // A user operators does not support multiple user conversions, but decimal type
2799                                 // is considered to be predefined type therefore we apply predefined operators rules
2800                                 // and then look for decimal user-operator implementation
2801                                 //
2802                                 if (left.BuiltinType == BuiltinTypeSpec.Type.Decimal) {
2803                                         b.left = Convert.ImplicitConversion (rc, b.left, left, b.left.Location);
2804                                         b.right = Convert.ImplicitConversion (rc, b.right, right, b.right.Location);
2805
2806                                         return b.ResolveUserOperator (rc, b.left, b.right);
2807                                 }
2808
2809                                 c = right_expr as Constant;
2810                                 if (c != null) {
2811                                         if (c.IsDefaultValue) {
2812                                                 //
2813                                                 // Optimizes
2814                                                 // 
2815                                                 // (expr + 0) to expr
2816                                                 // (expr - 0) to expr
2817                                                 // (bool? | false) to bool?
2818                                                 //
2819                                                 if (b.oper == Operator.Addition || b.oper == Operator.Subtraction ||
2820                                                         (b.oper == Operator.BitwiseOr && left_unwrap.BuiltinType == BuiltinTypeSpec.Type.Bool && c is BoolConstant)) {
2821                                                         b.left = Convert.ImplicitConversion (rc, b.left, left, b.left.Location);
2822                                                         return ReducedExpression.Create (b.left, b).Resolve (rc);
2823                                                 }
2824
2825                                                 //
2826                                                 // Optimizes (value &/&& 0) to 0
2827                                                 //
2828                                                 if ((b.oper == Operator.BitwiseAnd || b.oper == Operator.LogicalAnd) && !IsLifted) {
2829                                                         Constant side_effect = new SideEffectConstant (c, b.left, c.Location);
2830                                                         return ReducedExpression.Create (side_effect, b);
2831                                                 }
2832                                         } else {
2833                                                 //
2834                                                 // Optimizes (bool? & true) to bool?
2835                                                 //
2836                                                 if (IsLifted && left_unwrap.BuiltinType == BuiltinTypeSpec.Type.Bool && b.oper == Operator.BitwiseAnd) {
2837                                                         return ReducedExpression.Create (b.left, b).Resolve (rc);
2838                                                 }
2839                                         }
2840
2841                                         if ((b.oper == Operator.Multiply || b.oper == Operator.Division) && c.IsOneInteger)
2842                                                 return ReducedExpression.Create (b.left, b).Resolve (rc);
2843
2844                                         if ((b.oper & Operator.ShiftMask) != 0 && c is IntConstant) {
2845                                                 b.right = new IntConstant (rc.BuiltinTypes, ((IntConstant) c).Value & GetShiftMask (left_unwrap), b.right.Location);
2846                                         }
2847                                 }
2848
2849                                 c = b.left as Constant;
2850                                 if (c != null) {
2851                                         if (c.IsDefaultValue) {
2852                                                 //
2853                                                 // Optimizes
2854                                                 // 
2855                                                 // (0 + expr) to expr
2856                                                 // (false | bool?) to bool?
2857                                                 //
2858                                                 if (b.oper == Operator.Addition ||
2859                                                         (b.oper == Operator.BitwiseOr && right_unwrap.BuiltinType == BuiltinTypeSpec.Type.Bool && c is BoolConstant)) {
2860                                                         b.right = Convert.ImplicitConversion (rc, b.right, right, b.right.Location);
2861                                                         return ReducedExpression.Create (b.right, b).Resolve (rc);
2862                                                 }
2863
2864                                                 //
2865                                                 // Optimizes (false && expr) to false
2866                                                 //
2867                                                 if (b.oper == Operator.LogicalAnd && c.Type.BuiltinType == BuiltinTypeSpec.Type.Bool) {
2868                                                         // No rhs side-effects
2869                                                         Expression.Warning_UnreachableExpression (rc, b.right.StartLocation);
2870                                                         return ReducedExpression.Create (c, b);
2871                                                 }
2872
2873                                                 //
2874                                                 // Optimizes (0 & value) to 0
2875                                                 //
2876                                                 if (b.oper == Operator.BitwiseAnd && !IsLifted) {
2877                                                         Constant side_effect = new SideEffectConstant (c, b.right, c.Location);
2878                                                         return ReducedExpression.Create (side_effect, b);
2879                                                 }
2880                                         } else {
2881                                                 //
2882                                                 // Optimizes (true & bool?) to bool?
2883                                                 //
2884                                                 if (IsLifted && left_unwrap.BuiltinType == BuiltinTypeSpec.Type.Bool && b.oper == Operator.BitwiseAnd) {
2885                                                         return ReducedExpression.Create (b.right, b).Resolve (rc);
2886                                                 }
2887
2888                                                 //
2889                                                 // Optimizes (true || expr) to true
2890                                                 //
2891                                                 if (b.oper == Operator.LogicalOr && c.Type.BuiltinType == BuiltinTypeSpec.Type.Bool) {
2892                                                         // No rhs side-effects
2893                                                         Expression.Warning_UnreachableExpression (rc, b.right.StartLocation);
2894                                                         return ReducedExpression.Create (c, b);
2895                                                 }
2896                                         }
2897
2898                                         if (b.oper == Operator.Multiply && c.IsOneInteger)
2899                                                 return ReducedExpression.Create (b.right, b).Resolve (rc);
2900                                 }
2901
2902                                 if (IsLifted) {
2903                                         var lifted = new Nullable.LiftedBinaryOperator (b);
2904
2905                                         TypeSpec ltype, rtype;
2906                                         if (b.left.Type.IsNullableType) {
2907                                                 lifted.UnwrapLeft = new Nullable.Unwrap (b.left);
2908                                                 ltype = left_unwrap;
2909                                         } else {
2910                                                 ltype = left;
2911                                         }
2912
2913                                         if (b.right.Type.IsNullableType) {
2914                                                 lifted.UnwrapRight = new Nullable.Unwrap (b.right);
2915                                                 rtype = right_unwrap;
2916                                         } else {
2917                                                 rtype = right;
2918                                         }
2919
2920                                         lifted.Left = b.left.IsNull ?
2921                                                 Nullable.LiftedNull.Create (ltype, b.left.Location) :
2922                                                 Convert.ImplicitConversion (rc, lifted.UnwrapLeft ?? b.left, ltype, b.left.Location);
2923
2924                                         lifted.Right = b.right.IsNull ?
2925                                                 Nullable.LiftedNull.Create (rtype, b.right.Location) :
2926                                                 Convert.ImplicitConversion (rc, lifted.UnwrapRight ?? b.right, rtype, b.right.Location);
2927
2928                                         return lifted.Resolve (rc);
2929                                 }
2930
2931                                 b.left = Convert.ImplicitConversion (rc, b.left, left, b.left.Location);
2932                                 b.right = Convert.ImplicitConversion (rc, b.right, right, b.right.Location);
2933
2934                                 return b;
2935                         }
2936
2937                         public bool IsPrimitiveApplicable (TypeSpec ltype, TypeSpec rtype)
2938                         {
2939                                 //
2940                                 // We are dealing with primitive types only
2941                                 //
2942                                 return left == ltype && ltype == rtype;
2943                         }
2944
2945                         public virtual bool IsApplicable (ResolveContext ec, Expression lexpr, Expression rexpr)
2946                         {
2947                                 // Quick path
2948                                 if (left == lexpr.Type && right == rexpr.Type)
2949                                         return true;
2950
2951                                 return Convert.ImplicitConversionExists (ec, lexpr, left) &&
2952                                         Convert.ImplicitConversionExists (ec, rexpr, right);
2953                         }
2954
2955                         public PredefinedOperator ResolveBetterOperator (ResolveContext ec, PredefinedOperator best_operator)
2956                         {
2957                                 if ((OperatorsMask & Operator.DecomposedMask) != 0)
2958                                         return best_operator;
2959
2960                                 if ((best_operator.OperatorsMask & Operator.DecomposedMask) != 0)
2961                                         return this;
2962
2963                                 int result = 0;
2964                                 if (left != null && best_operator.left != null) {
2965                                         result = OverloadResolver.BetterTypeConversion (ec, best_operator.left_unwrap, left_unwrap);
2966                                 }
2967
2968                                 //
2969                                 // When second argument is same as the first one, the result is same
2970                                 //
2971                                 if (right != null && (left != right || best_operator.left != best_operator.right)) {
2972                                         result |= OverloadResolver.BetterTypeConversion (ec, best_operator.right_unwrap, right_unwrap);
2973                                 }
2974
2975                                 if (result == 0 || result > 2)
2976                                         return null;
2977
2978                                 return result == 1 ? best_operator : this;
2979                         }
2980                 }
2981
2982                 sealed class PredefinedStringOperator : PredefinedOperator
2983                 {
2984                         public PredefinedStringOperator (TypeSpec type, Operator op_mask, TypeSpec retType)
2985                                 : base (type, type, op_mask, retType)
2986                         {
2987                         }
2988
2989                         public PredefinedStringOperator (TypeSpec ltype, TypeSpec rtype, Operator op_mask, TypeSpec retType)
2990                                 : base (ltype, rtype, op_mask, retType)
2991                         {
2992                         }
2993
2994                         public override Expression ConvertResult (ResolveContext ec, Binary b)
2995                         {
2996                                 //
2997                                 // Use original expression for nullable arguments
2998                                 //
2999                                 Nullable.Unwrap unwrap = b.left as Nullable.Unwrap;
3000                                 if (unwrap != null)
3001                                         b.left = unwrap.Original;
3002
3003                                 unwrap = b.right as Nullable.Unwrap;
3004                                 if (unwrap != null)
3005                                         b.right = unwrap.Original;
3006
3007                                 b.left = Convert.ImplicitConversion (ec, b.left, left, b.left.Location);
3008                                 b.right = Convert.ImplicitConversion (ec, b.right, right, b.right.Location);
3009
3010                                 //
3011                                 // Start a new concat expression using converted expression
3012                                 //
3013                                 return StringConcat.Create (ec, b.left, b.right, b.loc);
3014                         }
3015                 }
3016
3017                 sealed class PredefinedEqualityOperator : PredefinedOperator
3018                 {
3019                         MethodSpec equal_method, inequal_method;
3020
3021                         public PredefinedEqualityOperator (TypeSpec arg, TypeSpec retType)
3022                                 : base (arg, arg, Operator.EqualityMask, retType)
3023                         {
3024                         }
3025
3026                         public override Expression ConvertResult (ResolveContext ec, Binary b)
3027                         {
3028                                 b.type = ReturnType;
3029
3030                                 b.left = Convert.ImplicitConversion (ec, b.left, left, b.left.Location);
3031                                 b.right = Convert.ImplicitConversion (ec, b.right, right, b.right.Location);
3032
3033                                 Arguments args = new Arguments (2);
3034                                 args.Add (new Argument (b.left));
3035                                 args.Add (new Argument (b.right));
3036
3037                                 MethodSpec method;
3038                                 if (b.oper == Operator.Equality) {
3039                                         if (equal_method == null) {
3040                                                 if (left.BuiltinType == BuiltinTypeSpec.Type.String)
3041                                                         equal_method = ec.Module.PredefinedMembers.StringEqual.Resolve (b.loc);
3042                                                 else if (left.BuiltinType == BuiltinTypeSpec.Type.Delegate)
3043                                                         equal_method = ec.Module.PredefinedMembers.DelegateEqual.Resolve (b.loc);
3044                                                 else
3045                                                         throw new NotImplementedException (left.GetSignatureForError ());
3046                                         }
3047
3048                                         method = equal_method;
3049                                 } else {
3050                                         if (inequal_method == null) {
3051                                                 if (left.BuiltinType == BuiltinTypeSpec.Type.String)
3052                                                         inequal_method = ec.Module.PredefinedMembers.StringInequal.Resolve (b.loc);
3053                                                 else if (left.BuiltinType == BuiltinTypeSpec.Type.Delegate)
3054                                                         inequal_method = ec.Module.PredefinedMembers.DelegateInequal.Resolve (b.loc);
3055                                                 else
3056                                                         throw new NotImplementedException (left.GetSignatureForError ());
3057                                         }
3058
3059                                         method = inequal_method;
3060                                 }
3061
3062                                 return new UserOperatorCall (method, args, b.CreateExpressionTree, b.loc);
3063                         }
3064                 }
3065
3066                 class PredefinedPointerOperator : PredefinedOperator
3067                 {
3068                         public PredefinedPointerOperator (TypeSpec ltype, TypeSpec rtype, Operator op_mask)
3069                                 : base (ltype, rtype, op_mask)
3070                         {
3071                         }
3072
3073                         public PredefinedPointerOperator (TypeSpec ltype, TypeSpec rtype, Operator op_mask, TypeSpec retType)
3074                                 : base (ltype, rtype, op_mask, retType)
3075                         {
3076                         }
3077
3078                         public PredefinedPointerOperator (TypeSpec type, Operator op_mask, TypeSpec return_type)
3079                                 : base (type, op_mask, return_type)
3080                         {
3081                         }
3082
3083                         public override bool IsApplicable (ResolveContext ec, Expression lexpr, Expression rexpr)
3084                         {
3085                                 if (left == null) {
3086                                         if (!lexpr.Type.IsPointer)
3087                                                 return false;
3088                                 } else {
3089                                         if (!Convert.ImplicitConversionExists (ec, lexpr, left))
3090                                                 return false;
3091                                 }
3092
3093                                 if (right == null) {
3094                                         if (!rexpr.Type.IsPointer)
3095                                                 return false;
3096                                 } else {
3097                                         if (!Convert.ImplicitConversionExists (ec, rexpr, right))
3098                                                 return false;
3099                                 }
3100
3101                                 return true;
3102                         }
3103
3104                         public override Expression ConvertResult (ResolveContext ec, Binary b)
3105                         {
3106                                 if (left != null) {
3107                                         b.left = EmptyCast.Create (b.left, left);
3108                                 } else if (right != null) {
3109                                         b.right = EmptyCast.Create (b.right, right);
3110                                 }
3111
3112                                 TypeSpec r_type = ReturnType;
3113                                 Expression left_arg, right_arg;
3114                                 if (r_type == null) {
3115                                         if (left == null) {
3116                                                 left_arg = b.left;
3117                                                 right_arg = b.right;
3118                                                 r_type = b.left.Type;
3119                                         } else {
3120                                                 left_arg = b.right;
3121                                                 right_arg = b.left;
3122                                                 r_type = b.right.Type;
3123                                         }
3124                                 } else {
3125                                         left_arg = b.left;
3126                                         right_arg = b.right;
3127                                 }
3128
3129                                 return new PointerArithmetic (b.oper, left_arg, right_arg, r_type, b.loc).Resolve (ec);
3130                         }
3131                 }
3132
3133                 [Flags]
3134                 public enum Operator {
3135                         Multiply        = 0 | ArithmeticMask,
3136                         Division        = 1 | ArithmeticMask,
3137                         Modulus         = 2 | ArithmeticMask,
3138                         Addition        = 3 | ArithmeticMask | AdditionMask,
3139                         Subtraction = 4 | ArithmeticMask | SubtractionMask,
3140
3141                         LeftShift       = 5 | ShiftMask,
3142                         RightShift      = 6 | ShiftMask,
3143
3144                         LessThan        = 7 | ComparisonMask | RelationalMask,
3145                         GreaterThan     = 8 | ComparisonMask | RelationalMask,
3146                         LessThanOrEqual         = 9 | ComparisonMask | RelationalMask,
3147                         GreaterThanOrEqual      = 10 | ComparisonMask | RelationalMask,
3148                         Equality        = 11 | ComparisonMask | EqualityMask,
3149                         Inequality      = 12 | ComparisonMask | EqualityMask,
3150
3151                         BitwiseAnd      = 13 | BitwiseMask,
3152                         ExclusiveOr     = 14 | BitwiseMask,
3153                         BitwiseOr       = 15 | BitwiseMask,
3154
3155                         LogicalAnd      = 16 | LogicalMask,
3156                         LogicalOr       = 17 | LogicalMask,
3157
3158                         //
3159                         // Operator masks
3160                         //
3161                         ValuesOnlyMask  = ArithmeticMask - 1,
3162                         ArithmeticMask  = 1 << 5,
3163                         ShiftMask               = 1 << 6,
3164                         ComparisonMask  = 1 << 7,
3165                         EqualityMask    = 1 << 8,
3166                         BitwiseMask             = 1 << 9,
3167                         LogicalMask             = 1 << 10,
3168                         AdditionMask    = 1 << 11,
3169                         SubtractionMask = 1 << 12,
3170                         RelationalMask  = 1 << 13,
3171
3172                         DecomposedMask  = 1 << 19,
3173                         NullableMask    = 1 << 20
3174                 }
3175
3176                 [Flags]
3177                 public enum State : byte
3178                 {
3179                         None = 0,
3180                         Compound = 1 << 1,
3181                         UserOperatorsExcluded = 1 << 2
3182                 }
3183
3184                 readonly Operator oper;
3185                 Expression left, right;
3186                 State state;
3187                 ConvCast.Mode enum_conversion;
3188
3189                 public Binary (Operator oper, Expression left, Expression right, bool isCompound)
3190                         : this (oper, left, right, State.Compound)
3191                 {
3192                 }
3193
3194                 public Binary (Operator oper, Expression left, Expression right, State state)
3195                         : this (oper, left, right)
3196                 {
3197                         this.state = state;
3198                 }
3199
3200                 public Binary (Operator oper, Expression left, Expression right)
3201                         : this (oper, left, right, left.Location)
3202                 {
3203                 }
3204
3205                 public Binary (Operator oper, Expression left, Expression right, Location loc)
3206                 {
3207                         this.oper = oper;
3208                         this.left = left;
3209                         this.right = right;
3210                         this.loc = loc;
3211                 }
3212
3213                 #region Properties
3214
3215                 public bool IsCompound {
3216                         get {
3217                                 return (state & State.Compound) != 0;
3218                         }
3219                 }
3220
3221                 public Operator Oper {
3222                         get {
3223                                 return oper;
3224                         }
3225                 }
3226
3227                 public Expression Left {
3228                         get {
3229                                 return this.left;
3230                         }
3231                 }
3232
3233                 public Expression Right {
3234                         get {
3235                                 return this.right;
3236                         }
3237                 }
3238
3239                 public override Location StartLocation {
3240                         get {
3241                                 return left.StartLocation;
3242                         }
3243                 }
3244
3245                 #endregion
3246
3247                 /// <summary>
3248                 ///   Returns a stringified representation of the Operator
3249                 /// </summary>
3250                 string OperName (Operator oper)
3251                 {
3252                         string s;
3253                         switch (oper){
3254                         case Operator.Multiply:
3255                                 s = "*";
3256                                 break;
3257                         case Operator.Division:
3258                                 s = "/";
3259                                 break;
3260                         case Operator.Modulus:
3261                                 s = "%";
3262                                 break;
3263                         case Operator.Addition:
3264                                 s = "+";
3265                                 break;
3266                         case Operator.Subtraction:
3267                                 s = "-";
3268                                 break;
3269                         case Operator.LeftShift:
3270                                 s = "<<";
3271                                 break;
3272                         case Operator.RightShift:
3273                                 s = ">>";
3274                                 break;
3275                         case Operator.LessThan:
3276                                 s = "<";
3277                                 break;
3278                         case Operator.GreaterThan:
3279                                 s = ">";
3280                                 break;
3281                         case Operator.LessThanOrEqual:
3282                                 s = "<=";
3283                                 break;
3284                         case Operator.GreaterThanOrEqual:
3285                                 s = ">=";
3286                                 break;
3287                         case Operator.Equality:
3288                                 s = "==";
3289                                 break;
3290                         case Operator.Inequality:
3291                                 s = "!=";
3292                                 break;
3293                         case Operator.BitwiseAnd:
3294                                 s = "&";
3295                                 break;
3296                         case Operator.BitwiseOr:
3297                                 s = "|";
3298                                 break;
3299                         case Operator.ExclusiveOr:
3300                                 s = "^";
3301                                 break;
3302                         case Operator.LogicalOr:
3303                                 s = "||";
3304                                 break;
3305                         case Operator.LogicalAnd:
3306                                 s = "&&";
3307                                 break;
3308                         default:
3309                                 s = oper.ToString ();
3310                                 break;
3311                         }
3312
3313                         if (IsCompound)
3314                                 return s + "=";
3315
3316                         return s;
3317                 }
3318
3319                 public static void Error_OperatorCannotBeApplied (ResolveContext ec, Expression left, Expression right, Operator oper, Location loc)
3320                 {
3321                         new Binary (oper, left, right).Error_OperatorCannotBeApplied (ec, left, right);
3322                 }
3323
3324                 public static void Error_OperatorCannotBeApplied (ResolveContext ec, Expression left, Expression right, string oper, Location loc)
3325                 {
3326                         if (left.Type == InternalType.ErrorType || right.Type == InternalType.ErrorType)
3327                                 return;
3328
3329                         string l, r;
3330                         l = left.Type.GetSignatureForError ();
3331                         r = right.Type.GetSignatureForError ();
3332
3333                         ec.Report.Error (19, loc, "Operator `{0}' cannot be applied to operands of type `{1}' and `{2}'",
3334                                 oper, l, r);
3335                 }
3336                 
3337                 void Error_OperatorCannotBeApplied (ResolveContext ec, Expression left, Expression right)
3338                 {
3339                         Error_OperatorCannotBeApplied (ec, left, right, OperName (oper), loc);
3340                 }
3341
3342                 public override void FlowAnalysis (FlowAnalysisContext fc)
3343                 {
3344                         //
3345                         // Optimized version when on-true/on-false data are not needed
3346                         //
3347                         if ((oper & Operator.LogicalMask) == 0) {
3348                                 left.FlowAnalysis (fc);
3349                                 right.FlowAnalysis (fc);
3350                                 return;
3351                         }
3352
3353                         left.FlowAnalysisConditional (fc);
3354                         var left_fc_ontrue = fc.DefiniteAssignmentOnTrue;
3355                         var left_fc_onfalse = fc.DefiniteAssignmentOnFalse;
3356
3357                         fc.DefiniteAssignmentOnTrue = fc.DefiniteAssignmentOnFalse = fc.DefiniteAssignment = new DefiniteAssignmentBitSet (
3358                                 oper == Operator.LogicalOr ? left_fc_onfalse : left_fc_ontrue);
3359                         right.FlowAnalysisConditional (fc);
3360
3361                         if (oper == Operator.LogicalOr)
3362                                 fc.DefiniteAssignment = (left_fc_onfalse | (fc.DefiniteAssignmentOnFalse & fc.DefiniteAssignmentOnTrue)) & left_fc_ontrue;
3363                         else
3364                                 fc.DefiniteAssignment = (left_fc_ontrue | (fc.DefiniteAssignmentOnFalse & fc.DefiniteAssignmentOnTrue)) & left_fc_onfalse;
3365                 }
3366
3367                 public override void FlowAnalysisConditional (FlowAnalysisContext fc)
3368                 {
3369                         if ((oper & Operator.LogicalMask) == 0) {
3370                                 base.FlowAnalysisConditional (fc);
3371                                 return;
3372                         }
3373
3374                         left.FlowAnalysisConditional (fc);
3375                         var left_fc_ontrue = fc.DefiniteAssignmentOnTrue;
3376                         var left_fc_onfalse = fc.DefiniteAssignmentOnFalse;
3377
3378                         fc.DefiniteAssignmentOnTrue = fc.DefiniteAssignmentOnFalse = fc.DefiniteAssignment = new DefiniteAssignmentBitSet (
3379                                 oper == Operator.LogicalOr ? left_fc_onfalse : left_fc_ontrue);
3380                         right.FlowAnalysisConditional (fc);
3381
3382                         var lc = left as Constant;
3383                         if (oper == Operator.LogicalOr) {
3384                                 fc.DefiniteAssignmentOnFalse = left_fc_onfalse | fc.DefiniteAssignmentOnFalse;
3385                                 if (lc != null && lc.IsDefaultValue)
3386                                         fc.DefiniteAssignmentOnTrue = fc.DefiniteAssignmentOnFalse;
3387                                 else
3388                                         fc.DefiniteAssignmentOnTrue = new DefiniteAssignmentBitSet (left_fc_ontrue & (left_fc_onfalse | fc.DefiniteAssignmentOnTrue));
3389                         } else {
3390                                 fc.DefiniteAssignmentOnTrue = left_fc_ontrue | fc.DefiniteAssignmentOnTrue;
3391                                 if (lc != null && !lc.IsDefaultValue)
3392                                         fc.DefiniteAssignmentOnFalse = fc.DefiniteAssignmentOnTrue;
3393                                 else
3394                                         fc.DefiniteAssignmentOnFalse = new DefiniteAssignmentBitSet ((left_fc_ontrue | fc.DefiniteAssignmentOnFalse) & left_fc_onfalse);
3395                         }
3396                 }
3397
3398                 //
3399                 // Converts operator to System.Linq.Expressions.ExpressionType enum name
3400                 //
3401                 string GetOperatorExpressionTypeName ()
3402                 {
3403                         switch (oper) {
3404                         case Operator.Addition:
3405                                 return IsCompound ? "AddAssign" : "Add";
3406                         case Operator.BitwiseAnd:
3407                                 return IsCompound ? "AndAssign" : "And";
3408                         case Operator.BitwiseOr:
3409                                 return IsCompound ? "OrAssign" : "Or";
3410                         case Operator.Division:
3411                                 return IsCompound ? "DivideAssign" : "Divide";
3412                         case Operator.ExclusiveOr:
3413                                 return IsCompound ? "ExclusiveOrAssign" : "ExclusiveOr";
3414                         case Operator.Equality:
3415                                 return "Equal";
3416                         case Operator.GreaterThan:
3417                                 return "GreaterThan";
3418                         case Operator.GreaterThanOrEqual:
3419                                 return "GreaterThanOrEqual";
3420                         case Operator.Inequality:
3421                                 return "NotEqual";
3422                         case Operator.LeftShift:
3423                                 return IsCompound ? "LeftShiftAssign" : "LeftShift";
3424                         case Operator.LessThan:
3425                                 return "LessThan";
3426                         case Operator.LessThanOrEqual:
3427                                 return "LessThanOrEqual";
3428                         case Operator.LogicalAnd:
3429                                 return "And";
3430                         case Operator.LogicalOr:
3431                                 return "Or";
3432                         case Operator.Modulus:
3433                                 return IsCompound ? "ModuloAssign" : "Modulo";
3434                         case Operator.Multiply:
3435                                 return IsCompound ? "MultiplyAssign" : "Multiply";
3436                         case Operator.RightShift:
3437                                 return IsCompound ? "RightShiftAssign" : "RightShift";
3438                         case Operator.Subtraction:
3439                                 return IsCompound ? "SubtractAssign" : "Subtract";
3440                         default:
3441                                 throw new NotImplementedException ("Unknown expression type operator " + oper.ToString ());
3442                         }
3443                 }
3444
3445                 static CSharp.Operator.OpType ConvertBinaryToUserOperator (Operator op)
3446                 {
3447                         switch (op) {
3448                         case Operator.Addition:
3449                                 return CSharp.Operator.OpType.Addition;
3450                         case Operator.BitwiseAnd:
3451                         case Operator.LogicalAnd:
3452                                 return CSharp.Operator.OpType.BitwiseAnd;
3453                         case Operator.BitwiseOr:
3454                         case Operator.LogicalOr:
3455                                 return CSharp.Operator.OpType.BitwiseOr;
3456                         case Operator.Division:
3457                                 return CSharp.Operator.OpType.Division;
3458                         case Operator.Equality:
3459                                 return CSharp.Operator.OpType.Equality;
3460                         case Operator.ExclusiveOr:
3461                                 return CSharp.Operator.OpType.ExclusiveOr;
3462                         case Operator.GreaterThan:
3463                                 return CSharp.Operator.OpType.GreaterThan;
3464                         case Operator.GreaterThanOrEqual:
3465                                 return CSharp.Operator.OpType.GreaterThanOrEqual;
3466                         case Operator.Inequality:
3467                                 return CSharp.Operator.OpType.Inequality;
3468                         case Operator.LeftShift:
3469                                 return CSharp.Operator.OpType.LeftShift;
3470                         case Operator.LessThan:
3471                                 return CSharp.Operator.OpType.LessThan;
3472                         case Operator.LessThanOrEqual:
3473                                 return CSharp.Operator.OpType.LessThanOrEqual;
3474                         case Operator.Modulus:
3475                                 return CSharp.Operator.OpType.Modulus;
3476                         case Operator.Multiply:
3477                                 return CSharp.Operator.OpType.Multiply;
3478                         case Operator.RightShift:
3479                                 return CSharp.Operator.OpType.RightShift;
3480                         case Operator.Subtraction:
3481                                 return CSharp.Operator.OpType.Subtraction;
3482                         default:
3483                                 throw new InternalErrorException (op.ToString ());
3484                         }
3485                 }
3486
3487                 public override bool ContainsEmitWithAwait ()
3488                 {
3489                         return left.ContainsEmitWithAwait () || right.ContainsEmitWithAwait ();
3490                 }
3491
3492                 public static void EmitOperatorOpcode (EmitContext ec, Operator oper, TypeSpec l, Expression right)
3493                 {
3494                         OpCode opcode;
3495
3496                         switch (oper){
3497                         case Operator.Multiply:
3498                                 if (ec.HasSet (EmitContext.Options.CheckedScope)) {
3499                                         if (l.BuiltinType == BuiltinTypeSpec.Type.Int || l.BuiltinType == BuiltinTypeSpec.Type.Long)
3500                                                 opcode = OpCodes.Mul_Ovf;
3501                                         else if (!IsFloat (l))
3502                                                 opcode = OpCodes.Mul_Ovf_Un;
3503                                         else
3504                                                 opcode = OpCodes.Mul;
3505                                 } else
3506                                         opcode = OpCodes.Mul;
3507                                 
3508                                 break;
3509                                 
3510                         case Operator.Division:
3511                                 if (IsUnsigned (l))
3512                                         opcode = OpCodes.Div_Un;
3513                                 else
3514                                         opcode = OpCodes.Div;
3515                                 break;
3516                                 
3517                         case Operator.Modulus:
3518                                 if (IsUnsigned (l))
3519                                         opcode = OpCodes.Rem_Un;
3520                                 else
3521                                         opcode = OpCodes.Rem;
3522                                 break;
3523
3524                         case Operator.Addition:
3525                                 if (ec.HasSet (EmitContext.Options.CheckedScope)) {
3526                                         if (l.BuiltinType == BuiltinTypeSpec.Type.Int || l.BuiltinType == BuiltinTypeSpec.Type.Long)
3527                                                 opcode = OpCodes.Add_Ovf;
3528                                         else if (!IsFloat (l))
3529                                                 opcode = OpCodes.Add_Ovf_Un;
3530                                         else
3531                                                 opcode = OpCodes.Add;
3532                                 } else
3533                                         opcode = OpCodes.Add;
3534                                 break;
3535
3536                         case Operator.Subtraction:
3537                                 if (ec.HasSet (EmitContext.Options.CheckedScope)) {
3538                                         if (l.BuiltinType == BuiltinTypeSpec.Type.Int || l.BuiltinType == BuiltinTypeSpec.Type.Long)
3539                                                 opcode = OpCodes.Sub_Ovf;
3540                                         else if (!IsFloat (l))
3541                                                 opcode = OpCodes.Sub_Ovf_Un;
3542                                         else
3543                                                 opcode = OpCodes.Sub;
3544                                 } else
3545                                         opcode = OpCodes.Sub;
3546                                 break;
3547
3548                         case Operator.RightShift:
3549                                 if (!(right is IntConstant)) {
3550                                         ec.EmitInt (GetShiftMask (l));
3551                                         ec.Emit (OpCodes.And);
3552                                 }
3553
3554                                 if (IsUnsigned (l))
3555                                         opcode = OpCodes.Shr_Un;
3556                                 else
3557                                         opcode = OpCodes.Shr;
3558                                 break;
3559                                 
3560                         case Operator.LeftShift:
3561                                 if (!(right is IntConstant)) {
3562                                         ec.EmitInt (GetShiftMask (l));
3563                                         ec.Emit (OpCodes.And);
3564                                 }
3565
3566                                 opcode = OpCodes.Shl;
3567                                 break;
3568
3569                         case Operator.Equality:
3570                                 opcode = OpCodes.Ceq;
3571                                 break;
3572
3573                         case Operator.Inequality:
3574                                 ec.Emit (OpCodes.Ceq);
3575                                 ec.EmitInt (0);
3576                                 
3577                                 opcode = OpCodes.Ceq;
3578                                 break;
3579
3580                         case Operator.LessThan:
3581                                 if (IsUnsigned (l))
3582                                         opcode = OpCodes.Clt_Un;
3583                                 else
3584                                         opcode = OpCodes.Clt;
3585                                 break;
3586
3587                         case Operator.GreaterThan:
3588                                 if (IsUnsigned (l))
3589                                         opcode = OpCodes.Cgt_Un;
3590                                 else
3591                                         opcode = OpCodes.Cgt;
3592                                 break;
3593
3594                         case Operator.LessThanOrEqual:
3595                                 if (IsUnsigned (l) || IsFloat (l))
3596                                         ec.Emit (OpCodes.Cgt_Un);
3597                                 else
3598                                         ec.Emit (OpCodes.Cgt);
3599                                 ec.EmitInt (0);
3600                                 
3601                                 opcode = OpCodes.Ceq;
3602                                 break;
3603
3604                         case Operator.GreaterThanOrEqual:
3605                                 if (IsUnsigned (l) || IsFloat (l))
3606                                         ec.Emit (OpCodes.Clt_Un);
3607                                 else
3608                                         ec.Emit (OpCodes.Clt);
3609                                 
3610                                 ec.EmitInt (0);
3611                                 
3612                                 opcode = OpCodes.Ceq;
3613                                 break;
3614
3615                         case Operator.BitwiseOr:
3616                                 opcode = OpCodes.Or;
3617                                 break;
3618
3619                         case Operator.BitwiseAnd:
3620                                 opcode = OpCodes.And;
3621                                 break;
3622
3623                         case Operator.ExclusiveOr:
3624                                 opcode = OpCodes.Xor;
3625                                 break;
3626
3627                         default:
3628                                 throw new InternalErrorException (oper.ToString ());
3629                         }
3630
3631                         ec.Emit (opcode);
3632                 }
3633
3634                 static int GetShiftMask (TypeSpec type)
3635                 {
3636                         return type.BuiltinType == BuiltinTypeSpec.Type.Int || type.BuiltinType == BuiltinTypeSpec.Type.UInt ? 0x1f : 0x3f;
3637                 }
3638
3639                 static bool IsUnsigned (TypeSpec t)
3640                 {
3641                         switch (t.BuiltinType) {
3642                         case BuiltinTypeSpec.Type.Char:
3643                         case BuiltinTypeSpec.Type.UInt:
3644                         case BuiltinTypeSpec.Type.ULong:
3645                         case BuiltinTypeSpec.Type.UShort:
3646                         case BuiltinTypeSpec.Type.Byte:
3647                                 return true;
3648                         }
3649
3650                         return t.IsPointer;
3651                 }
3652
3653                 static bool IsFloat (TypeSpec t)
3654                 {
3655                         return t.BuiltinType == BuiltinTypeSpec.Type.Float || t.BuiltinType == BuiltinTypeSpec.Type.Double;
3656                 }
3657
3658                 public Expression ResolveOperator (ResolveContext rc)
3659                 {
3660                         eclass = ExprClass.Value;
3661
3662                         TypeSpec l = left.Type;
3663                         TypeSpec r = right.Type;
3664                         Expression expr;
3665                         bool primitives_only = false;
3666
3667                         //
3668                         // Handles predefined primitive types
3669                         //
3670                         if ((BuiltinTypeSpec.IsPrimitiveType (l) || (l.IsNullableType && BuiltinTypeSpec.IsPrimitiveType (Nullable.NullableInfo.GetUnderlyingType (l)))) &&
3671                                 (BuiltinTypeSpec.IsPrimitiveType (r) || (r.IsNullableType && BuiltinTypeSpec.IsPrimitiveType (Nullable.NullableInfo.GetUnderlyingType (r))))) {
3672                                 if ((oper & Operator.ShiftMask) == 0) {
3673                                         if (!DoBinaryOperatorPromotion (rc))
3674                                                 return null;
3675
3676                                         primitives_only = BuiltinTypeSpec.IsPrimitiveType (l) && BuiltinTypeSpec.IsPrimitiveType (r);
3677                                 }
3678                         } else {
3679                                 // Pointers
3680                                 if (l.IsPointer || r.IsPointer)
3681                                         return ResolveOperatorPointer (rc, l, r);
3682
3683                                 // User operators
3684                                 if ((state & State.UserOperatorsExcluded) == 0) {
3685                                         expr = ResolveUserOperator (rc, left, right);
3686                                         if (expr != null)
3687                                                 return expr;
3688                                 }
3689
3690                                 bool lenum = l.IsEnum;
3691                                 bool renum = r.IsEnum;
3692                                 if ((oper & (Operator.ComparisonMask | Operator.BitwiseMask)) != 0) {
3693                                         //
3694                                         // Enumerations
3695                                         //
3696                                         if (IsEnumOrNullableEnum (l) || IsEnumOrNullableEnum (r)) {
3697                                                 expr = ResolveSingleEnumOperators (rc, lenum, renum, l, r);
3698
3699                                                 if (expr == null)
3700                                                         return null;
3701
3702                                                 if ((oper & Operator.BitwiseMask) != 0) {
3703                                                         expr = EmptyCast.Create (expr, type);
3704                                                         enum_conversion = GetEnumResultCast (type);
3705
3706                                                         if (oper == Operator.BitwiseAnd && left.Type.IsEnum && right.Type.IsEnum) {
3707                                                                 expr = OptimizeAndOperation (expr);
3708                                                         }
3709                                                 }
3710
3711                                                 left = ConvertEnumOperandToUnderlyingType (rc, left, r.IsNullableType);
3712                                                 right = ConvertEnumOperandToUnderlyingType (rc, right, l.IsNullableType);
3713                                                 return expr;
3714                                         }
3715                                 } else if ((oper == Operator.Addition || oper == Operator.Subtraction)) {
3716                                         if (IsEnumOrNullableEnum (l) || IsEnumOrNullableEnum (r)) {
3717                                                 //
3718                                                 // Enumerations
3719                                                 //
3720                                                 expr = ResolveEnumOperators (rc, lenum, renum, l, r);
3721
3722                                                 //
3723                                                 // We cannot break here there is also Enum + String possible match
3724                                                 // which is not ambiguous with predefined enum operators
3725                                                 //
3726                                                 if (expr != null) {
3727                                                         left = ConvertEnumOperandToUnderlyingType (rc, left, false);
3728                                                         right = ConvertEnumOperandToUnderlyingType (rc, right, false);
3729
3730                                                         return expr;
3731                                                 }
3732                                         } else if (l.IsDelegate || r.IsDelegate) {
3733                                                 //
3734                                                 // Delegates
3735                                                 //
3736                                                 expr = ResolveOperatorDelegate (rc, l, r);
3737
3738                                                 // TODO: Can this be ambiguous
3739                                                 if (expr != null)
3740                                                         return expr;
3741                                         }
3742                                 }
3743                         }
3744                         
3745                         //
3746                         // Equality operators are more complicated
3747                         //
3748                         if ((oper & Operator.EqualityMask) != 0) {
3749                                 return ResolveEquality (rc, l, r, primitives_only);
3750                         }
3751
3752                         expr = ResolveOperatorPredefined (rc, rc.BuiltinTypes.OperatorsBinaryStandard, primitives_only);
3753                         if (expr != null)
3754                                 return expr;
3755
3756                         if (primitives_only)
3757                                 return null;
3758
3759                         //
3760                         // Lifted operators have lower priority
3761                         //
3762                         return ResolveOperatorPredefined (rc, rc.Module.OperatorsBinaryLifted, false);
3763                 }
3764
3765                 static bool IsEnumOrNullableEnum (TypeSpec type)
3766                 {
3767                         return type.IsEnum || (type.IsNullableType && Nullable.NullableInfo.GetUnderlyingType (type).IsEnum);
3768                 }
3769
3770
3771                 // at least one of 'left' or 'right' is an enumeration constant (EnumConstant or SideEffectConstant or ...)
3772                 // if 'left' is not an enumeration constant, create one from the type of 'right'
3773                 Constant EnumLiftUp (ResolveContext ec, Constant left, Constant right)
3774                 {
3775                         switch (oper) {
3776                         case Operator.BitwiseOr:
3777                         case Operator.BitwiseAnd:
3778                         case Operator.ExclusiveOr:
3779                         case Operator.Equality:
3780                         case Operator.Inequality:
3781                         case Operator.LessThan:
3782                         case Operator.LessThanOrEqual:
3783                         case Operator.GreaterThan:
3784                         case Operator.GreaterThanOrEqual:
3785                                 if (left.Type.IsEnum)
3786                                         return left;
3787                                 
3788                                 if (left.IsZeroInteger)
3789                                         return left.Reduce (ec, right.Type);
3790                                 
3791                                 break;
3792                                 
3793                         case Operator.Addition:
3794                         case Operator.Subtraction:
3795                                 return left;
3796                                 
3797                         case Operator.Multiply:
3798                         case Operator.Division:
3799                         case Operator.Modulus:
3800                         case Operator.LeftShift:
3801                         case Operator.RightShift:
3802                                 if (right.Type.IsEnum || left.Type.IsEnum)
3803                                         break;
3804                                 return left;
3805                         }
3806
3807                         return null;
3808                 }
3809
3810                 //
3811                 // The `|' operator used on types which were extended is dangerous
3812                 //
3813                 void CheckBitwiseOrOnSignExtended (ResolveContext ec)
3814                 {
3815                         OpcodeCast lcast = left as OpcodeCast;
3816                         if (lcast != null) {
3817                                 if (IsUnsigned (lcast.UnderlyingType))
3818                                         lcast = null;
3819                         }
3820
3821                         OpcodeCast rcast = right as OpcodeCast;
3822                         if (rcast != null) {
3823                                 if (IsUnsigned (rcast.UnderlyingType))
3824                                         rcast = null;
3825                         }
3826
3827                         if (lcast == null && rcast == null)
3828                                 return;
3829
3830                         // FIXME: consider constants
3831
3832                         var ltype = lcast != null ? lcast.UnderlyingType : rcast.UnderlyingType;
3833                         ec.Report.Warning (675, 3, loc,
3834                                 "The operator `|' used on the sign-extended type `{0}'. Consider casting to a smaller unsigned type first",
3835                                 ltype.GetSignatureForError ());
3836                 }
3837
3838                 public static PredefinedOperator[] CreatePointerOperatorsTable (BuiltinTypes types)
3839                 {
3840                         return new PredefinedOperator[] {
3841                                 //
3842                                 // Pointer arithmetic:
3843                                 //
3844                                 // T* operator + (T* x, int y);         T* operator - (T* x, int y);
3845                                 // T* operator + (T* x, uint y);        T* operator - (T* x, uint y);
3846                                 // T* operator + (T* x, long y);        T* operator - (T* x, long y);
3847                                 // T* operator + (T* x, ulong y);       T* operator - (T* x, ulong y);
3848                                 //
3849                                 new PredefinedPointerOperator (null, types.Int, Operator.AdditionMask | Operator.SubtractionMask),
3850                                 new PredefinedPointerOperator (null, types.UInt, Operator.AdditionMask | Operator.SubtractionMask),
3851                                 new PredefinedPointerOperator (null, types.Long, Operator.AdditionMask | Operator.SubtractionMask),
3852                                 new PredefinedPointerOperator (null, types.ULong, Operator.AdditionMask | Operator.SubtractionMask),
3853
3854                                 //
3855                                 // T* operator + (int y,   T* x);
3856                                 // T* operator + (uint y,  T *x);
3857                                 // T* operator + (long y,  T *x);
3858                                 // T* operator + (ulong y, T *x);
3859                                 //
3860                                 new PredefinedPointerOperator (types.Int, null, Operator.AdditionMask, null),
3861                                 new PredefinedPointerOperator (types.UInt, null, Operator.AdditionMask, null),
3862                                 new PredefinedPointerOperator (types.Long, null, Operator.AdditionMask, null),
3863                                 new PredefinedPointerOperator (types.ULong, null, Operator.AdditionMask, null),
3864
3865                                 //
3866                                 // long operator - (T* x, T *y)
3867                                 //
3868                                 new PredefinedPointerOperator (null, Operator.SubtractionMask, types.Long)
3869                         };
3870                 }
3871
3872                 public static PredefinedOperator[] CreateStandardOperatorsTable (BuiltinTypes types)
3873                 {
3874                         TypeSpec bool_type = types.Bool;
3875
3876                         return new [] {
3877                                 new PredefinedOperator (types.Int, Operator.ArithmeticMask | Operator.BitwiseMask | Operator.ShiftMask),
3878                                 new PredefinedOperator (types.UInt, Operator.ArithmeticMask | Operator.BitwiseMask),
3879                                 new PredefinedOperator (types.Long, Operator.ArithmeticMask | Operator.BitwiseMask),
3880                                 new PredefinedOperator (types.ULong, Operator.ArithmeticMask | Operator.BitwiseMask),
3881                                 new PredefinedOperator (types.Float, Operator.ArithmeticMask),
3882                                 new PredefinedOperator (types.Double, Operator.ArithmeticMask),
3883                                 new PredefinedOperator (types.Decimal, Operator.ArithmeticMask),
3884
3885                                 new PredefinedOperator (types.Int, Operator.ComparisonMask, bool_type),
3886                                 new PredefinedOperator (types.UInt, Operator.ComparisonMask, bool_type),
3887                                 new PredefinedOperator (types.Long, Operator.ComparisonMask, bool_type),
3888                                 new PredefinedOperator (types.ULong, Operator.ComparisonMask, bool_type),
3889                                 new PredefinedOperator (types.Float, Operator.ComparisonMask, bool_type),
3890                                 new PredefinedOperator (types.Double, Operator.ComparisonMask, bool_type),
3891                                 new PredefinedOperator (types.Decimal, Operator.ComparisonMask, bool_type),
3892
3893                                 new PredefinedStringOperator (types.String, Operator.AdditionMask, types.String),
3894                                 // Remaining string operators are in lifted tables
3895
3896                                 new PredefinedOperator (bool_type, Operator.BitwiseMask | Operator.LogicalMask | Operator.EqualityMask, bool_type),
3897
3898                                 new PredefinedOperator (types.UInt, types.Int, Operator.ShiftMask),
3899                                 new PredefinedOperator (types.Long, types.Int, Operator.ShiftMask),
3900                                 new PredefinedOperator (types.ULong, types.Int, Operator.ShiftMask)
3901                         };
3902
3903                 }
3904                 public static PredefinedOperator[] CreateStandardLiftedOperatorsTable (ModuleContainer module)
3905                 {
3906                         var types = module.Compiler.BuiltinTypes;
3907
3908                         //
3909                         // Not strictly lifted but need to be in second group otherwise expressions like
3910                         // int + null would resolve to +(object, string) instead of +(int?, int?)
3911                         //
3912                         var string_operators = new [] {
3913                                 new PredefinedStringOperator (types.String, types.Object, Operator.AdditionMask, types.String),
3914                                 new PredefinedStringOperator (types.Object, types.String, Operator.AdditionMask, types.String),
3915                         };
3916
3917                         var nullable = module.PredefinedTypes.Nullable.TypeSpec;
3918                         if (nullable == null)
3919                                 return string_operators;
3920
3921                         var bool_type = types.Bool;
3922
3923                         var nullable_bool = nullable.MakeGenericType (module, new[] { bool_type });
3924                         var nullable_int = nullable.MakeGenericType (module, new[] { types.Int });
3925                         var nullable_uint = nullable.MakeGenericType (module, new[] { types.UInt });
3926                         var nullable_long = nullable.MakeGenericType (module, new[] { types.Long });
3927                         var nullable_ulong = nullable.MakeGenericType (module, new[] { types.ULong });
3928                         var nullable_float = nullable.MakeGenericType (module, new[] { types.Float });
3929                         var nullable_double = nullable.MakeGenericType (module, new[] { types.Double });
3930                         var nullable_decimal = nullable.MakeGenericType (module, new[] { types.Decimal });
3931
3932                         return new[] {
3933                                 new PredefinedOperator (nullable_int, Operator.NullableMask | Operator.ArithmeticMask | Operator.BitwiseMask | Operator.ShiftMask),
3934                                 new PredefinedOperator (nullable_uint, Operator.NullableMask | Operator.ArithmeticMask | Operator.BitwiseMask),
3935                                 new PredefinedOperator (nullable_long, Operator.NullableMask | Operator.ArithmeticMask | Operator.BitwiseMask),
3936                                 new PredefinedOperator (nullable_ulong, Operator.NullableMask | Operator.ArithmeticMask | Operator.BitwiseMask),
3937                                 new PredefinedOperator (nullable_float, Operator.NullableMask | Operator.ArithmeticMask),
3938                                 new PredefinedOperator (nullable_double, Operator.NullableMask | Operator.ArithmeticMask),
3939                                 new PredefinedOperator (nullable_decimal, Operator.NullableMask | Operator.ArithmeticMask),
3940
3941                                 new PredefinedOperator (nullable_int, Operator.NullableMask | Operator.ComparisonMask, bool_type),
3942                                 new PredefinedOperator (nullable_uint, Operator.NullableMask | Operator.ComparisonMask, bool_type),
3943                                 new PredefinedOperator (nullable_long, Operator.NullableMask | Operator.ComparisonMask, bool_type),
3944                                 new PredefinedOperator (nullable_ulong, Operator.NullableMask | Operator.ComparisonMask, bool_type),
3945                                 new PredefinedOperator (nullable_float, Operator.NullableMask | Operator.ComparisonMask, bool_type),
3946                                 new PredefinedOperator (nullable_double, Operator.NullableMask | Operator.ComparisonMask, bool_type),
3947                                 new PredefinedOperator (nullable_decimal, Operator.NullableMask | Operator.ComparisonMask, bool_type),
3948
3949                                 new PredefinedOperator (nullable_bool, Operator.NullableMask | Operator.BitwiseMask, nullable_bool),
3950
3951                                 new PredefinedOperator (nullable_uint, nullable_int, Operator.NullableMask | Operator.ShiftMask),
3952                                 new PredefinedOperator (nullable_long, nullable_int, Operator.NullableMask | Operator.ShiftMask),
3953                                 new PredefinedOperator (nullable_ulong, nullable_int, Operator.NullableMask | Operator.ShiftMask),
3954
3955                                 string_operators [0],
3956                                 string_operators [1]
3957                         };
3958                 }
3959
3960                 public static PredefinedOperator[] CreateEqualityOperatorsTable (BuiltinTypes types)
3961                 {
3962                         TypeSpec bool_type = types.Bool;
3963
3964                         return new[] {
3965                                 new PredefinedEqualityOperator (types.String, bool_type),
3966                                 new PredefinedEqualityOperator (types.Delegate, bool_type),
3967                                 new PredefinedOperator (bool_type, Operator.EqualityMask, bool_type),
3968                                 new PredefinedOperator (types.Int, Operator.EqualityMask, bool_type),
3969                                 new PredefinedOperator (types.UInt, Operator.EqualityMask, bool_type),
3970                                 new PredefinedOperator (types.Long, Operator.EqualityMask, bool_type),
3971                                 new PredefinedOperator (types.ULong, Operator.EqualityMask, bool_type),
3972                                 new PredefinedOperator (types.Float, Operator.EqualityMask, bool_type),
3973                                 new PredefinedOperator (types.Double, Operator.EqualityMask, bool_type),
3974                                 new PredefinedOperator (types.Decimal, Operator.EqualityMask, bool_type),
3975                         };
3976                 }
3977
3978                 public static PredefinedOperator[] CreateEqualityLiftedOperatorsTable (ModuleContainer module)
3979                 {
3980                         var nullable = module.PredefinedTypes.Nullable.TypeSpec;
3981
3982                         if (nullable == null)
3983                                 return new PredefinedOperator [0];
3984
3985                         var types = module.Compiler.BuiltinTypes;
3986                         var bool_type = types.Bool;
3987                         var nullable_bool = nullable.MakeGenericType (module, new [] { bool_type });
3988                         var nullable_int = nullable.MakeGenericType (module, new[] { types.Int });
3989                         var nullable_uint = nullable.MakeGenericType (module, new[] { types.UInt });
3990                         var nullable_long = nullable.MakeGenericType (module, new[] { types.Long });
3991                         var nullable_ulong = nullable.MakeGenericType (module, new[] { types.ULong });
3992                         var nullable_float = nullable.MakeGenericType (module, new[] { types.Float });
3993                         var nullable_double = nullable.MakeGenericType (module, new[] { types.Double });
3994                         var nullable_decimal = nullable.MakeGenericType (module, new[] { types.Decimal });
3995
3996                         return new [] {
3997                                 new PredefinedOperator (nullable_bool, Operator.NullableMask | Operator.EqualityMask, bool_type),
3998                                 new PredefinedOperator (nullable_int, Operator.NullableMask | Operator.EqualityMask, bool_type),
3999                                 new PredefinedOperator (nullable_uint, Operator.NullableMask | Operator.EqualityMask, bool_type),
4000                                 new PredefinedOperator (nullable_long, Operator.NullableMask | Operator.EqualityMask, bool_type),
4001                                 new PredefinedOperator (nullable_ulong, Operator.NullableMask | Operator.EqualityMask, bool_type),
4002                                 new PredefinedOperator (nullable_float, Operator.NullableMask | Operator.EqualityMask, bool_type),
4003                                 new PredefinedOperator (nullable_double, Operator.NullableMask | Operator.EqualityMask, bool_type),
4004                                 new PredefinedOperator (nullable_decimal, Operator.NullableMask | Operator.EqualityMask, bool_type)
4005                         };
4006                 }
4007
4008                 //
4009                 // 7.2.6.2 Binary numeric promotions
4010                 //
4011                 bool DoBinaryOperatorPromotion (ResolveContext rc)
4012                 {
4013                         TypeSpec ltype = left.Type;
4014                         if (ltype.IsNullableType) {
4015                                 ltype = Nullable.NullableInfo.GetUnderlyingType (ltype);
4016                         }
4017
4018                         //
4019                         // This is numeric promotion code only
4020                         //
4021                         if (ltype.BuiltinType == BuiltinTypeSpec.Type.Bool)
4022                                 return true;
4023
4024                         TypeSpec rtype = right.Type;
4025                         if (rtype.IsNullableType) {
4026                                 rtype = Nullable.NullableInfo.GetUnderlyingType (rtype);
4027                         }
4028
4029                         var lb = ltype.BuiltinType;
4030                         var rb = rtype.BuiltinType;
4031                         TypeSpec type;
4032                         Expression expr;
4033
4034                         if (lb == BuiltinTypeSpec.Type.Decimal || rb == BuiltinTypeSpec.Type.Decimal) {
4035                                 type = rc.BuiltinTypes.Decimal;
4036                         } else if (lb == BuiltinTypeSpec.Type.Double || rb == BuiltinTypeSpec.Type.Double) {
4037                                 type = rc.BuiltinTypes.Double;
4038                         } else if (lb == BuiltinTypeSpec.Type.Float || rb == BuiltinTypeSpec.Type.Float) {
4039                                 type = rc.BuiltinTypes.Float;
4040                         } else if (lb == BuiltinTypeSpec.Type.ULong || rb == BuiltinTypeSpec.Type.ULong) {
4041                                 type = rc.BuiltinTypes.ULong;
4042
4043                                 if (IsSignedType (lb)) {
4044                                         expr = ConvertSignedConstant (left, type);
4045                                         if (expr == null)
4046                                                 return false;
4047                                         left = expr;
4048                                 } else if (IsSignedType (rb)) {
4049                                         expr = ConvertSignedConstant (right, type);
4050                                         if (expr == null)
4051                                                 return false;
4052                                         right = expr;
4053                                 }
4054
4055                         } else if (lb == BuiltinTypeSpec.Type.Long || rb == BuiltinTypeSpec.Type.Long) {
4056                                 type = rc.BuiltinTypes.Long;
4057                         } else if (lb == BuiltinTypeSpec.Type.UInt || rb == BuiltinTypeSpec.Type.UInt) {
4058                                 type = rc.BuiltinTypes.UInt;
4059
4060                                 if (IsSignedType (lb)) {
4061                                         expr = ConvertSignedConstant (left, type);
4062                                         if (expr == null)
4063                                                 type = rc.BuiltinTypes.Long;
4064                                 } else if (IsSignedType (rb)) {
4065                                         expr = ConvertSignedConstant (right, type);
4066                                         if (expr == null)
4067                                                 type = rc.BuiltinTypes.Long;
4068                                 }
4069                         } else {
4070                                 type = rc.BuiltinTypes.Int;
4071                         }
4072
4073                         if (ltype != type) {
4074                                 expr = PromoteExpression (rc, left, type);
4075                                 if (expr == null)
4076                                         return false;
4077
4078                                 left = expr;
4079                         }
4080
4081                         if (rtype != type) {
4082                                 expr = PromoteExpression (rc, right, type);
4083                                 if (expr == null)
4084                                         return false;
4085
4086                                 right = expr;
4087                         }
4088
4089                         return true;
4090                 }
4091
4092                 static bool IsSignedType (BuiltinTypeSpec.Type type)
4093                 {
4094                         switch (type) {
4095                         case BuiltinTypeSpec.Type.Int:
4096                         case BuiltinTypeSpec.Type.Short:
4097                         case BuiltinTypeSpec.Type.SByte:
4098                         case BuiltinTypeSpec.Type.Long:
4099                                 return true;
4100                         default:
4101                                 return false;
4102                         }
4103                 }
4104
4105                 static Expression ConvertSignedConstant (Expression expr, TypeSpec type)
4106                 {
4107                         var c = expr as Constant;
4108                         if (c == null)
4109                                 return null;
4110
4111                         return c.ConvertImplicitly (type);
4112                 }
4113
4114                 static Expression PromoteExpression (ResolveContext rc, Expression expr, TypeSpec type)
4115                 {
4116                         if (expr.Type.IsNullableType) {
4117                                 return Convert.ImplicitConversionStandard (rc, expr,
4118                                         rc.Module.PredefinedTypes.Nullable.TypeSpec.MakeGenericType (rc, new[] { type }), expr.Location);
4119                         }
4120
4121                         var c = expr as Constant;
4122                         if (c != null)
4123                                 return c.ConvertImplicitly (type);
4124
4125                         return Convert.ImplicitNumericConversion (expr, type);
4126                 }
4127
4128                 protected override Expression DoResolve (ResolveContext ec)
4129                 {
4130                         if (left == null)
4131                                 return null;
4132
4133                         if ((oper == Operator.Subtraction) && (left is ParenthesizedExpression)) {
4134                                 left = ((ParenthesizedExpression) left).Expr;
4135                                 left = left.Resolve (ec, ResolveFlags.VariableOrValue | ResolveFlags.Type);
4136                                 if (left == null)
4137                                         return null;
4138
4139                                 if (left.eclass == ExprClass.Type) {
4140                                         ec.Report.Error (75, loc, "To cast a negative value, you must enclose the value in parentheses");
4141                                         return null;
4142                                 }
4143                         } else
4144                                 left = left.Resolve (ec);
4145
4146                         if (left == null)
4147                                 return null;
4148
4149                         right = right.Resolve (ec);
4150                         if (right == null)
4151                                 return null;
4152
4153                         Constant lc = left as Constant;
4154                         Constant rc = right as Constant;
4155
4156                         // The conversion rules are ignored in enum context but why
4157                         if (!ec.HasSet (ResolveContext.Options.EnumScope) && lc != null && rc != null && (left.Type.IsEnum || right.Type.IsEnum)) {
4158                                 lc = EnumLiftUp (ec, lc, rc);
4159                                 if (lc != null)
4160                                         rc = EnumLiftUp (ec, rc, lc);
4161                         }
4162
4163                         if (rc != null && lc != null) {
4164                                 int prev_e = ec.Report.Errors;
4165                                 Expression e = ConstantFold.BinaryFold (ec, oper, lc, rc, loc);
4166                                 if (e != null || ec.Report.Errors != prev_e)
4167                                         return e;
4168                         }
4169
4170                         // Comparison warnings
4171                         if ((oper & Operator.ComparisonMask) != 0) {
4172                                 if (left.Equals (right)) {
4173                                         ec.Report.Warning (1718, 3, loc, "A comparison made to same variable. Did you mean to compare something else?");
4174                                 }
4175                                 CheckOutOfRangeComparison (ec, lc, right.Type);
4176                                 CheckOutOfRangeComparison (ec, rc, left.Type);
4177                         }
4178
4179                         if (left.Type.BuiltinType == BuiltinTypeSpec.Type.Dynamic || right.Type.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
4180                                 return DoResolveDynamic (ec);
4181
4182                         return DoResolveCore (ec, left, right);
4183                 }
4184
4185                 Expression DoResolveDynamic (ResolveContext rc)
4186                 {
4187                         var lt = left.Type;
4188                         var rt = right.Type;
4189                         if (lt.Kind == MemberKind.Void || lt == InternalType.MethodGroup || lt == InternalType.AnonymousMethod ||
4190                                 rt.Kind == MemberKind.Void || rt == InternalType.MethodGroup || rt == InternalType.AnonymousMethod) {
4191                                 Error_OperatorCannotBeApplied (rc, left, right);
4192                                 return null;
4193                         }
4194
4195                         Arguments args;
4196
4197                         //
4198                         // Special handling for logical boolean operators which require rhs not to be
4199                         // evaluated based on lhs value
4200                         //
4201                         if ((oper & Operator.LogicalMask) != 0) {
4202                                 Expression cond_left, cond_right, expr;
4203
4204                                 args = new Arguments (2);
4205
4206                                 if (lt.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
4207                                         LocalVariable temp = LocalVariable.CreateCompilerGenerated (lt, rc.CurrentBlock, loc);
4208
4209                                         var cond_args = new Arguments (1);
4210                                         cond_args.Add (new Argument (new SimpleAssign (temp.CreateReferenceExpression (rc, loc), left).Resolve (rc)));
4211
4212                                         //
4213                                         // dynamic && bool => IsFalse (temp = left) ? temp : temp && right;
4214                                         // dynamic || bool => IsTrue (temp = left) ? temp : temp || right;
4215                                         //
4216                                         left = temp.CreateReferenceExpression (rc, loc);
4217                                         if (oper == Operator.LogicalAnd) {
4218                                                 expr = DynamicUnaryConversion.CreateIsFalse (rc, cond_args, loc);
4219                                                 cond_left = left;
4220                                         } else {
4221                                                 expr = DynamicUnaryConversion.CreateIsTrue (rc, cond_args, loc);
4222                                                 cond_left = left;
4223                                         }
4224
4225                                         args.Add (new Argument (left));
4226                                         args.Add (new Argument (right));
4227                                         cond_right = new DynamicExpressionStatement (this, args, loc);
4228                                 } else {
4229                                         LocalVariable temp = LocalVariable.CreateCompilerGenerated (rc.BuiltinTypes.Bool, rc.CurrentBlock, loc);
4230
4231                                         if (!Convert.ImplicitConversionExists (rc, left, temp.Type) && (oper == Operator.LogicalAnd ? GetOperatorFalse (rc, left, loc) : GetOperatorTrue (rc, left, loc)) == null) {
4232                                                 rc.Report.Error (7083, left.Location,
4233                                                         "Expression must be implicitly convertible to Boolean or its type `{0}' must define operator `{1}'",
4234                                                         lt.GetSignatureForError (), oper == Operator.LogicalAnd ? "false" : "true");
4235                                                 return null;
4236                                         }
4237
4238                                         args.Add (new Argument (temp.CreateReferenceExpression (rc, loc).Resolve (rc)));
4239                                         args.Add (new Argument (right));
4240                                         right = new DynamicExpressionStatement (this, args, loc);
4241
4242                                         //
4243                                         // bool && dynamic => (temp = left) ? temp && right : temp;
4244                                         // bool || dynamic => (temp = left) ? temp : temp || right;
4245                                         //
4246                                         if (oper == Operator.LogicalAnd) {
4247                                                 cond_left = right;
4248                                                 cond_right = temp.CreateReferenceExpression (rc, loc);
4249                                         } else {
4250                                                 cond_left = temp.CreateReferenceExpression (rc, loc);
4251                                                 cond_right = right;
4252                                         }
4253
4254                                         expr = new BooleanExpression (new SimpleAssign (temp.CreateReferenceExpression (rc, loc), left));
4255                                 }
4256
4257                                 return new Conditional (expr, cond_left, cond_right, loc).Resolve (rc);
4258                         }
4259
4260                         args = new Arguments (2);
4261                         args.Add (new Argument (left));
4262                         args.Add (new Argument (right));
4263                         return new DynamicExpressionStatement (this, args, loc).Resolve (rc);
4264                 }
4265
4266                 Expression DoResolveCore (ResolveContext ec, Expression left_orig, Expression right_orig)
4267                 {
4268                         Expression expr = ResolveOperator (ec);
4269                         if (expr == null)
4270                                 Error_OperatorCannotBeApplied (ec, left_orig, right_orig);
4271
4272                         if (left == null || right == null)
4273                                 throw new InternalErrorException ("Invalid conversion");
4274
4275                         if (oper == Operator.BitwiseOr)
4276                                 CheckBitwiseOrOnSignExtended (ec);
4277
4278                         return expr;
4279                 }
4280
4281                 public override SLE.Expression MakeExpression (BuilderContext ctx)
4282                 {
4283                         return MakeExpression (ctx, left, right);
4284                 }
4285
4286                 public SLE.Expression MakeExpression (BuilderContext ctx, Expression left, Expression right)
4287                 {
4288                         var le = left.MakeExpression (ctx);
4289                         var re = right.MakeExpression (ctx);
4290                         bool is_checked = ctx.HasSet (BuilderContext.Options.CheckedScope);
4291
4292                         switch (oper) {
4293                         case Operator.Addition:
4294                                 return is_checked ? SLE.Expression.AddChecked (le, re) : SLE.Expression.Add (le, re);
4295                         case Operator.BitwiseAnd:
4296                                 return SLE.Expression.And (le, re);
4297                         case Operator.BitwiseOr:
4298                                 return SLE.Expression.Or (le, re);
4299                         case Operator.Division:
4300                                 return SLE.Expression.Divide (le, re);
4301                         case Operator.Equality:
4302                                 return SLE.Expression.Equal (le, re);
4303                         case Operator.ExclusiveOr:
4304                                 return SLE.Expression.ExclusiveOr (le, re);
4305                         case Operator.GreaterThan:
4306                                 return SLE.Expression.GreaterThan (le, re);
4307                         case Operator.GreaterThanOrEqual:
4308                                 return SLE.Expression.GreaterThanOrEqual (le, re);
4309                         case Operator.Inequality:
4310                                 return SLE.Expression.NotEqual (le, re);
4311                         case Operator.LeftShift:
4312                                 return SLE.Expression.LeftShift (le, re);
4313                         case Operator.LessThan:
4314                                 return SLE.Expression.LessThan (le, re);
4315                         case Operator.LessThanOrEqual:
4316                                 return SLE.Expression.LessThanOrEqual (le, re);
4317                         case Operator.LogicalAnd:
4318                                 return SLE.Expression.AndAlso (le, re);
4319                         case Operator.LogicalOr:
4320                                 return SLE.Expression.OrElse (le, re);
4321                         case Operator.Modulus:
4322                                 return SLE.Expression.Modulo (le, re);
4323                         case Operator.Multiply:
4324                                 return is_checked ? SLE.Expression.MultiplyChecked (le, re) : SLE.Expression.Multiply (le, re);
4325                         case Operator.RightShift:
4326                                 return SLE.Expression.RightShift (le, re);
4327                         case Operator.Subtraction:
4328                                 return is_checked ? SLE.Expression.SubtractChecked (le, re) : SLE.Expression.Subtract (le, re);
4329                         default:
4330                                 throw new NotImplementedException (oper.ToString ());
4331                         }
4332                 }
4333
4334                 //
4335                 // D operator + (D x, D y)
4336                 // D operator - (D x, D y)
4337                 //
4338                 Expression ResolveOperatorDelegate (ResolveContext ec, TypeSpec l, TypeSpec r)
4339                 {
4340                         if (l != r && !TypeSpecComparer.Variant.IsEqual (r, l)) {
4341                                 Expression tmp;
4342                                 if (right.eclass == ExprClass.MethodGroup || r == InternalType.AnonymousMethod || r == InternalType.NullLiteral) {
4343                                         tmp = Convert.ImplicitConversionRequired (ec, right, l, loc);
4344                                         if (tmp == null)
4345                                                 return null;
4346                                         right = tmp;
4347                                         r = right.Type;
4348                                 } else if (left.eclass == ExprClass.MethodGroup || (l == InternalType.AnonymousMethod || l == InternalType.NullLiteral)) {
4349                                         tmp = Convert.ImplicitConversionRequired (ec, left, r, loc);
4350                                         if (tmp == null)
4351                                                 return null;
4352                                         left = tmp;
4353                                         l = left.Type;
4354                                 } else {
4355                                         return null;
4356                                 }
4357                         }
4358
4359                         MethodSpec method = null;
4360                         Arguments args = new Arguments (2);
4361                         args.Add (new Argument (left));
4362                         args.Add (new Argument (right));
4363
4364                         if (oper == Operator.Addition) {
4365                                 method = ec.Module.PredefinedMembers.DelegateCombine.Resolve (loc);
4366                         } else if (oper == Operator.Subtraction) {
4367                                 method = ec.Module.PredefinedMembers.DelegateRemove.Resolve (loc);
4368                         }
4369
4370                         if (method == null)
4371                                 return new EmptyExpression (ec.BuiltinTypes.Decimal);
4372
4373                         Expression expr = new UserOperatorCall (method, args, CreateExpressionTree, loc);
4374                         return new ClassCast (expr, l);
4375                 }
4376
4377                 //
4378                 // Resolves enumeration operators where only single predefined overload exists, handles lifted versions too
4379                 //
4380                 Expression ResolveSingleEnumOperators (ResolveContext rc, bool lenum, bool renum, TypeSpec ltype, TypeSpec rtype)
4381                 {
4382                         //
4383                         // bool operator == (E x, E y);
4384                         // bool operator != (E x, E y);
4385                         // bool operator < (E x, E y);
4386                         // bool operator > (E x, E y);
4387                         // bool operator <= (E x, E y);
4388                         // bool operator >= (E x, E y);
4389                         //
4390                         // E operator & (E x, E y);
4391                         // E operator | (E x, E y);
4392                         // E operator ^ (E x, E y);
4393                         //
4394                         Expression expr;
4395                         if ((oper & Operator.ComparisonMask) != 0) {
4396                                 type = rc.BuiltinTypes.Bool;
4397                         } else {
4398                                 if (lenum)
4399                                         type = ltype;
4400                                 else if (renum)
4401                                         type = rtype;
4402                                 else if (ltype.IsNullableType && Nullable.NullableInfo.GetUnderlyingType (ltype).IsEnum)
4403                                         type = ltype;
4404                                 else
4405                                         type = rtype;
4406                         }
4407
4408                         if (ltype == rtype) {
4409                                 if (lenum || renum)
4410                                         return this;
4411
4412                                 var lifted = new Nullable.LiftedBinaryOperator (this);
4413                                 lifted.Left = left;
4414                                 lifted.Right = right;
4415                                 return lifted.Resolve (rc);
4416                         }
4417
4418                         if (renum && !ltype.IsNullableType) {
4419                                 expr = Convert.ImplicitConversion (rc, left, rtype, loc);
4420                                 if (expr != null) {
4421                                         left = expr;
4422                                         return this;
4423                                 }
4424                         } else if (lenum && !rtype.IsNullableType) {
4425                                 expr = Convert.ImplicitConversion (rc, right, ltype, loc);
4426                                 if (expr != null) {
4427                                         right = expr;
4428                                         return this;
4429                                 }
4430                         }
4431
4432                         //
4433                         // Now try lifted version of predefined operator
4434                         //
4435                         var nullable_type = rc.Module.PredefinedTypes.Nullable.TypeSpec;
4436                         if (nullable_type != null) {
4437                                 if (renum && !ltype.IsNullableType) {
4438                                         var lifted_type = nullable_type.MakeGenericType (rc.Module, new[] { rtype });
4439
4440                                         expr = Convert.ImplicitConversion (rc, left, lifted_type, loc);
4441                                         if (expr != null) {
4442                                                 left = expr;
4443                                                 right = Convert.ImplicitConversion (rc, right, lifted_type, loc);
4444                                         }
4445
4446                                         if ((oper & Operator.BitwiseMask) != 0)
4447                                                 type = lifted_type;
4448
4449                                         if (left.IsNull) {
4450                                                 if ((oper & Operator.BitwiseMask) != 0)
4451                                                         return Nullable.LiftedNull.CreateFromExpression (rc, this);
4452
4453                                                 return CreateLiftedValueTypeResult (rc, rtype);
4454                                         }
4455
4456                                         if (expr != null) {
4457                                                 var lifted = new Nullable.LiftedBinaryOperator (this);
4458                                                 lifted.Left = expr;
4459                                                 lifted.Right = right;
4460                                                 return lifted.Resolve (rc);
4461                                         }
4462                                 } else if (lenum && !rtype.IsNullableType) {
4463                                         var lifted_type = nullable_type.MakeGenericType (rc.Module, new[] { ltype });
4464
4465                                         expr = Convert.ImplicitConversion (rc, right, lifted_type, loc);
4466                                         if (expr != null) {
4467                                                 right = expr;
4468                                                 left = Convert.ImplicitConversion (rc, left, lifted_type, loc);
4469                                         }
4470
4471                                         if ((oper & Operator.BitwiseMask) != 0)
4472                                                 type = lifted_type;
4473
4474                                         if (right.IsNull) {
4475                                                 if ((oper & Operator.BitwiseMask) != 0)
4476                                                         return Nullable.LiftedNull.CreateFromExpression (rc, this);
4477
4478                                                 return CreateLiftedValueTypeResult (rc, ltype);
4479                                         }
4480
4481                                         if (expr != null) {
4482                                                 var lifted = new Nullable.LiftedBinaryOperator (this);
4483                                                 lifted.Left = left;
4484                                                 lifted.Right = expr;
4485                                                 return lifted.Resolve (rc);
4486                                         }
4487                                 } else if (rtype.IsNullableType && Nullable.NullableInfo.GetUnderlyingType (rtype).IsEnum) {
4488                                         Nullable.Unwrap unwrap = null;
4489                                         if (left.IsNull || right.IsNull) {
4490                                                 if (rc.HasSet (ResolveContext.Options.ExpressionTreeConversion))
4491                                                         left = Convert.ImplicitConversion (rc, left, rtype, left.Location);
4492
4493                                                 if ((oper & Operator.RelationalMask) != 0)
4494                                                         return CreateLiftedValueTypeResult (rc, rtype);
4495
4496                                                 if ((oper & Operator.BitwiseMask) != 0)
4497                                                         return Nullable.LiftedNull.CreateFromExpression (rc, this);
4498
4499                                                 if (right.IsNull)
4500                                                         return CreateLiftedValueTypeResult (rc, left.Type);
4501
4502                                                 // Equality operators are valid between E? and null
4503                                                 expr = left;
4504                                                 unwrap = new Nullable.Unwrap (right);
4505                                         } else {
4506                                                 expr = Convert.ImplicitConversion (rc, left, Nullable.NullableInfo.GetUnderlyingType (rtype), loc);
4507                                                 if (expr == null)
4508                                                         return null;
4509
4510                                                 if ((oper & Operator.BitwiseMask) != 0)
4511                                                         type = rtype;
4512                                         }
4513
4514                                         if (expr != null) {
4515                                                 var lifted = new Nullable.LiftedBinaryOperator (this);
4516                                                 lifted.Left = expr;
4517                                                 lifted.Right = right;
4518                                                 lifted.UnwrapRight = unwrap;
4519                                                 return lifted.Resolve (rc);
4520                                         }
4521                                 } else if (ltype.IsNullableType && Nullable.NullableInfo.GetUnderlyingType (ltype).IsEnum) {
4522                                         Nullable.Unwrap unwrap = null;
4523                                         if (right.IsNull || left.IsNull) {
4524                                                 if (rc.HasSet (ResolveContext.Options.ExpressionTreeConversion))
4525                                                         right = Convert.ImplicitConversion (rc, right, ltype, right.Location);
4526
4527                                                 if ((oper & Operator.RelationalMask) != 0)
4528                                                         return CreateLiftedValueTypeResult (rc, ltype);
4529
4530                                                 if ((oper & Operator.BitwiseMask) != 0)
4531                                                         return Nullable.LiftedNull.CreateFromExpression (rc, this);
4532
4533                                                 if (left.IsNull)
4534                                                         return CreateLiftedValueTypeResult (rc, right.Type);
4535
4536                                                 // Equality operators are valid between E? and null
4537                                                 expr = right;
4538                                                 unwrap = new Nullable.Unwrap (left);
4539                                         } else {
4540                                                 expr = Convert.ImplicitConversion (rc, right, Nullable.NullableInfo.GetUnderlyingType (ltype), loc);
4541                                                 if (expr == null)
4542                                                         return null;
4543
4544                                                 if ((oper & Operator.BitwiseMask) != 0)
4545                                                         type = ltype;
4546                                         }
4547
4548                                         if (expr != null) {
4549                                                 var lifted = new Nullable.LiftedBinaryOperator (this);
4550                                                 lifted.Left = left;
4551                                                 lifted.UnwrapLeft = unwrap;
4552                                                 lifted.Right = expr;
4553                                                 return lifted.Resolve (rc);
4554                                         }
4555                                 }
4556                         }
4557
4558                         return null;
4559                 }
4560
4561                 static Expression ConvertEnumOperandToUnderlyingType (ResolveContext rc, Expression expr, bool liftType)
4562                 {
4563                         TypeSpec underlying_type;
4564                         if (expr.Type.IsNullableType) {
4565                                 var nt = Nullable.NullableInfo.GetUnderlyingType (expr.Type);
4566                                 if (nt.IsEnum)
4567                                         underlying_type = EnumSpec.GetUnderlyingType (nt);
4568                                 else
4569                                         underlying_type = nt;
4570                         } else if (expr.Type.IsEnum) {
4571                                 underlying_type = EnumSpec.GetUnderlyingType (expr.Type);
4572                         } else {
4573                                 underlying_type = expr.Type;
4574                         }
4575
4576                         switch (underlying_type.BuiltinType) {
4577                         case BuiltinTypeSpec.Type.SByte:
4578                         case BuiltinTypeSpec.Type.Byte:
4579                         case BuiltinTypeSpec.Type.Short:
4580                         case BuiltinTypeSpec.Type.UShort:
4581                                 underlying_type = rc.BuiltinTypes.Int;
4582                                 break;
4583                         }
4584
4585                         if (expr.Type.IsNullableType || liftType)
4586                                 underlying_type = rc.Module.PredefinedTypes.Nullable.TypeSpec.MakeGenericType (rc.Module, new[] { underlying_type });
4587
4588                         if (expr.Type == underlying_type)
4589                                 return expr;
4590
4591                         return EmptyCast.Create (expr, underlying_type);
4592                 }
4593
4594                 Expression ResolveEnumOperators (ResolveContext rc, bool lenum, bool renum, TypeSpec ltype, TypeSpec rtype)
4595                 {
4596                         //
4597                         // U operator - (E e, E f)
4598                         // E operator - (E e, U x)  // Internal decomposition operator
4599                         // E operator - (U x, E e)      // Internal decomposition operator
4600                         //
4601                         // E operator + (E e, U x)
4602                         // E operator + (U x, E e)
4603                         //
4604
4605                         TypeSpec enum_type;
4606
4607                         if (lenum)
4608                                 enum_type = ltype;
4609                         else if (renum)
4610                                 enum_type = rtype;
4611                         else if (ltype.IsNullableType && Nullable.NullableInfo.GetUnderlyingType (ltype).IsEnum)
4612                                 enum_type = ltype;
4613                         else
4614                                 enum_type = rtype;
4615
4616                         Expression expr;
4617                         if (!enum_type.IsNullableType) {
4618                                 expr = ResolveOperatorPredefined (rc, rc.Module.GetPredefinedEnumAritmeticOperators (enum_type, false), false);
4619                                 if (expr != null) {
4620                                         if (oper == Operator.Subtraction)
4621                                                 expr = ConvertEnumSubtractionResult (rc, expr);
4622                                         else
4623                                                 expr = ConvertEnumAdditionalResult (expr, enum_type);
4624
4625                                         enum_conversion = GetEnumResultCast (expr.Type);
4626
4627                                         return expr;
4628                                 }
4629
4630                                 var nullable = rc.Module.PredefinedTypes.Nullable;
4631
4632                                 //
4633                                 // Don't try nullable version when nullable type is undefined
4634                                 //
4635                                 if (!nullable.IsDefined)
4636                                         return null;
4637
4638                                 enum_type = nullable.TypeSpec.MakeGenericType (rc.Module, new[] { enum_type });
4639                         }
4640
4641                         expr = ResolveOperatorPredefined (rc, rc.Module.GetPredefinedEnumAritmeticOperators (enum_type, true), false);
4642                         if (expr != null) {
4643                                 if (oper == Operator.Subtraction)
4644                                         expr = ConvertEnumSubtractionResult (rc, expr);
4645                                 else
4646                                         expr = ConvertEnumAdditionalResult (expr, enum_type);
4647
4648                                 enum_conversion = GetEnumResultCast (expr.Type);
4649                         }
4650
4651                         return expr;
4652                 }
4653
4654                 static Expression ConvertEnumAdditionalResult (Expression expr, TypeSpec enumType)
4655                 {
4656                         return EmptyCast.Create (expr, enumType);
4657                 }
4658
4659                 Expression ConvertEnumSubtractionResult (ResolveContext rc, Expression expr)
4660                 {
4661                         //
4662                         // Enumeration subtraction has different result type based on
4663                         // best overload
4664                         //
4665                         TypeSpec result_type;
4666                         if (left.Type == right.Type) {
4667                                 var c = right as EnumConstant;
4668                                 if (c != null && c.IsZeroInteger && !right.Type.IsEnum) {
4669                                         //
4670                                         // LAMESPEC: This is quite unexpected for expression E - 0 the return type is
4671                                         // E which is not what expressions E - 1 or 0 - E return
4672                                         //
4673                                         result_type = left.Type;
4674                                 } else {
4675                                         result_type = left.Type.IsNullableType ?
4676                                                 Nullable.NullableInfo.GetEnumUnderlyingType (rc.Module, left.Type) :
4677                                                 EnumSpec.GetUnderlyingType (left.Type);
4678                                 }
4679                         } else {
4680                                 if (IsEnumOrNullableEnum (left.Type)) {
4681                                         result_type = left.Type;
4682                                 } else {
4683                                         result_type = right.Type;
4684                                 }
4685
4686                                 if (expr is Nullable.LiftedBinaryOperator && !result_type.IsNullableType)
4687                                         result_type = rc.Module.PredefinedTypes.Nullable.TypeSpec.MakeGenericType (rc.Module, new[] { result_type });
4688                         }
4689
4690                         return EmptyCast.Create (expr, result_type);
4691                 }
4692
4693                 public static ConvCast.Mode GetEnumResultCast (TypeSpec type)
4694                 {
4695                         if (type.IsNullableType)
4696                                 type = Nullable.NullableInfo.GetUnderlyingType (type);
4697
4698                         if (type.IsEnum)
4699                                 type = EnumSpec.GetUnderlyingType (type);
4700
4701                         switch (type.BuiltinType) {
4702                         case BuiltinTypeSpec.Type.SByte:
4703                                 return ConvCast.Mode.I4_I1;
4704                         case BuiltinTypeSpec.Type.Byte:
4705                                 return ConvCast.Mode.I4_U1;
4706                         case BuiltinTypeSpec.Type.Short:
4707                                 return ConvCast.Mode.I4_I2;
4708                         case BuiltinTypeSpec.Type.UShort:
4709                                 return ConvCast.Mode.I4_U2;
4710                         }
4711
4712                         return 0;
4713                 }
4714
4715                 //
4716                 // Equality operators rules
4717                 //
4718                 Expression ResolveEquality (ResolveContext ec, TypeSpec l, TypeSpec r, bool primitives_only)
4719                 {
4720                         Expression result;
4721                         type = ec.BuiltinTypes.Bool;
4722                         bool no_arg_conv = false;
4723
4724                         if (!primitives_only) {
4725
4726                                 //
4727                                 // a, Both operands are reference-type values or the value null
4728                                 // b, One operand is a value of type T where T is a type-parameter and
4729                                 // the other operand is the value null. Furthermore T does not have the
4730                                 // value type constraint
4731                                 //
4732                                 // LAMESPEC: Very confusing details in the specification, basically any
4733                                 // reference like type-parameter is allowed
4734                                 //
4735                                 var tparam_l = l as TypeParameterSpec;
4736                                 var tparam_r = r as TypeParameterSpec;
4737                                 if (tparam_l != null) {
4738                                         if (right is NullLiteral) {
4739                                                 if (tparam_l.GetEffectiveBase ().BuiltinType == BuiltinTypeSpec.Type.ValueType)
4740                                                         return null;
4741
4742                                                 left = new BoxedCast (left, ec.BuiltinTypes.Object);
4743                                                 return this;
4744                                         }
4745
4746                                         if (!tparam_l.IsReferenceType)
4747                                                 return null;
4748
4749                                         l = tparam_l.GetEffectiveBase ();
4750                                         left = new BoxedCast (left, l);
4751                                 } else if (left is NullLiteral && tparam_r == null) {
4752                                         if (TypeSpec.IsReferenceType (r))
4753                                                 return this;
4754
4755                                         if (r.Kind == MemberKind.InternalCompilerType)
4756                                                 return null;
4757                                 }
4758
4759                                 if (tparam_r != null) {
4760                                         if (left is NullLiteral) {
4761                                                 if (tparam_r.GetEffectiveBase ().BuiltinType == BuiltinTypeSpec.Type.ValueType)
4762                                                         return null;
4763
4764                                                 right = new BoxedCast (right, ec.BuiltinTypes.Object);
4765                                                 return this;
4766                                         }
4767
4768                                         if (!tparam_r.IsReferenceType)
4769                                                 return null;
4770
4771                                         r = tparam_r.GetEffectiveBase ();
4772                                         right = new BoxedCast (right, r);
4773                                 } else if (right is NullLiteral) {
4774                                         if (TypeSpec.IsReferenceType (l))
4775                                                 return this;
4776
4777                                         if (l.Kind == MemberKind.InternalCompilerType)
4778                                                 return null;
4779                                 }
4780
4781                                 //
4782                                 // LAMESPEC: method groups can be compared when they convert to other side delegate
4783                                 //
4784                                 if (l.IsDelegate) {
4785                                         if (right.eclass == ExprClass.MethodGroup) {
4786                                                 result = Convert.ImplicitConversion (ec, right, l, loc);
4787                                                 if (result == null)
4788                                                         return null;
4789
4790                                                 right = result;
4791                                                 r = l;
4792                                         } else if (r.IsDelegate && l != r) {
4793                                                 return null;
4794                                         }
4795                                 } else if (left.eclass == ExprClass.MethodGroup && r.IsDelegate) {
4796                                         result = Convert.ImplicitConversionRequired (ec, left, r, loc);
4797                                         if (result == null)
4798                                                 return null;
4799
4800                                         left = result;
4801                                         l = r;
4802                                 } else {
4803                                         no_arg_conv = l == r && !l.IsStruct;
4804                                 }
4805                         }
4806
4807                         //
4808                         // bool operator != (string a, string b)
4809                         // bool operator == (string a, string b)
4810                         //
4811                         // bool operator != (Delegate a, Delegate b)
4812                         // bool operator == (Delegate a, Delegate b)
4813                         //
4814                         // bool operator != (bool a, bool b)
4815                         // bool operator == (bool a, bool b)
4816                         //
4817                         // LAMESPEC: Reference equality comparison can apply to value/reference types when
4818                         // they implement an implicit conversion to any of types above. This does
4819                         // not apply when both operands are of same reference type
4820                         //
4821                         if (r.BuiltinType != BuiltinTypeSpec.Type.Object && l.BuiltinType != BuiltinTypeSpec.Type.Object) {
4822                                 result = ResolveOperatorPredefined (ec, ec.BuiltinTypes.OperatorsBinaryEquality, no_arg_conv);  
4823                                 if (result != null)
4824                                         return result;
4825
4826                                 //
4827                                 // Now try lifted version of predefined operators
4828                                 //
4829                                 if (no_arg_conv && !l.IsNullableType) {
4830                                         //
4831                                         // Optimizes cases which won't match
4832                                         //
4833                                 } else {
4834                                         result = ResolveOperatorPredefined (ec, ec.Module.OperatorsBinaryEqualityLifted, no_arg_conv);
4835                                         if (result != null)
4836                                                 return result;
4837                                 }
4838
4839                                 //
4840                                 // The == and != operators permit one operand to be a value of a nullable
4841                                 // type and the other to be the null literal, even if no predefined or user-defined
4842                                 // operator (in unlifted or lifted form) exists for the operation.
4843                                 //
4844                                 if ((l.IsNullableType && right.IsNull) || (r.IsNullableType && left.IsNull)) {
4845                                         var lifted = new Nullable.LiftedBinaryOperator (this);
4846                                         lifted.Left = left;
4847                                         lifted.Right = right;
4848                                         return lifted.Resolve (ec);
4849                                 }
4850                         }
4851
4852                         //
4853                         // bool operator != (object a, object b)
4854                         // bool operator == (object a, object b)
4855                         //
4856                         // An explicit reference conversion exists from the
4857                         // type of either operand to the type of the other operand.
4858                         //
4859
4860                         // Optimize common path
4861                         if (l == r) {
4862                                 return l.Kind == MemberKind.InternalCompilerType || l.Kind == MemberKind.Struct ? null : this;
4863                         }
4864
4865                         if (!Convert.ExplicitReferenceConversionExists (l, r) &&
4866                                 !Convert.ExplicitReferenceConversionExists (r, l))
4867                                 return null;
4868
4869                         // Reject allowed explicit conversions like int->object
4870                         if (!TypeSpec.IsReferenceType (l) || !TypeSpec.IsReferenceType (r))
4871                                 return null;
4872
4873                         if (l.BuiltinType == BuiltinTypeSpec.Type.String || l.BuiltinType == BuiltinTypeSpec.Type.Delegate || l.IsDelegate || MemberCache.GetUserOperator (l, CSharp.Operator.OpType.Equality, false) != null)
4874                                 ec.Report.Warning (253, 2, loc,
4875                                         "Possible unintended reference comparison. Consider casting the right side expression to type `{0}' to get value comparison",
4876                                         l.GetSignatureForError ());
4877
4878                         if (r.BuiltinType == BuiltinTypeSpec.Type.String || r.BuiltinType == BuiltinTypeSpec.Type.Delegate || r.IsDelegate || MemberCache.GetUserOperator (r, CSharp.Operator.OpType.Equality, false) != null)
4879                                 ec.Report.Warning (252, 2, loc,
4880                                         "Possible unintended reference comparison. Consider casting the left side expression to type `{0}' to get value comparison",
4881                                         r.GetSignatureForError ());
4882
4883                         return this;
4884                 }
4885
4886
4887                 Expression ResolveOperatorPointer (ResolveContext ec, TypeSpec l, TypeSpec r)
4888                 {
4889                         //
4890                         // bool operator == (void* x, void* y);
4891                         // bool operator != (void* x, void* y);
4892                         // bool operator < (void* x, void* y);
4893                         // bool operator > (void* x, void* y);
4894                         // bool operator <= (void* x, void* y);
4895                         // bool operator >= (void* x, void* y);
4896                         //
4897                         if ((oper & Operator.ComparisonMask) != 0) {
4898                                 Expression temp;
4899                                 if (!l.IsPointer) {
4900                                         temp = Convert.ImplicitConversion (ec, left, r, left.Location);
4901                                         if (temp == null)
4902                                                 return null;
4903                                         left = temp;
4904                                 }
4905
4906                                 if (!r.IsPointer) {
4907                                         temp = Convert.ImplicitConversion (ec, right, l, right.Location);
4908                                         if (temp == null)
4909                                                 return null;
4910                                         right = temp;
4911                                 }
4912
4913                                 type = ec.BuiltinTypes.Bool;
4914                                 return this;
4915                         }
4916
4917                         return ResolveOperatorPredefined (ec, ec.BuiltinTypes.OperatorsBinaryUnsafe, false);
4918                 }
4919
4920                 //
4921                 // Build-in operators method overloading
4922                 //
4923                 Expression ResolveOperatorPredefined (ResolveContext ec, PredefinedOperator [] operators, bool primitives_only)
4924                 {
4925                         PredefinedOperator best_operator = null;
4926                         TypeSpec l = left.Type;
4927                         TypeSpec r = right.Type;
4928                         Operator oper_mask = oper & ~Operator.ValuesOnlyMask;
4929
4930                         foreach (PredefinedOperator po in operators) {
4931                                 if ((po.OperatorsMask & oper_mask) == 0)
4932                                         continue;
4933
4934                                 if (primitives_only) {
4935                                         if (!po.IsPrimitiveApplicable (l, r))
4936                                                 continue;
4937                                 } else {
4938                                         if (!po.IsApplicable (ec, left, right))
4939                                                 continue;
4940                                 }
4941
4942                                 if (best_operator == null) {
4943                                         best_operator = po;
4944                                         if (primitives_only)
4945                                                 break;
4946
4947                                         continue;
4948                                 }
4949
4950                                 best_operator = po.ResolveBetterOperator (ec, best_operator);
4951
4952                                 if (best_operator == null) {
4953                                         ec.Report.Error (34, loc, "Operator `{0}' is ambiguous on operands of type `{1}' and `{2}'",
4954                                                 OperName (oper), l.GetSignatureForError (), r.GetSignatureForError ());
4955
4956                                         best_operator = po;
4957                                         break;
4958                                 }
4959                         }
4960
4961                         if (best_operator == null)
4962                                 return null;
4963
4964                         return best_operator.ConvertResult (ec, this);
4965                 }
4966
4967                 //
4968                 // Optimize & constant expressions with 0 value
4969                 //
4970                 Expression OptimizeAndOperation (Expression expr)
4971                 {
4972                         Constant rc = right as Constant;
4973                         Constant lc = left as Constant;
4974                         if ((lc != null && lc.IsDefaultValue) || (rc != null && rc.IsDefaultValue)) {
4975                                 //
4976                                 // The result is a constant with side-effect
4977                                 //
4978                                 Constant side_effect = rc == null ?
4979                                         new SideEffectConstant (lc, right, loc) :
4980                                         new SideEffectConstant (rc, left, loc);
4981
4982                                 return ReducedExpression.Create (side_effect, expr);
4983                         }
4984
4985                         return expr;
4986                 }
4987
4988                 //
4989                 // Value types can be compared with the null literal because of the lifting
4990                 // language rules. However the result is always true or false.
4991                 //
4992                 public Expression CreateLiftedValueTypeResult (ResolveContext rc, TypeSpec valueType)
4993                 {
4994                         if (rc.HasSet (ResolveContext.Options.ExpressionTreeConversion)) {
4995                                 type = rc.BuiltinTypes.Bool;
4996                                 return this;
4997                         }
4998
4999                         // FIXME: Handle side effect constants
5000                         Constant c = new BoolConstant (rc.BuiltinTypes, Oper == Operator.Inequality, loc);
5001
5002                         if ((Oper & Operator.EqualityMask) != 0) {
5003                                 rc.Report.Warning (472, 2, loc, "The result of comparing value type `{0}' with null is always `{1}'",
5004                                         valueType.GetSignatureForError (), c.GetValueAsLiteral ());
5005                         } else {
5006                                 rc.Report.Warning (464, 2, loc, "The result of comparing type `{0}' with null is always `{1}'",
5007                                         valueType.GetSignatureForError (), c.GetValueAsLiteral ());
5008                         }
5009
5010                         return c;
5011                 }
5012
5013                 //
5014                 // Performs user-operator overloading
5015                 //
5016                 Expression ResolveUserOperator (ResolveContext rc, Expression left, Expression right)
5017                 {
5018                         Expression oper_expr;
5019
5020                         var op = ConvertBinaryToUserOperator (oper);
5021                         var l = left.Type;
5022                         if (l.IsNullableType)
5023                                 l = Nullable.NullableInfo.GetUnderlyingType (l);
5024                         var r = right.Type;
5025                         if (r.IsNullableType)
5026                                 r = Nullable.NullableInfo.GetUnderlyingType (r);
5027
5028                         IList<MemberSpec> left_operators = MemberCache.GetUserOperator (l, op, false);
5029                         IList<MemberSpec> right_operators = null;
5030
5031                         if (l != r) {
5032                                 right_operators = MemberCache.GetUserOperator (r, op, false);
5033                                 if (right_operators == null && left_operators == null)
5034                                         return null;
5035                         } else if (left_operators == null) {
5036                                 return null;
5037                         }
5038
5039                         Arguments args = new Arguments (2);
5040                         Argument larg = new Argument (left);
5041                         args.Add (larg);        
5042                         Argument rarg = new Argument (right);
5043                         args.Add (rarg);
5044
5045                         //
5046                         // User-defined operator implementations always take precedence
5047                         // over predefined operator implementations
5048                         //
5049                         if (left_operators != null && right_operators != null) {
5050                                 left_operators = CombineUserOperators (left_operators, right_operators);
5051                         } else if (right_operators != null) {
5052                                 left_operators = right_operators;
5053                         }
5054
5055                         const OverloadResolver.Restrictions restr = OverloadResolver.Restrictions.ProbingOnly |
5056                                 OverloadResolver.Restrictions.NoBaseMembers | OverloadResolver.Restrictions.BaseMembersIncluded;
5057
5058                         var res = new OverloadResolver (left_operators, restr, loc);
5059
5060                         var oper_method = res.ResolveOperator (rc, ref args);
5061                         if (oper_method == null) {
5062                                 //
5063                                 // Logical && and || cannot be lifted
5064                                 //
5065                                 if ((oper & Operator.LogicalMask) != 0)
5066                                         return null;
5067
5068                                 //
5069                                 // Apply lifted user operators only for liftable types. Implicit conversion
5070                                 // to nullable types is not allowed
5071                                 //
5072                                 if (!IsLiftedOperatorApplicable ())
5073                                         return null;
5074
5075                                 // TODO: Cache the result in module container
5076                                 var lifted_methods = CreateLiftedOperators (rc, left_operators);
5077                                 if (lifted_methods == null)
5078                                         return null;
5079
5080                                 res = new OverloadResolver (lifted_methods, restr | OverloadResolver.Restrictions.ProbingOnly, loc);
5081
5082                                 oper_method = res.ResolveOperator (rc, ref args);
5083                                 if (oper_method == null)
5084                                         return null;
5085
5086                                 MethodSpec best_original = null;
5087                                 foreach (MethodSpec ms in left_operators) {
5088                                         if (ms.MemberDefinition == oper_method.MemberDefinition) {
5089                                                 best_original = ms;
5090                                                 break;
5091                                         }
5092                                 }
5093
5094                                 if (rc.HasSet (ResolveContext.Options.ExpressionTreeConversion)) {
5095                                         //
5096                                         // Expression trees use lifted notation in this case
5097                                         //
5098                                         this.left = Convert.ImplicitConversion (rc, left, oper_method.Parameters.Types[0], left.Location);
5099                                         this.right = Convert.ImplicitConversion (rc, right, oper_method.Parameters.Types[1], left.Location);
5100                                 }
5101
5102                                 var ptypes = best_original.Parameters.Types;
5103
5104                                 if (left.IsNull || right.IsNull) {
5105                                         //
5106                                         // The lifted operator produces a null value if one or both operands are null
5107                                         //
5108                                         if ((oper & (Operator.ArithmeticMask | Operator.ShiftMask | Operator.BitwiseMask)) != 0) {
5109                                                 type = oper_method.ReturnType;
5110                                                 return Nullable.LiftedNull.CreateFromExpression (rc, this);
5111                                         }
5112
5113                                         //
5114                                         // The lifted operator produces the value false if one or both operands are null for
5115                                         // relational operators.
5116                                         //
5117                                         if ((oper & Operator.RelationalMask) != 0) {
5118                                                 //
5119                                                 // CSC BUG: This should be different warning, csc reports CS0458 with bool? which is wrong
5120                                                 // because return type is actually bool
5121                                                 //
5122                                                 return CreateLiftedValueTypeResult (rc, left.IsNull ? ptypes [1] : ptypes [0]);
5123                                         }
5124
5125                                         if ((oper & Operator.EqualityMask) != 0 && ((left.IsNull && !right.Type.IsNullableType) || !left.Type.IsNullableType)) {
5126                                                 return CreateLiftedValueTypeResult (rc, left.IsNull ? ptypes [1] : ptypes [0]);
5127                                         }
5128                                 }
5129
5130                                 type = oper_method.ReturnType;
5131                                 var lifted = new Nullable.LiftedBinaryOperator (this);
5132                                 lifted.UserOperator = best_original;
5133
5134                                 if (left.Type.IsNullableType && !ptypes[0].IsNullableType) {
5135                                         lifted.UnwrapLeft = new Nullable.Unwrap (left);
5136                                 }
5137
5138                                 if (right.Type.IsNullableType && !ptypes[1].IsNullableType) {
5139                                         lifted.UnwrapRight = new Nullable.Unwrap (right);
5140                                 }
5141
5142                                 lifted.Left = Convert.ImplicitConversion (rc, lifted.UnwrapLeft ?? left, ptypes[0], left.Location);
5143                                 lifted.Right = Convert.ImplicitConversion (rc, lifted.UnwrapRight ?? right, ptypes[1], right.Location);
5144
5145                                 return lifted.Resolve (rc);
5146                         }
5147                         
5148                         if ((oper & Operator.LogicalMask) != 0) {
5149                                 // TODO: CreateExpressionTree is allocated every time           
5150                                 oper_expr = new ConditionalLogicalOperator (oper_method, args, CreateExpressionTree,
5151                                         oper == Operator.LogicalAnd, loc).Resolve (rc);
5152                         } else {
5153                                 oper_expr = new UserOperatorCall (oper_method, args, CreateExpressionTree, loc);
5154                         }
5155
5156                         this.left = larg.Expr;
5157                         this.right = rarg.Expr;
5158
5159                         return oper_expr;
5160                 }
5161
5162                 bool IsLiftedOperatorApplicable ()
5163                 {
5164                         if (left.Type.IsNullableType) {
5165                                 if ((oper & Operator.EqualityMask) != 0)
5166                                         return !right.IsNull;
5167
5168                                 return true;
5169                         }
5170
5171                         if (right.Type.IsNullableType) {
5172                                 if ((oper & Operator.EqualityMask) != 0)
5173                                         return !left.IsNull;
5174
5175                                 return true;
5176                         }
5177
5178                         if (TypeSpec.IsValueType (left.Type))
5179                                 return right.IsNull;
5180
5181                         if (TypeSpec.IsValueType (right.Type))
5182                                 return left.IsNull;
5183
5184                         return false;
5185                 }
5186
5187                 List<MemberSpec> CreateLiftedOperators (ResolveContext rc, IList<MemberSpec> operators)
5188                 {
5189                         var nullable_type = rc.Module.PredefinedTypes.Nullable.TypeSpec;
5190                         if (nullable_type == null)
5191                                 return null;
5192
5193                         //
5194                         // Lifted operators permit predefined and user-defined operators that operate
5195                         // on non-nullable value types to also be used with nullable forms of those types.
5196                         // Lifted operators are constructed from predefined and user-defined operators
5197                         // that meet certain requirements
5198                         //
5199                         List<MemberSpec> lifted = null;
5200                         foreach (MethodSpec oper in operators) {
5201                                 TypeSpec rt;
5202                                 if ((Oper & Operator.ComparisonMask) != 0) {
5203                                         //
5204                                         // Result type must be of type bool for lifted comparison operators
5205                                         //
5206                                         rt = oper.ReturnType;
5207                                         if (rt.BuiltinType != BuiltinTypeSpec.Type.Bool)
5208                                                 continue;
5209                                 } else {
5210                                         if (!TypeSpec.IsNonNullableValueType (oper.ReturnType))
5211                                                 continue;
5212
5213                                         rt = null;
5214                                 }
5215
5216                                 var ptypes = oper.Parameters.Types;
5217                                 if (!TypeSpec.IsNonNullableValueType (ptypes [0]) || !TypeSpec.IsNonNullableValueType (ptypes [1]))
5218                                         continue;
5219
5220                                 //
5221                                 // LAMESPEC: I am not sure why but for equality operators to be lifted
5222                                 // both types have to match
5223                                 //
5224                                 if ((Oper & Operator.EqualityMask) != 0 && ptypes [0] != ptypes [1])
5225                                         continue;
5226
5227                                 if (lifted == null)
5228                                         lifted = new List<MemberSpec> ();
5229
5230                                 //
5231                                 // The lifted form is constructed by adding a single ? modifier to each operand and
5232                                 // result type except for comparison operators where return type is bool
5233                                 //
5234                                 if (rt == null)
5235                                         rt = nullable_type.MakeGenericType (rc.Module, new[] { oper.ReturnType });
5236
5237                                 var parameters = ParametersCompiled.CreateFullyResolved (
5238                                         nullable_type.MakeGenericType (rc.Module, new [] { ptypes[0] }),
5239                                         nullable_type.MakeGenericType (rc.Module, new [] { ptypes[1] }));
5240
5241                                 var lifted_op = new MethodSpec (oper.Kind, oper.DeclaringType, oper.MemberDefinition,
5242                                         rt, parameters, oper.Modifiers);
5243
5244                                 lifted.Add (lifted_op);
5245                         }
5246
5247                         return lifted;
5248                 }
5249
5250                 //
5251                 // Merge two sets of user operators into one, they are mostly distinguish
5252                 // except when they share base type and it contains an operator
5253                 //
5254                 static IList<MemberSpec> CombineUserOperators (IList<MemberSpec> left, IList<MemberSpec> right)
5255                 {
5256                         var combined = new List<MemberSpec> (left.Count + right.Count);
5257                         combined.AddRange (left);
5258                         foreach (var r in right) {
5259                                 bool same = false;
5260                                 foreach (var l in left) {
5261                                         if (l.DeclaringType == r.DeclaringType) {
5262                                                 same = true;
5263                                                 break;
5264                                         }
5265                                 }
5266
5267                                 if (!same)
5268                                         combined.Add (r);
5269                         }
5270
5271                         return combined;
5272                 }
5273
5274                 void CheckOutOfRangeComparison (ResolveContext ec, Constant c, TypeSpec type)
5275                 {
5276                         if (c is IntegralConstant || c is CharConstant) {
5277                                 try {
5278                                         c.ConvertExplicitly (true, type);
5279                                 } catch (OverflowException) {
5280                                         ec.Report.Warning (652, 2, loc,
5281                                                 "A comparison between a constant and a variable is useless. The constant is out of the range of the variable type `{0}'",
5282                                                 type.GetSignatureForError ());
5283                                 }
5284                         }
5285                 }
5286
5287                 /// <remarks>
5288                 ///   EmitBranchable is called from Statement.EmitBoolExpression in the
5289                 ///   context of a conditional bool expression.  This function will return
5290                 ///   false if it is was possible to use EmitBranchable, or true if it was.
5291                 ///
5292                 ///   The expression's code is generated, and we will generate a branch to `target'
5293                 ///   if the resulting expression value is equal to isTrue
5294                 /// </remarks>
5295                 public override void EmitBranchable (EmitContext ec, Label target, bool on_true)
5296                 {
5297                         if (ec.HasSet (BuilderContext.Options.AsyncBody) && right.ContainsEmitWithAwait ()) {
5298                                 left = left.EmitToField (ec);
5299
5300                                 if ((oper & Operator.LogicalMask) == 0) {
5301                                         right = right.EmitToField (ec);
5302                                 }
5303                         }
5304
5305                         //
5306                         // This is more complicated than it looks, but its just to avoid
5307                         // duplicated tests: basically, we allow ==, !=, >, <, >= and <=
5308                         // but on top of that we want for == and != to use a special path
5309                         // if we are comparing against null
5310                         //
5311                         if ((oper & Operator.EqualityMask) != 0 && (left is Constant || right is Constant)) {
5312                                 bool my_on_true = oper == Operator.Inequality ? on_true : !on_true;
5313                                 
5314                                 //
5315                                 // put the constant on the rhs, for simplicity
5316                                 //
5317                                 if (left is Constant) {
5318                                         Expression swap = right;
5319                                         right = left;
5320                                         left = swap;
5321                                 }
5322                                 
5323                                 //
5324                                 // brtrue/brfalse works with native int only
5325                                 //
5326                                 if (((Constant) right).IsZeroInteger && right.Type.BuiltinType != BuiltinTypeSpec.Type.Long && right.Type.BuiltinType != BuiltinTypeSpec.Type.ULong) {
5327                                         left.EmitBranchable (ec, target, my_on_true);
5328                                         return;
5329                                 }
5330                                 if (right.Type.BuiltinType == BuiltinTypeSpec.Type.Bool) {
5331                                         // right is a boolean, and it's not 'false' => it is 'true'
5332                                         left.EmitBranchable (ec, target, !my_on_true);
5333                                         return;
5334                                 }
5335
5336                         } else if (oper == Operator.LogicalAnd) {
5337
5338                                 if (on_true) {
5339                                         Label tests_end = ec.DefineLabel ();
5340                                         
5341                                         left.EmitBranchable (ec, tests_end, false);
5342                                         right.EmitBranchable (ec, target, true);
5343                                         ec.MarkLabel (tests_end);                                       
5344                                 } else {
5345                                         //
5346                                         // This optimizes code like this 
5347                                         // if (true && i > 4)
5348                                         //
5349                                         if (!(left is Constant))
5350                                                 left.EmitBranchable (ec, target, false);
5351
5352                                         if (!(right is Constant)) 
5353                                                 right.EmitBranchable (ec, target, false);
5354                                 }
5355                                 
5356                                 return;
5357                                 
5358                         } else if (oper == Operator.LogicalOr){
5359                                 if (on_true) {
5360                                         left.EmitBranchable (ec, target, true);
5361                                         right.EmitBranchable (ec, target, true);
5362                                         
5363                                 } else {
5364                                         Label tests_end = ec.DefineLabel ();
5365                                         left.EmitBranchable (ec, tests_end, true);
5366                                         right.EmitBranchable (ec, target, false);
5367                                         ec.MarkLabel (tests_end);
5368                                 }
5369                                 
5370                                 return;
5371
5372                         } else if ((oper & Operator.ComparisonMask) == 0) {
5373                                 base.EmitBranchable (ec, target, on_true);
5374                                 return;
5375                         }
5376                         
5377                         left.Emit (ec);
5378                         right.Emit (ec);
5379
5380                         TypeSpec t = left.Type;
5381                         bool is_float = IsFloat (t);
5382                         bool is_unsigned = is_float || IsUnsigned (t);
5383                         
5384                         switch (oper){
5385                         case Operator.Equality:
5386                                 if (on_true)
5387                                         ec.Emit (OpCodes.Beq, target);
5388                                 else
5389                                         ec.Emit (OpCodes.Bne_Un, target);
5390                                 break;
5391
5392                         case Operator.Inequality:
5393                                 if (on_true)
5394                                         ec.Emit (OpCodes.Bne_Un, target);
5395                                 else
5396                                         ec.Emit (OpCodes.Beq, target);
5397                                 break;
5398
5399                         case Operator.LessThan:
5400                                 if (on_true)
5401                                         if (is_unsigned && !is_float)
5402                                                 ec.Emit (OpCodes.Blt_Un, target);
5403                                         else
5404                                                 ec.Emit (OpCodes.Blt, target);
5405                                 else
5406                                         if (is_unsigned)
5407                                                 ec.Emit (OpCodes.Bge_Un, target);
5408                                         else
5409                                                 ec.Emit (OpCodes.Bge, target);
5410                                 break;
5411
5412                         case Operator.GreaterThan:
5413                                 if (on_true)
5414                                         if (is_unsigned && !is_float)
5415                                                 ec.Emit (OpCodes.Bgt_Un, target);
5416                                         else
5417                                                 ec.Emit (OpCodes.Bgt, target);
5418                                 else
5419                                         if (is_unsigned)
5420                                                 ec.Emit (OpCodes.Ble_Un, target);
5421                                         else
5422                                                 ec.Emit (OpCodes.Ble, target);
5423                                 break;
5424
5425                         case Operator.LessThanOrEqual:
5426                                 if (on_true)
5427                                         if (is_unsigned && !is_float)
5428                                                 ec.Emit (OpCodes.Ble_Un, target);
5429                                         else
5430                                                 ec.Emit (OpCodes.Ble, target);
5431                                 else
5432                                         if (is_unsigned)
5433                                                 ec.Emit (OpCodes.Bgt_Un, target);
5434                                         else
5435                                                 ec.Emit (OpCodes.Bgt, target);
5436                                 break;
5437
5438
5439                         case Operator.GreaterThanOrEqual:
5440                                 if (on_true)
5441                                         if (is_unsigned && !is_float)
5442                                                 ec.Emit (OpCodes.Bge_Un, target);
5443                                         else
5444                                                 ec.Emit (OpCodes.Bge, target);
5445                                 else
5446                                         if (is_unsigned)
5447                                                 ec.Emit (OpCodes.Blt_Un, target);
5448                                         else
5449                                                 ec.Emit (OpCodes.Blt, target);
5450                                 break;
5451                         default:
5452                                 throw new InternalErrorException (oper.ToString ());
5453                         }
5454                 }
5455                 
5456                 public override void Emit (EmitContext ec)
5457                 {
5458                         if (ec.HasSet (BuilderContext.Options.AsyncBody) && right.ContainsEmitWithAwait ()) {
5459                                 left = left.EmitToField (ec);
5460
5461                                 if ((oper & Operator.LogicalMask) == 0) {
5462                                         right = right.EmitToField (ec);
5463                                 }
5464                         }
5465
5466                         //
5467                         // Handle short-circuit operators differently
5468                         // than the rest
5469                         //
5470                         if ((oper & Operator.LogicalMask) != 0) {
5471                                 Label load_result = ec.DefineLabel ();
5472                                 Label end = ec.DefineLabel ();
5473
5474                                 bool is_or = oper == Operator.LogicalOr;
5475                                 left.EmitBranchable (ec, load_result, is_or);
5476                                 right.Emit (ec);
5477                                 ec.Emit (OpCodes.Br_S, end);
5478                                 
5479                                 ec.MarkLabel (load_result);
5480                                 ec.EmitInt (is_or ? 1 : 0);
5481                                 ec.MarkLabel (end);
5482                                 return;
5483                         }
5484
5485                         //
5486                         // Optimize zero-based operations which cannot be optimized at expression level
5487                         //
5488                         if (oper == Operator.Subtraction) {
5489                                 var lc = left as IntegralConstant;
5490                                 if (lc != null && lc.IsDefaultValue) {
5491                                         right.Emit (ec);
5492                                         ec.Emit (OpCodes.Neg);
5493                                         return;
5494                                 }
5495                         }
5496
5497                         EmitOperator (ec, left, right);
5498                 }
5499
5500                 public void EmitOperator (EmitContext ec, Expression left, Expression right)
5501                 {
5502                         left.Emit (ec);
5503                         right.Emit (ec);
5504
5505                         EmitOperatorOpcode (ec, oper, left.Type, right);
5506
5507                         //
5508                         // Emit result enumerable conversion this way because it's quite complicated get it
5509                         // to resolved tree because expression tree cannot see it.
5510                         //
5511                         if (enum_conversion != 0)
5512                                 ConvCast.Emit (ec, enum_conversion);
5513                 }
5514
5515                 public override void EmitSideEffect (EmitContext ec)
5516                 {
5517                         if ((oper & Operator.LogicalMask) != 0 ||
5518                                 (ec.HasSet (EmitContext.Options.CheckedScope) && (oper == Operator.Multiply || oper == Operator.Addition || oper == Operator.Subtraction))) {
5519                                 base.EmitSideEffect (ec);
5520                         } else {
5521                                 left.EmitSideEffect (ec);
5522                                 right.EmitSideEffect (ec);
5523                         }
5524                 }
5525
5526                 public override Expression EmitToField (EmitContext ec)
5527                 {
5528                         if ((oper & Operator.LogicalMask) == 0) {
5529                                 var await_expr = left as Await;
5530                                 if (await_expr != null && right.IsSideEffectFree) {
5531                                         await_expr.Statement.EmitPrologue (ec);
5532                                         left = await_expr.Statement.GetResultExpression (ec);
5533                                         return this;
5534                                 }
5535
5536                                 await_expr = right as Await;
5537                                 if (await_expr != null && left.IsSideEffectFree) {
5538                                         await_expr.Statement.EmitPrologue (ec);
5539                                         right = await_expr.Statement.GetResultExpression (ec);
5540                                         return this;
5541                                 }
5542                         }
5543
5544                         return base.EmitToField (ec);
5545                 }
5546
5547                 protected override void CloneTo (CloneContext clonectx, Expression t)
5548                 {
5549                         Binary target = (Binary) t;
5550
5551                         target.left = left.Clone (clonectx);
5552                         target.right = right.Clone (clonectx);
5553                 }
5554
5555                 public Expression CreateCallSiteBinder (ResolveContext ec, Arguments args)
5556                 {
5557                         Arguments binder_args = new Arguments (4);
5558
5559                         MemberAccess sle = new MemberAccess (new MemberAccess (
5560                                 new QualifiedAliasMember (QualifiedAliasMember.GlobalAlias, "System", loc), "Linq", loc), "Expressions", loc);
5561
5562                         CSharpBinderFlags flags = 0;
5563                         if (ec.HasSet (ResolveContext.Options.CheckedScope))
5564                                 flags = CSharpBinderFlags.CheckedContext;
5565
5566                         if ((oper & Operator.LogicalMask) != 0)
5567                                 flags |= CSharpBinderFlags.BinaryOperationLogical;
5568
5569                         binder_args.Add (new Argument (new EnumConstant (new IntLiteral (ec.BuiltinTypes, (int) flags, loc), ec.Module.PredefinedTypes.BinderFlags.Resolve ())));
5570                         binder_args.Add (new Argument (new MemberAccess (new MemberAccess (sle, "ExpressionType", loc), GetOperatorExpressionTypeName (), loc)));
5571                         binder_args.Add (new Argument (new TypeOf (ec.CurrentType, loc)));                                                                      
5572                         binder_args.Add (new Argument (new ImplicitlyTypedArrayCreation (args.CreateDynamicBinderArguments (ec), loc)));
5573
5574                         return new Invocation (new MemberAccess (new TypeExpression (ec.Module.PredefinedTypes.Binder.TypeSpec, loc), "BinaryOperation", loc), binder_args);
5575                 }
5576                 
5577                 public override Expression CreateExpressionTree (ResolveContext ec)
5578                 {
5579                         return CreateExpressionTree (ec, null);
5580                 }
5581
5582                 public Expression CreateExpressionTree (ResolveContext ec, Expression method)           
5583                 {
5584                         string method_name;
5585                         bool lift_arg = false;
5586                         
5587                         switch (oper) {
5588                         case Operator.Addition:
5589                                 if (method == null && ec.HasSet (ResolveContext.Options.CheckedScope) && !IsFloat (type))
5590                                         method_name = "AddChecked";
5591                                 else
5592                                         method_name = "Add";
5593                                 break;
5594                         case Operator.BitwiseAnd:
5595                                 method_name = "And";
5596                                 break;
5597                         case Operator.BitwiseOr:
5598                                 method_name = "Or";
5599                                 break;
5600                         case Operator.Division:
5601                                 method_name = "Divide";
5602                                 break;
5603                         case Operator.Equality:
5604                                 method_name = "Equal";
5605                                 lift_arg = true;
5606                                 break;
5607                         case Operator.ExclusiveOr:
5608                                 method_name = "ExclusiveOr";
5609                                 break;                          
5610                         case Operator.GreaterThan:
5611                                 method_name = "GreaterThan";
5612                                 lift_arg = true;
5613                                 break;
5614                         case Operator.GreaterThanOrEqual:
5615                                 method_name = "GreaterThanOrEqual";
5616                                 lift_arg = true;
5617                                 break;
5618                         case Operator.Inequality:
5619                                 method_name = "NotEqual";
5620                                 lift_arg = true;
5621                                 break;
5622                         case Operator.LeftShift:
5623                                 method_name = "LeftShift";
5624                                 break;
5625                         case Operator.LessThan:
5626                                 method_name = "LessThan";
5627                                 lift_arg = true;
5628                                 break;
5629                         case Operator.LessThanOrEqual:
5630                                 method_name = "LessThanOrEqual";
5631                                 lift_arg = true;
5632                                 break;
5633                         case Operator.LogicalAnd:
5634                                 method_name = "AndAlso";
5635                                 break;
5636                         case Operator.LogicalOr:
5637                                 method_name = "OrElse";
5638                                 break;
5639                         case Operator.Modulus:
5640                                 method_name = "Modulo";
5641                                 break;
5642                         case Operator.Multiply:
5643                                 if (method == null && ec.HasSet (ResolveContext.Options.CheckedScope) && !IsFloat (type))
5644                                         method_name = "MultiplyChecked";
5645                                 else
5646                                         method_name = "Multiply";
5647                                 break;
5648                         case Operator.RightShift:
5649                                 method_name = "RightShift";
5650                                 break;
5651                         case Operator.Subtraction:
5652                                 if (method == null && ec.HasSet (ResolveContext.Options.CheckedScope) && !IsFloat (type))
5653                                         method_name = "SubtractChecked";
5654                                 else
5655                                         method_name = "Subtract";
5656                                 break;
5657
5658                         default:
5659                                 throw new InternalErrorException ("Unknown expression tree binary operator " + oper);
5660                         }
5661
5662                         Arguments args = new Arguments (2);
5663                         args.Add (new Argument (left.CreateExpressionTree (ec)));
5664                         args.Add (new Argument (right.CreateExpressionTree (ec)));
5665                         if (method != null) {
5666                                 if (lift_arg)
5667                                         args.Add (new Argument (new BoolLiteral (ec.BuiltinTypes, false, loc)));
5668
5669                                 args.Add (new Argument (method));
5670                         }
5671                         
5672                         return CreateExpressionFactoryCall (ec, method_name, args);
5673                 }
5674                 
5675                 public override object Accept (StructuralVisitor visitor)
5676                 {
5677                         return visitor.Visit (this);
5678                 }
5679
5680         }
5681         
5682         //
5683         // Represents the operation a + b [+ c [+ d [+ ...]]], where a is a string
5684         // b, c, d... may be strings or objects.
5685         //
5686         public class StringConcat : Expression
5687         {
5688                 Arguments arguments;
5689                 
5690                 StringConcat (Location loc)
5691                 {
5692                         this.loc = loc;
5693                         arguments = new Arguments (2);
5694                 }
5695
5696                 public override bool ContainsEmitWithAwait ()
5697                 {
5698                         return arguments.ContainsEmitWithAwait ();
5699                 }
5700
5701                 public static StringConcat Create (ResolveContext rc, Expression left, Expression right, Location loc)
5702                 {
5703                         if (left.eclass == ExprClass.Unresolved || right.eclass == ExprClass.Unresolved)
5704                                 throw new ArgumentException ();
5705
5706                         var s = new StringConcat (loc);
5707                         s.type = rc.BuiltinTypes.String;
5708                         s.eclass = ExprClass.Value;
5709
5710                         s.Append (rc, left);
5711                         s.Append (rc, right);
5712                         return s;
5713                 }
5714
5715                 public override Expression CreateExpressionTree (ResolveContext ec)
5716                 {
5717                         Argument arg = arguments [0];
5718                         return CreateExpressionAddCall (ec, arg, arg.CreateExpressionTree (ec), 1);
5719                 }
5720
5721                 //
5722                 // Creates nested calls tree from an array of arguments used for IL emit
5723                 //
5724                 Expression CreateExpressionAddCall (ResolveContext ec, Argument left, Expression left_etree, int pos)
5725                 {
5726                         Arguments concat_args = new Arguments (2);
5727                         Arguments add_args = new Arguments (3);
5728
5729                         concat_args.Add (left);
5730                         add_args.Add (new Argument (left_etree));
5731
5732                         concat_args.Add (arguments [pos]);
5733                         add_args.Add (new Argument (arguments [pos].CreateExpressionTree (ec)));
5734
5735                         var methods = GetConcatMethodCandidates ();
5736                         if (methods == null)
5737                                 return null;
5738
5739                         var res = new OverloadResolver (methods, OverloadResolver.Restrictions.NoBaseMembers, loc);
5740                         var method = res.ResolveMember<MethodSpec> (ec, ref concat_args);
5741                         if (method == null)
5742                                 return null;
5743
5744                         add_args.Add (new Argument (new TypeOfMethod (method, loc)));
5745
5746                         Expression expr = CreateExpressionFactoryCall (ec, "Add", add_args);
5747                         if (++pos == arguments.Count)
5748                                 return expr;
5749
5750                         left = new Argument (new EmptyExpression (method.ReturnType));
5751                         return CreateExpressionAddCall (ec, left, expr, pos);
5752                 }
5753
5754                 protected override Expression DoResolve (ResolveContext ec)
5755                 {
5756                         return this;
5757                 }
5758                 
5759                 void Append (ResolveContext rc, Expression operand)
5760                 {
5761                         //
5762                         // Constant folding
5763                         //
5764                         StringConstant sc = operand as StringConstant;
5765                         if (sc != null) {
5766                                 if (arguments.Count != 0) {
5767                                         Argument last_argument = arguments [arguments.Count - 1];
5768                                         StringConstant last_expr_constant = last_argument.Expr as StringConstant;
5769                                         if (last_expr_constant != null) {
5770                                                 last_argument.Expr = new StringConstant (rc.BuiltinTypes, last_expr_constant.Value + sc.Value, sc.Location);
5771                                                 return;
5772                                         }
5773                                 }
5774                         } else {
5775                                 //
5776                                 // Multiple (3+) concatenation are resolved as multiple StringConcat instances
5777                                 //
5778                                 StringConcat concat_oper = operand as StringConcat;
5779                                 if (concat_oper != null) {
5780                                         arguments.AddRange (concat_oper.arguments);
5781                                         return;
5782                                 }
5783                         }
5784
5785                         arguments.Add (new Argument (operand));
5786                 }
5787
5788                 IList<MemberSpec> GetConcatMethodCandidates ()
5789                 {
5790                         return MemberCache.FindMembers (type, "Concat", true);
5791                 }
5792
5793                 public override void Emit (EmitContext ec)
5794                 {
5795                         // Optimize by removing any extra null arguments, they are no-op
5796                         for (int i = 0; i < arguments.Count; ++i) {
5797                                 if (arguments[i].Expr is NullConstant)
5798                                         arguments.RemoveAt (i--);
5799                         }
5800
5801                         var members = GetConcatMethodCandidates ();
5802                         var res = new OverloadResolver (members, OverloadResolver.Restrictions.NoBaseMembers, loc);
5803                         var method = res.ResolveMember<MethodSpec> (new ResolveContext (ec.MemberContext), ref arguments);
5804                         if (method != null) {
5805                                 var call = new CallEmitter ();
5806                                 call.EmitPredefined (ec, method, arguments, false);
5807                         }
5808                 }
5809
5810                 public override void FlowAnalysis (FlowAnalysisContext fc)
5811                 {
5812                         arguments.FlowAnalysis (fc);
5813                 }
5814
5815                 public override SLE.Expression MakeExpression (BuilderContext ctx)
5816                 {
5817                         if (arguments.Count != 2)
5818                                 throw new NotImplementedException ("arguments.Count != 2");
5819
5820                         var concat = typeof (string).GetMethod ("Concat", new[] { typeof (object), typeof (object) });
5821                         return SLE.Expression.Add (arguments[0].Expr.MakeExpression (ctx), arguments[1].Expr.MakeExpression (ctx), concat);
5822                 }
5823         }
5824
5825         //
5826         // User-defined conditional logical operator
5827         //
5828         public class ConditionalLogicalOperator : UserOperatorCall
5829         {
5830                 readonly bool is_and;
5831                 Expression oper_expr;
5832
5833                 public ConditionalLogicalOperator (MethodSpec oper, Arguments arguments, Func<ResolveContext, Expression, Expression> expr_tree, bool is_and, Location loc)
5834                         : base (oper, arguments, expr_tree, loc)
5835                 {
5836                         this.is_and = is_and;
5837                         eclass = ExprClass.Unresolved;
5838                 }
5839                 
5840                 protected override Expression DoResolve (ResolveContext ec)
5841                 {
5842                         AParametersCollection pd = oper.Parameters;
5843                         if (!TypeSpecComparer.IsEqual (type, pd.Types[0]) || !TypeSpecComparer.IsEqual (type, pd.Types[1])) {
5844                                 ec.Report.Error (217, loc,
5845                                         "A user-defined operator `{0}' must have each parameter type and return type of the same type in order to be applicable as a short circuit operator",
5846                                         oper.GetSignatureForError ());
5847                                 return null;
5848                         }
5849
5850                         Expression left_dup = new EmptyExpression (type);
5851                         Expression op_true = GetOperatorTrue (ec, left_dup, loc);
5852                         Expression op_false = GetOperatorFalse (ec, left_dup, loc);
5853                         if (op_true == null || op_false == null) {
5854                                 ec.Report.Error (218, loc,
5855                                         "The type `{0}' must have operator `true' and operator `false' defined when `{1}' is used as a short circuit operator",
5856                                         type.GetSignatureForError (), oper.GetSignatureForError ());
5857                                 return null;
5858                         }
5859
5860                         oper_expr = is_and ? op_false : op_true;
5861                         eclass = ExprClass.Value;
5862                         return this;
5863                 }
5864
5865                 public override void Emit (EmitContext ec)
5866                 {
5867                         Label end_target = ec.DefineLabel ();
5868
5869                         //
5870                         // Emit and duplicate left argument
5871                         //
5872                         bool right_contains_await = ec.HasSet (BuilderContext.Options.AsyncBody) && arguments[1].Expr.ContainsEmitWithAwait ();
5873                         if (right_contains_await) {
5874                                 arguments[0] = arguments[0].EmitToField (ec, false);
5875                                 arguments[0].Expr.Emit (ec);
5876                         } else {
5877                                 arguments[0].Expr.Emit (ec);
5878                                 ec.Emit (OpCodes.Dup);
5879                                 arguments.RemoveAt (0);
5880                         }
5881
5882                         oper_expr.EmitBranchable (ec, end_target, true);
5883
5884                         base.Emit (ec);
5885
5886                         if (right_contains_await) {
5887                                 //
5888                                 // Special handling when right expression contains await and left argument
5889                                 // could not be left on stack before logical branch
5890                                 //
5891                                 Label skip_left_load = ec.DefineLabel ();
5892                                 ec.Emit (OpCodes.Br_S, skip_left_load);
5893                                 ec.MarkLabel (end_target);
5894                                 arguments[0].Expr.Emit (ec);
5895                                 ec.MarkLabel (skip_left_load);
5896                         } else {
5897                                 ec.MarkLabel (end_target);
5898                         }
5899                 }
5900         }
5901
5902         public class PointerArithmetic : Expression {
5903                 Expression left, right;
5904                 readonly Binary.Operator op;
5905
5906                 //
5907                 // We assume that `l' is always a pointer
5908                 //
5909                 public PointerArithmetic (Binary.Operator op, Expression l, Expression r, TypeSpec t, Location loc)
5910                 {
5911                         type = t;
5912                         this.loc = loc;
5913                         left = l;
5914                         right = r;
5915                         this.op = op;
5916                 }
5917
5918                 public override bool ContainsEmitWithAwait ()
5919                 {
5920                         throw new NotImplementedException ();
5921                 }
5922
5923                 public override Expression CreateExpressionTree (ResolveContext ec)
5924                 {
5925                         Error_PointerInsideExpressionTree (ec);
5926                         return null;
5927                 }
5928
5929                 protected override Expression DoResolve (ResolveContext ec)
5930                 {
5931                         eclass = ExprClass.Variable;
5932
5933                         var pc = left.Type as PointerContainer;
5934                         if (pc != null && pc.Element.Kind == MemberKind.Void) {
5935                                 Error_VoidPointerOperation (ec);
5936                                 return null;
5937                         }
5938                         
5939                         return this;
5940                 }
5941
5942                 public override void Emit (EmitContext ec)
5943                 {
5944                         TypeSpec op_type = left.Type;
5945                         
5946                         // It must be either array or fixed buffer
5947                         TypeSpec element;
5948                         if (TypeManager.HasElementType (op_type)) {
5949                                 element = TypeManager.GetElementType (op_type);
5950                         } else {
5951                                 FieldExpr fe = left as FieldExpr;
5952                                 if (fe != null)
5953                                         element = ((FixedFieldSpec) (fe.Spec)).ElementType;
5954                                 else
5955                                         element = op_type;
5956                         }
5957
5958                         int size = BuiltinTypeSpec.GetSize(element);
5959                         TypeSpec rtype = right.Type;
5960                         
5961                         if ((op & Binary.Operator.SubtractionMask) != 0 && rtype.IsPointer){
5962                                 //
5963                                 // handle (pointer - pointer)
5964                                 //
5965                                 left.Emit (ec);
5966                                 right.Emit (ec);
5967                                 ec.Emit (OpCodes.Sub);
5968
5969                                 if (size != 1){
5970                                         if (size == 0)
5971                                                 ec.Emit (OpCodes.Sizeof, element);
5972                                         else 
5973                                                 ec.EmitInt (size);
5974                                         ec.Emit (OpCodes.Div);
5975                                 }
5976                                 ec.Emit (OpCodes.Conv_I8);
5977                         } else {
5978                                 //
5979                                 // handle + and - on (pointer op int)
5980                                 //
5981                                 Constant left_const = left as Constant;
5982                                 if (left_const != null) {
5983                                         //
5984                                         // Optimize ((T*)null) pointer operations
5985                                         //
5986                                         if (left_const.IsDefaultValue) {
5987                                                 left = EmptyExpression.Null;
5988                                         } else {
5989                                                 left_const = null;
5990                                         }
5991                                 }
5992
5993                                 left.Emit (ec);
5994
5995                                 var right_const = right as Constant;
5996                                 if (right_const != null) {
5997                                         //
5998                                         // Optimize 0-based arithmetic
5999                                         //
6000                                         if (right_const.IsDefaultValue)
6001                                                 return;
6002
6003                                         if (size != 0)
6004                                                 right = new IntConstant (ec.BuiltinTypes, size, right.Location);
6005                                         else
6006                                                 right = new SizeOf (new TypeExpression (element, right.Location), right.Location);
6007                                         
6008                                         // TODO: Should be the checks resolve context sensitive?
6009                                         ResolveContext rc = new ResolveContext (ec.MemberContext, ResolveContext.Options.UnsafeScope);
6010                                         right = new Binary (Binary.Operator.Multiply, right, right_const).Resolve (rc);
6011                                         if (right == null)
6012                                                 return;
6013                                 }
6014
6015                                 right.Emit (ec);
6016                                 if (right_const == null) {
6017                                         switch (rtype.BuiltinType) {
6018                                         case BuiltinTypeSpec.Type.SByte:
6019                                         case BuiltinTypeSpec.Type.Byte:
6020                                         case BuiltinTypeSpec.Type.Short:
6021                                         case BuiltinTypeSpec.Type.UShort:
6022                                         case BuiltinTypeSpec.Type.Int:
6023                                                 ec.Emit (OpCodes.Conv_I);
6024                                                 break;
6025                                         case BuiltinTypeSpec.Type.UInt:
6026                                                 ec.Emit (OpCodes.Conv_U);
6027                                                 break;
6028                                         }
6029                                 }
6030
6031                                 if (right_const == null && size != 1){
6032                                         if (size == 0)
6033                                                 ec.Emit (OpCodes.Sizeof, element);
6034                                         else 
6035                                                 ec.EmitInt (size);
6036                                         if (rtype.BuiltinType == BuiltinTypeSpec.Type.Long || rtype.BuiltinType == BuiltinTypeSpec.Type.ULong)
6037                                                 ec.Emit (OpCodes.Conv_I8);
6038
6039                                         Binary.EmitOperatorOpcode (ec, Binary.Operator.Multiply, rtype, right);
6040                                 }
6041
6042                                 if (left_const == null) {
6043                                         if (rtype.BuiltinType == BuiltinTypeSpec.Type.Long)
6044                                                 ec.Emit (OpCodes.Conv_I);
6045                                         else if (rtype.BuiltinType == BuiltinTypeSpec.Type.ULong)
6046                                                 ec.Emit (OpCodes.Conv_U);
6047
6048                                         Binary.EmitOperatorOpcode (ec, op, op_type, right);
6049                                 }
6050                         }
6051                 }
6052         }
6053
6054         //
6055         // A boolean-expression is an expression that yields a result
6056         // of type bool
6057         //
6058         public class BooleanExpression : ShimExpression
6059         {
6060                 public BooleanExpression (Expression expr)
6061                         : base (expr)
6062                 {
6063                         this.loc = expr.Location;
6064                 }
6065
6066                 public override Expression CreateExpressionTree (ResolveContext ec)
6067                 {
6068                         // TODO: We should emit IsTrue (v4) instead of direct user operator
6069                         // call but that would break csc compatibility
6070                         return base.CreateExpressionTree (ec);
6071                 }
6072
6073                 protected override Expression DoResolve (ResolveContext ec)
6074                 {
6075                         // A boolean-expression is required to be of a type
6076                         // that can be implicitly converted to bool or of
6077                         // a type that implements operator true
6078
6079                         expr = expr.Resolve (ec);
6080                         if (expr == null)
6081                                 return null;
6082
6083                         Assign ass = expr as Assign;
6084                         if (ass != null && ass.Source is Constant) {
6085                                 ec.Report.Warning (665, 3, loc,
6086                                         "Assignment in conditional expression is always constant. Did you mean to use `==' instead ?");
6087                         }
6088
6089                         if (expr.Type.BuiltinType == BuiltinTypeSpec.Type.Bool)
6090                                 return expr;
6091
6092                         if (expr.Type.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
6093                                 Arguments args = new Arguments (1);
6094                                 args.Add (new Argument (expr));
6095                                 return DynamicUnaryConversion.CreateIsTrue (ec, args, loc).Resolve (ec);
6096                         }
6097
6098                         type = ec.BuiltinTypes.Bool;
6099                         Expression converted = Convert.ImplicitConversion (ec, expr, type, loc);
6100                         if (converted != null)
6101                                 return converted;
6102
6103                         //
6104                         // If no implicit conversion to bool exists, try using `operator true'
6105                         //
6106                         converted = GetOperatorTrue (ec, expr, loc);
6107                         if (converted == null) {
6108                                 expr.Error_ValueCannotBeConverted (ec, type, false);
6109                                 return null;
6110                         }
6111
6112                         return converted;
6113                 }
6114                 
6115                 public override object Accept (StructuralVisitor visitor)
6116                 {
6117                         return visitor.Visit (this);
6118                 }
6119         }
6120
6121         public class BooleanExpressionFalse : Unary
6122         {
6123                 public BooleanExpressionFalse (Expression expr)
6124                         : base (Operator.LogicalNot, expr, expr.Location)
6125                 {
6126                 }
6127
6128                 protected override Expression ResolveOperator (ResolveContext ec, Expression expr)
6129                 {
6130                         return GetOperatorFalse (ec, expr, loc) ?? base.ResolveOperator (ec, expr);
6131                 }
6132         }
6133         
6134         /// <summary>
6135         ///   Implements the ternary conditional operator (?:)
6136         /// </summary>
6137         public class Conditional : Expression {
6138                 Expression expr, true_expr, false_expr;
6139
6140                 public Conditional (Expression expr, Expression true_expr, Expression false_expr, Location loc)
6141                 {
6142                         this.expr = expr;
6143                         this.true_expr = true_expr;
6144                         this.false_expr = false_expr;
6145                         this.loc = loc;
6146                 }
6147
6148                 #region Properties
6149
6150                 public Expression Expr {
6151                         get {
6152                                 return expr;
6153                         }
6154                 }
6155
6156                 public Expression TrueExpr {
6157                         get {
6158                                 return true_expr;
6159                         }
6160                 }
6161
6162                 public Expression FalseExpr {
6163                         get {
6164                                 return false_expr;
6165                         }
6166                 }
6167
6168                 #endregion
6169
6170                 public override bool ContainsEmitWithAwait ()
6171                 {
6172                         return Expr.ContainsEmitWithAwait () || true_expr.ContainsEmitWithAwait () || false_expr.ContainsEmitWithAwait ();
6173                 }
6174
6175                 public override Expression CreateExpressionTree (ResolveContext ec)
6176                 {
6177                         Arguments args = new Arguments (3);
6178                         args.Add (new Argument (expr.CreateExpressionTree (ec)));
6179                         args.Add (new Argument (true_expr.CreateExpressionTree (ec)));
6180                         args.Add (new Argument (false_expr.CreateExpressionTree (ec)));
6181                         return CreateExpressionFactoryCall (ec, "Condition", args);
6182                 }
6183
6184                 protected override Expression DoResolve (ResolveContext ec)
6185                 {
6186                         expr = expr.Resolve (ec);
6187                         true_expr = true_expr.Resolve (ec);
6188                         false_expr = false_expr.Resolve (ec);
6189
6190                         if (true_expr == null || false_expr == null || expr == null)
6191                                 return null;
6192
6193                         eclass = ExprClass.Value;
6194                         TypeSpec true_type = true_expr.Type;
6195                         TypeSpec false_type = false_expr.Type;
6196                         type = true_type;
6197
6198                         //
6199                         // First, if an implicit conversion exists from true_expr
6200                         // to false_expr, then the result type is of type false_expr.Type
6201                         //
6202                         if (!TypeSpecComparer.IsEqual (true_type, false_type)) {
6203                                 Expression conv = Convert.ImplicitConversion (ec, true_expr, false_type, loc);
6204                                 if (conv != null && true_type.BuiltinType != BuiltinTypeSpec.Type.Dynamic) {
6205                                         //
6206                                         // Check if both can convert implicitly to each other's type
6207                                         //
6208                                         type = false_type;
6209
6210                                         if (false_type.BuiltinType != BuiltinTypeSpec.Type.Dynamic) {
6211                                                 var conv_false_expr = Convert.ImplicitConversion (ec, false_expr, true_type, loc);
6212                                                 //
6213                                                 // LAMESPEC: There seems to be hardcoded promotition to int type when
6214                                                 // both sides are numeric constants and one side is int constant and
6215                                                 // other side is numeric constant convertible to int.
6216                                                 //
6217                                                 // var res = condition ? (short)1 : 1;
6218                                                 //
6219                                                 // Type of res is int even if according to the spec the conversion is
6220                                                 // ambiguous because 1 literal can be converted to short.
6221                                                 //
6222                                                 if (conv_false_expr != null) {
6223                                                         if (conv_false_expr.Type.BuiltinType == BuiltinTypeSpec.Type.Int && conv is Constant) {
6224                                                                 type = true_type;
6225                                                                 conv_false_expr = null;
6226                                                         } else if (type.BuiltinType == BuiltinTypeSpec.Type.Int && conv_false_expr is Constant) {
6227                                                                 conv_false_expr = null;
6228                                                         }
6229                                                 }
6230
6231                                                 if (conv_false_expr != null) {
6232                                                         ec.Report.Error (172, true_expr.Location,
6233                                                                 "Type of conditional expression cannot be determined as `{0}' and `{1}' convert implicitly to each other",
6234                                                                         true_type.GetSignatureForError (), false_type.GetSignatureForError ());
6235                                                 }
6236                                         }
6237
6238                                         true_expr = conv;
6239                                         if (true_expr.Type != type)
6240                                                 true_expr = EmptyCast.Create (true_expr, type);
6241                                 } else if ((conv = Convert.ImplicitConversion (ec, false_expr, true_type, loc)) != null) {
6242                                         false_expr = conv;
6243                                 } else {
6244                                         if (false_type != InternalType.ErrorType) {
6245                                                 ec.Report.Error (173, true_expr.Location,
6246                                                         "Type of conditional expression cannot be determined because there is no implicit conversion between `{0}' and `{1}'",
6247                                                         true_type.GetSignatureForError (), false_type.GetSignatureForError ());
6248                                         }
6249                                         return null;
6250                                 }
6251                         }
6252
6253                         Constant c = expr as Constant;
6254                         if (c != null) {
6255                                 bool is_false = c.IsDefaultValue;
6256
6257                                 //
6258                                 // Don't issue the warning for constant expressions
6259                                 //
6260                                 if (!(is_false ? true_expr is Constant : false_expr is Constant)) {
6261                                         // CSC: Missing warning
6262                                         Warning_UnreachableExpression (ec, is_false ? true_expr.Location : false_expr.Location);
6263                                 }
6264
6265                                 return ReducedExpression.Create (
6266                                         is_false ? false_expr : true_expr, this,
6267                                         false_expr is Constant && true_expr is Constant).Resolve (ec);
6268                         }
6269
6270                         return this;
6271                 }
6272
6273                 public override void Emit (EmitContext ec)
6274                 {
6275                         Label false_target = ec.DefineLabel ();
6276                         Label end_target = ec.DefineLabel ();
6277
6278                         expr.EmitBranchable (ec, false_target, false);
6279                         true_expr.Emit (ec);
6280
6281                         //
6282                         // Verifier doesn't support interface merging. When there are two types on
6283                         // the stack without common type hint and the common type is an interface.
6284                         // Use temporary local to give verifier hint on what type to unify the stack
6285                         //
6286                         if (type.IsInterface && true_expr is EmptyCast && false_expr is EmptyCast) {
6287                                 var temp = ec.GetTemporaryLocal (type);
6288                                 ec.Emit (OpCodes.Stloc, temp);
6289                                 ec.Emit (OpCodes.Ldloc, temp);
6290                                 ec.FreeTemporaryLocal (temp, type);
6291                         }
6292
6293                         ec.Emit (OpCodes.Br, end_target);
6294                         ec.MarkLabel (false_target);
6295                         false_expr.Emit (ec);
6296                         ec.MarkLabel (end_target);
6297                 }
6298
6299                 public override void FlowAnalysis (FlowAnalysisContext fc)
6300                 {
6301                         expr.FlowAnalysisConditional (fc);
6302                         var expr_true = fc.DefiniteAssignmentOnTrue;
6303                         var expr_false = fc.DefiniteAssignmentOnFalse;
6304
6305                         fc.BranchDefiniteAssignment (expr_true);
6306                         true_expr.FlowAnalysis (fc);
6307                         var true_fc = fc.DefiniteAssignment;
6308
6309                         fc.BranchDefiniteAssignment (expr_false);
6310                         false_expr.FlowAnalysis (fc);
6311
6312                         fc.DefiniteAssignment &= true_fc;
6313                 }
6314
6315                 public override void FlowAnalysisConditional (FlowAnalysisContext fc)
6316                 {
6317                         expr.FlowAnalysisConditional (fc);
6318                         var expr_true = fc.DefiniteAssignmentOnTrue;
6319                         var expr_false = fc.DefiniteAssignmentOnFalse;
6320
6321                         fc.DefiniteAssignmentOnTrue = fc.DefiniteAssignmentOnFalse = fc.DefiniteAssignment = new DefiniteAssignmentBitSet (expr_true);
6322                         true_expr.FlowAnalysisConditional (fc);
6323                         var true_fc = fc.DefiniteAssignment;
6324                         var true_da_true = fc.DefiniteAssignmentOnTrue;
6325                         var true_da_false = fc.DefiniteAssignmentOnFalse;
6326
6327                         fc.DefiniteAssignmentOnTrue = fc.DefiniteAssignmentOnFalse = fc.DefiniteAssignment = new DefiniteAssignmentBitSet (expr_false);
6328                         false_expr.FlowAnalysisConditional (fc);
6329
6330                         fc.DefiniteAssignment &= true_fc;
6331                         fc.DefiniteAssignmentOnTrue = true_da_true & fc.DefiniteAssignmentOnTrue;
6332                         fc.DefiniteAssignmentOnFalse = true_da_false & fc.DefiniteAssignmentOnFalse;
6333                 }
6334
6335                 protected override void CloneTo (CloneContext clonectx, Expression t)
6336                 {
6337                         Conditional target = (Conditional) t;
6338
6339                         target.expr = expr.Clone (clonectx);
6340                         target.true_expr = true_expr.Clone (clonectx);
6341                         target.false_expr = false_expr.Clone (clonectx);
6342                 }
6343         }
6344
6345         public abstract class VariableReference : Expression, IAssignMethod, IMemoryLocation, IVariableReference
6346         {
6347                 LocalTemporary temp;
6348
6349                 #region Abstract
6350                 public abstract HoistedVariable GetHoistedVariable (AnonymousExpression ae);
6351                 public abstract void SetHasAddressTaken ();
6352
6353                 public abstract bool IsLockedByStatement { get; set; }
6354
6355                 public abstract bool IsFixed { get; }
6356                 public abstract bool IsRef { get; }
6357                 public abstract string Name { get; }
6358
6359                 //
6360                 // Variable IL data, it has to be protected to encapsulate hoisted variables
6361                 //
6362                 protected abstract ILocalVariable Variable { get; }
6363                 
6364                 //
6365                 // Variable flow-analysis data
6366                 //
6367                 public abstract VariableInfo VariableInfo { get; }
6368                 #endregion
6369
6370                 public virtual void AddressOf (EmitContext ec, AddressOp mode)
6371                 {
6372                         HoistedVariable hv = GetHoistedVariable (ec);
6373                         if (hv != null) {
6374                                 hv.AddressOf (ec, mode);
6375                                 return;
6376                         }
6377
6378                         Variable.EmitAddressOf (ec);
6379                 }
6380
6381                 public override bool ContainsEmitWithAwait ()
6382                 {
6383                         return false;
6384                 }
6385
6386                 public override Expression CreateExpressionTree (ResolveContext ec)
6387                 {
6388                         HoistedVariable hv = GetHoistedVariable (ec);
6389                         if (hv != null)
6390                                 return hv.CreateExpressionTree ();
6391
6392                         Arguments arg = new Arguments (1);
6393                         arg.Add (new Argument (this));
6394                         return CreateExpressionFactoryCall (ec, "Constant", arg);
6395                 }
6396
6397                 public override Expression DoResolveLValue (ResolveContext rc, Expression right_side)
6398                 {
6399                         if (IsLockedByStatement) {
6400                                 rc.Report.Warning (728, 2, loc,
6401                                         "Possibly incorrect assignment to `{0}' which is the argument to a using or lock statement",
6402                                         Name);
6403                         }
6404
6405                         return this;
6406                 }
6407
6408                 public override void Emit (EmitContext ec)
6409                 {
6410                         Emit (ec, false);
6411                 }
6412
6413                 public override void EmitSideEffect (EmitContext ec)
6414                 {
6415                         // do nothing
6416                 }
6417
6418                 //
6419                 // This method is used by parameters that are references, that are
6420                 // being passed as references:  we only want to pass the pointer (that
6421                 // is already stored in the parameter, not the address of the pointer,
6422                 // and not the value of the variable).
6423                 //
6424                 public void EmitLoad (EmitContext ec)
6425                 {
6426                         Variable.Emit (ec);
6427                 }
6428
6429                 public void Emit (EmitContext ec, bool leave_copy)
6430                 {
6431                         HoistedVariable hv = GetHoistedVariable (ec);
6432                         if (hv != null) {
6433                                 hv.Emit (ec, leave_copy);
6434                                 return;
6435                         }
6436
6437                         EmitLoad (ec);
6438
6439                         if (IsRef) {
6440                                 //
6441                                 // If we are a reference, we loaded on the stack a pointer
6442                                 // Now lets load the real value
6443                                 //
6444                                 ec.EmitLoadFromPtr (type);
6445                         }
6446
6447                         if (leave_copy) {
6448                                 ec.Emit (OpCodes.Dup);
6449
6450                                 if (IsRef) {
6451                                         temp = new LocalTemporary (Type);
6452                                         temp.Store (ec);
6453                                 }
6454                         }
6455                 }
6456
6457                 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy,
6458                                         bool prepare_for_load)
6459                 {
6460                         HoistedVariable hv = GetHoistedVariable (ec);
6461                         if (hv != null) {
6462                                 hv.EmitAssign (ec, source, leave_copy, prepare_for_load);
6463                                 return;
6464                         }
6465
6466                         New n_source = source as New;
6467                         if (n_source != null) {
6468                                 if (!n_source.Emit (ec, this)) {
6469                                         if (leave_copy) {
6470                                                 EmitLoad (ec);
6471                                                 if (IsRef)
6472                                                         ec.EmitLoadFromPtr (type);
6473                                         }
6474                                         return;
6475                                 }
6476                         } else {
6477                                 if (IsRef)
6478                                         EmitLoad (ec);
6479
6480                                 source.Emit (ec);
6481                         }
6482
6483                         if (leave_copy) {
6484                                 ec.Emit (OpCodes.Dup);
6485                                 if (IsRef) {
6486                                         temp = new LocalTemporary (Type);
6487                                         temp.Store (ec);
6488                                 }
6489                         }
6490
6491                         if (IsRef)
6492                                 ec.EmitStoreFromPtr (type);
6493                         else
6494                                 Variable.EmitAssign (ec);
6495
6496                         if (temp != null) {
6497                                 temp.Emit (ec);
6498                                 temp.Release (ec);
6499                         }
6500                 }
6501
6502                 public override Expression EmitToField (EmitContext ec)
6503                 {
6504                         HoistedVariable hv = GetHoistedVariable (ec);
6505                         if (hv != null) {
6506                                 return hv.EmitToField (ec);
6507                         }
6508
6509                         return base.EmitToField (ec);
6510                 }
6511
6512                 public HoistedVariable GetHoistedVariable (ResolveContext rc)
6513                 {
6514                         return GetHoistedVariable (rc.CurrentAnonymousMethod);
6515                 }
6516
6517                 public HoistedVariable GetHoistedVariable (EmitContext ec)
6518                 {
6519                         return GetHoistedVariable (ec.CurrentAnonymousMethod);
6520                 }
6521
6522                 public override string GetSignatureForError ()
6523                 {
6524                         return Name;
6525                 }
6526
6527                 public bool IsHoisted {
6528                         get { return GetHoistedVariable ((AnonymousExpression) null) != null; }
6529                 }
6530         }
6531
6532         //
6533         // Resolved reference to a local variable
6534         //
6535         public class LocalVariableReference : VariableReference
6536         {
6537                 public LocalVariable local_info;
6538
6539                 public LocalVariableReference (LocalVariable li, Location l)
6540                 {
6541                         this.local_info = li;
6542                         loc = l;
6543                 }
6544
6545                 public override VariableInfo VariableInfo {
6546                         get { return local_info.VariableInfo; }
6547                 }
6548
6549                 public override HoistedVariable GetHoistedVariable (AnonymousExpression ae)
6550                 {
6551                         return local_info.HoistedVariant;
6552                 }
6553
6554                 #region Properties
6555
6556                 //              
6557                 // A local variable is always fixed
6558                 //
6559                 public override bool IsFixed {
6560                         get {
6561                                 return true;
6562                         }
6563                 }
6564
6565                 public override bool IsLockedByStatement {
6566                         get {
6567                                 return local_info.IsLocked;
6568                         }
6569                         set {
6570                                 local_info.IsLocked = value;
6571                         }
6572                 }
6573
6574                 public override bool IsRef {
6575                         get { return false; }
6576                 }
6577
6578                 public override string Name {
6579                         get { return local_info.Name; }
6580                 }
6581
6582                 #endregion
6583
6584                 public override void FlowAnalysis (FlowAnalysisContext fc)
6585                 {
6586                         VariableInfo variable_info = VariableInfo;
6587                         if (variable_info == null)
6588                                 return;
6589
6590                         if (fc.IsDefinitelyAssigned (variable_info))
6591                                 return;
6592
6593                         fc.Report.Error (165, loc, "Use of unassigned local variable `{0}'", Name);
6594                         variable_info.SetAssigned (fc.DefiniteAssignment, true);
6595                 }
6596
6597                 public override void SetHasAddressTaken ()
6598                 {
6599                         local_info.SetHasAddressTaken ();
6600                 }
6601
6602                 void DoResolveBase (ResolveContext ec)
6603                 {
6604                         eclass = ExprClass.Variable;
6605                         type = local_info.Type;
6606
6607                         //
6608                         // If we are referencing a variable from the external block
6609                         // flag it for capturing
6610                         //
6611                         if (ec.MustCaptureVariable (local_info)) {
6612                                 if (local_info.AddressTaken) {
6613                                         AnonymousMethodExpression.Error_AddressOfCapturedVar (ec, this, loc);
6614                                 } else if (local_info.IsFixed) {
6615                                         ec.Report.Error (1764, loc,
6616                                                 "Cannot use fixed local `{0}' inside an anonymous method, lambda expression or query expression",
6617                                                 GetSignatureForError ());
6618                                 }
6619
6620                                 if (ec.IsVariableCapturingRequired) {
6621                                         AnonymousMethodStorey storey = local_info.Block.Explicit.CreateAnonymousMethodStorey (ec);
6622                                         storey.CaptureLocalVariable (ec, local_info);
6623                                 }
6624                         }
6625                 }
6626
6627                 protected override Expression DoResolve (ResolveContext ec)
6628                 {
6629                         local_info.SetIsUsed ();
6630
6631                         DoResolveBase (ec);
6632
6633                         if (local_info.Type == InternalType.VarOutType) {
6634                                 ec.Report.Error (8048, loc, "Cannot use uninitialized variable `{0}'",
6635                                         GetSignatureForError ());
6636
6637                                 type = InternalType.ErrorType;
6638                         }
6639
6640                         return this;
6641                 }
6642
6643                 public override Expression DoResolveLValue (ResolveContext ec, Expression rhs)
6644                 {
6645                         //
6646                         // Don't be too pedantic when variable is used as out param or for some broken code
6647                         // which uses property/indexer access to run some initialization
6648                         //
6649                         if (rhs == EmptyExpression.OutAccess || rhs.eclass == ExprClass.PropertyAccess || rhs.eclass == ExprClass.IndexerAccess)
6650                                 local_info.SetIsUsed ();
6651
6652                         if (local_info.IsReadonly && !ec.HasAny (ResolveContext.Options.FieldInitializerScope | ResolveContext.Options.UsingInitializerScope)) {
6653                                 if (rhs == EmptyExpression.LValueMemberAccess) {
6654                                         // CS1654 already reported
6655                                 } else {
6656                                         int code;
6657                                         string msg;
6658                                         if (rhs == EmptyExpression.OutAccess) {
6659                                                 code = 1657; msg = "Cannot pass `{0}' as a ref or out argument because it is a `{1}'";
6660                                         } else if (rhs == EmptyExpression.LValueMemberOutAccess) {
6661                                                 code = 1655; msg = "Cannot pass members of `{0}' as ref or out arguments because it is a `{1}'";
6662                                         } else if (rhs == EmptyExpression.UnaryAddress) {
6663                                                 code = 459; msg = "Cannot take the address of {1} `{0}'";
6664                                         } else {
6665                                                 code = 1656; msg = "Cannot assign to `{0}' because it is a `{1}'";
6666                                         }
6667                                         ec.Report.Error (code, loc, msg, Name, local_info.GetReadOnlyContext ());
6668                                 }
6669                         }
6670
6671                         if (eclass == ExprClass.Unresolved)
6672                                 DoResolveBase (ec);
6673
6674                         return base.DoResolveLValue (ec, rhs);
6675                 }
6676
6677                 public override int GetHashCode ()
6678                 {
6679                         return local_info.GetHashCode ();
6680                 }
6681
6682                 public override bool Equals (object obj)
6683                 {
6684                         LocalVariableReference lvr = obj as LocalVariableReference;
6685                         if (lvr == null)
6686                                 return false;
6687
6688                         return local_info == lvr.local_info;
6689                 }
6690
6691                 protected override ILocalVariable Variable {
6692                         get { return local_info; }
6693                 }
6694
6695                 public override string ToString ()
6696                 {
6697                         return String.Format ("{0} ({1}:{2})", GetType (), Name, loc);
6698                 }
6699
6700                 protected override void CloneTo (CloneContext clonectx, Expression t)
6701                 {
6702                         // Nothing
6703                 }
6704         }
6705
6706         /// <summary>
6707         ///   This represents a reference to a parameter in the intermediate
6708         ///   representation.
6709         /// </summary>
6710         public class ParameterReference : VariableReference
6711         {
6712                 protected ParametersBlock.ParameterInfo pi;
6713
6714                 public ParameterReference (ParametersBlock.ParameterInfo pi, Location loc)
6715                 {
6716                         this.pi = pi;
6717                         this.loc = loc;
6718                 }
6719
6720                 #region Properties
6721
6722                 public override bool IsLockedByStatement {
6723                         get {
6724                                 return pi.IsLocked;
6725                         }
6726                         set     {
6727                                 pi.IsLocked = value;
6728                         }
6729                 }
6730
6731                 public override bool IsRef {
6732                         get { return (pi.Parameter.ModFlags & Parameter.Modifier.RefOutMask) != 0; }
6733                 }
6734
6735                 bool HasOutModifier {
6736                         get { return (pi.Parameter.ModFlags & Parameter.Modifier.OUT) != 0; }
6737                 }
6738
6739                 public override HoistedVariable GetHoistedVariable (AnonymousExpression ae)
6740                 {
6741                         return pi.Parameter.HoistedVariant;
6742                 }
6743
6744                 //
6745                 // A ref or out parameter is classified as a moveable variable, even 
6746                 // if the argument given for the parameter is a fixed variable
6747                 //              
6748                 public override bool IsFixed {
6749                         get { return !IsRef; }
6750                 }
6751
6752                 public override string Name {
6753                         get { return Parameter.Name; }
6754                 }
6755
6756                 public Parameter Parameter {
6757                         get { return pi.Parameter; }
6758                 }
6759
6760                 public override VariableInfo VariableInfo {
6761                         get { return pi.VariableInfo; }
6762                 }
6763
6764                 protected override ILocalVariable Variable {
6765                         get { return Parameter; }
6766                 }
6767
6768                 #endregion
6769
6770                 public override void AddressOf (EmitContext ec, AddressOp mode)
6771                 {
6772                         //
6773                         // ParameterReferences might already be a reference
6774                         //
6775                         if (IsRef) {
6776                                 EmitLoad (ec);
6777                                 return;
6778                         }
6779
6780                         base.AddressOf (ec, mode);
6781                 }
6782
6783                 public override void SetHasAddressTaken ()
6784                 {
6785                         Parameter.HasAddressTaken = true;
6786                 }
6787
6788                 bool DoResolveBase (ResolveContext ec)
6789                 {
6790                         if (eclass != ExprClass.Unresolved)
6791                                 return true;
6792
6793                         type = pi.ParameterType;
6794                         eclass = ExprClass.Variable;
6795
6796                         //
6797                         // If we are referencing a parameter from the external block
6798                         // flag it for capturing
6799                         //
6800                         if (ec.MustCaptureVariable (pi)) {
6801                                 if (Parameter.HasAddressTaken)
6802                                         AnonymousMethodExpression.Error_AddressOfCapturedVar (ec, this, loc);
6803
6804                                 if (IsRef) {
6805                                         ec.Report.Error (1628, loc,
6806                                                 "Parameter `{0}' cannot be used inside `{1}' when using `ref' or `out' modifier",
6807                                                 Name, ec.CurrentAnonymousMethod.ContainerType);
6808                                 }
6809
6810                                 if (ec.IsVariableCapturingRequired && !pi.Block.ParametersBlock.IsExpressionTree) {
6811                                         AnonymousMethodStorey storey = pi.Block.Explicit.CreateAnonymousMethodStorey (ec);
6812                                         storey.CaptureParameter (ec, pi, this);
6813                                 }
6814                         }
6815
6816                         return true;
6817                 }
6818
6819                 public override int GetHashCode ()
6820                 {
6821                         return Name.GetHashCode ();
6822                 }
6823
6824                 public override bool Equals (object obj)
6825                 {
6826                         ParameterReference pr = obj as ParameterReference;
6827                         if (pr == null)
6828                                 return false;
6829
6830                         return Name == pr.Name;
6831                 }
6832         
6833                 protected override void CloneTo (CloneContext clonectx, Expression target)
6834                 {
6835                         // Nothing to clone
6836                         return;
6837                 }
6838
6839                 public override Expression CreateExpressionTree (ResolveContext ec)
6840                 {
6841                         HoistedVariable hv = GetHoistedVariable (ec);
6842                         if (hv != null)
6843                                 return hv.CreateExpressionTree ();
6844
6845                         return Parameter.ExpressionTreeVariableReference ();
6846                 }
6847
6848                 protected override Expression DoResolve (ResolveContext ec)
6849                 {
6850                         if (!DoResolveBase (ec))
6851                                 return null;
6852
6853                         return this;
6854                 }
6855
6856                 public override Expression DoResolveLValue (ResolveContext ec, Expression right_side)
6857                 {
6858                         if (!DoResolveBase (ec))
6859                                 return null;
6860
6861                         if (Parameter.HoistedVariant != null)
6862                                 Parameter.HoistedVariant.IsAssigned = true;
6863
6864                         return base.DoResolveLValue (ec, right_side);
6865                 }
6866
6867                 public override void FlowAnalysis (FlowAnalysisContext fc)
6868                 {
6869                         VariableInfo variable_info = VariableInfo;
6870                         if (variable_info == null)
6871                                 return;
6872
6873                         if (fc.IsDefinitelyAssigned (variable_info))
6874                                 return;
6875
6876                         fc.Report.Error (269, loc, "Use of unassigned out parameter `{0}'", Name);
6877                         fc.SetVariableAssigned (variable_info);
6878                 }
6879         }
6880
6881         /// <summary>
6882         ///   Invocation of methods or delegates.
6883         /// </summary>
6884         public class Invocation : ExpressionStatement
6885         {
6886                 public class Predefined : Invocation
6887                 {
6888                         public Predefined (MethodGroupExpr expr, Arguments arguments)
6889                                 : base (expr, arguments)
6890                         {
6891                                 this.mg = expr;
6892                         }
6893
6894                         protected override MethodGroupExpr DoResolveOverload (ResolveContext rc)
6895                         {
6896                                 mg.BestCandidate.CheckObsoleteness (rc, loc);
6897
6898                                 return mg;
6899                         }
6900                 }
6901
6902                 protected Arguments arguments;
6903                 protected Expression expr;
6904                 protected MethodGroupExpr mg;
6905                 bool conditional_access_receiver;
6906                 
6907                 public Invocation (Expression expr, Arguments arguments)
6908                 {
6909                         this.expr = expr;               
6910                         this.arguments = arguments;
6911                         if (expr != null) {
6912                                 loc = expr.Location;
6913                         }
6914                 }
6915
6916                 #region Properties
6917                 public Arguments Arguments {
6918                         get {
6919                                 return arguments;
6920                         }
6921                 }
6922                 
6923                 public Expression Exp {
6924                         get {
6925                                 return expr;
6926                         }
6927                 }
6928
6929                 public MethodGroupExpr MethodGroup {
6930                         get {
6931                                 return mg;
6932                         }
6933                 }
6934
6935                 public override Location StartLocation {
6936                         get {
6937                                 return expr.StartLocation;
6938                         }
6939                 }
6940
6941                 #endregion
6942
6943                 public override MethodGroupExpr CanReduceLambda (AnonymousMethodBody body)
6944                 {
6945                         if (MethodGroup == null)
6946                                 return null;
6947
6948                         var candidate = MethodGroup.BestCandidate;
6949                         if (candidate == null || !(candidate.IsStatic || Exp is This))
6950                                 return null;
6951
6952                         var args_count = arguments == null ? 0 : arguments.Count;
6953                         if (args_count != body.Parameters.Count)
6954                                 return null;
6955
6956                         var lambda_parameters = body.Block.Parameters.FixedParameters;
6957                         for (int i = 0; i < args_count; ++i) {
6958                                 var pr = arguments[i].Expr as ParameterReference;
6959                                 if (pr == null)
6960                                         return null;
6961
6962                                 if (lambda_parameters[i] != pr.Parameter)
6963                                         return null;
6964
6965                                 if ((lambda_parameters[i].ModFlags & Parameter.Modifier.RefOutMask) != (pr.Parameter.ModFlags & Parameter.Modifier.RefOutMask))
6966                                         return null;
6967                         }
6968
6969                         var emg = MethodGroup as ExtensionMethodGroupExpr;
6970                         if (emg != null) {
6971                                 var mg = MethodGroupExpr.CreatePredefined (candidate, candidate.DeclaringType, MethodGroup.Location);
6972                                 if (candidate.IsGeneric) {
6973                                         var targs = new TypeExpression [candidate.Arity];
6974                                         for (int i = 0; i < targs.Length; ++i) {
6975                                                 targs[i] = new TypeExpression (candidate.TypeArguments[i], MethodGroup.Location);
6976                                         }
6977
6978                                         mg.SetTypeArguments (null, new TypeArguments (targs));
6979                                 }
6980
6981                                 return mg;
6982                         }
6983
6984                         return MethodGroup;
6985                 }
6986
6987                 protected override void CloneTo (CloneContext clonectx, Expression t)
6988                 {
6989                         Invocation target = (Invocation) t;
6990
6991                         if (arguments != null)
6992                                 target.arguments = arguments.Clone (clonectx);
6993
6994                         target.expr = expr.Clone (clonectx);
6995                 }
6996
6997                 public override bool ContainsEmitWithAwait ()
6998                 {
6999                         if (arguments != null && arguments.ContainsEmitWithAwait ())
7000                                 return true;
7001
7002                         return mg.ContainsEmitWithAwait ();
7003                 }
7004
7005                 public override Expression CreateExpressionTree (ResolveContext ec)
7006                 {
7007                         Expression instance = mg.IsInstance ?
7008                                 mg.InstanceExpression.CreateExpressionTree (ec) :
7009                                 new NullLiteral (loc);
7010
7011                         var args = Arguments.CreateForExpressionTree (ec, arguments,
7012                                 instance,
7013                                 mg.CreateExpressionTree (ec));
7014
7015                         return CreateExpressionFactoryCall (ec, "Call", args);
7016                 }
7017
7018                 void ResolveConditionalAccessReceiver (ResolveContext rc)
7019                 {
7020                         if (!rc.HasSet (ResolveContext.Options.DontSetConditionalAccessReceiver) && expr.HasConditionalAccess ()) {
7021                                 conditional_access_receiver = true;
7022                         }
7023                 }
7024
7025                 protected override Expression DoResolve (ResolveContext rc)
7026                 {
7027                         ResolveConditionalAccessReceiver (rc);
7028                         return DoResolveInvocation (rc);
7029                 }
7030
7031                 Expression DoResolveInvocation (ResolveContext ec)
7032                 {
7033                         Expression member_expr;
7034                         var atn = expr as ATypeNameExpression;
7035
7036                         var flags = default (ResolveContext.FlagsHandle);
7037                         if (conditional_access_receiver)
7038                                 flags = ec.Set (ResolveContext.Options.DontSetConditionalAccessReceiver);
7039
7040                         if (atn != null) {
7041                                 member_expr = atn.LookupNameExpression (ec, MemberLookupRestrictions.InvocableOnly | MemberLookupRestrictions.ReadAccess);
7042                                 if (member_expr != null) {
7043                                         var name_of = member_expr as NameOf;
7044                                         if (name_of != null) {
7045                                                 return name_of.ResolveOverload (ec, arguments);
7046                                         }
7047
7048                                         member_expr = member_expr.Resolve (ec);
7049                                 }
7050                         } else {
7051                                 member_expr = expr.Resolve (ec);
7052                         }
7053
7054                         if (conditional_access_receiver)
7055                                 flags.Dispose ();
7056
7057                         if (member_expr == null)
7058                                 return null;
7059
7060                         //
7061                         // Next, evaluate all the expressions in the argument list
7062                         //
7063                         bool dynamic_arg = false;
7064                         if (arguments != null) {
7065                                 using (ec.With (ResolveContext.Options.DontSetConditionalAccessReceiver, false)) {
7066                                         arguments.Resolve (ec, out dynamic_arg);
7067                                 }
7068                         }
7069
7070                         TypeSpec expr_type = member_expr.Type;
7071                         if (expr_type.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
7072                                 return DoResolveDynamic (ec, member_expr);
7073
7074                         mg = member_expr as MethodGroupExpr;
7075                         Expression invoke = null;
7076
7077                         if (mg == null) {
7078                                 if (expr_type != null && expr_type.IsDelegate) {
7079                                         invoke = new DelegateInvocation (member_expr, arguments, conditional_access_receiver, loc);
7080                                         invoke = invoke.Resolve (ec);
7081                                         if (invoke == null || !dynamic_arg)
7082                                                 return invoke;
7083                                 } else {
7084                                         if (member_expr is RuntimeValueExpression) {
7085                                                 ec.Report.Error (Report.RuntimeErrorId, loc, "Cannot invoke a non-delegate type `{0}'",
7086                                                         member_expr.Type.GetSignatureForError ());
7087                                                 return null;
7088                                         }
7089
7090                                         MemberExpr me = member_expr as MemberExpr;
7091                                         if (me == null) {
7092                                                 member_expr.Error_UnexpectedKind (ec, ResolveFlags.MethodGroup, loc);
7093                                                 return null;
7094                                         }
7095
7096                                         ec.Report.Error (1955, loc, "The member `{0}' cannot be used as method or delegate",
7097                                                         member_expr.GetSignatureForError ());
7098                                         return null;
7099                                 }
7100                         }
7101
7102                         if (invoke == null) {
7103                                 mg = DoResolveOverload (ec);
7104                                 if (mg == null)
7105                                         return null;
7106                         }
7107
7108                         if (dynamic_arg)
7109                                 return DoResolveDynamic (ec, member_expr);
7110
7111                         var method = mg.BestCandidate;
7112                         type = mg.BestCandidateReturnType;
7113                         if (conditional_access_receiver)
7114                                 type = LiftMemberType (ec, type);
7115
7116                         if (arguments == null && method.DeclaringType.BuiltinType == BuiltinTypeSpec.Type.Object && method.Name == Destructor.MetadataName) {
7117                                 if (mg.IsBase)
7118                                         ec.Report.Error (250, loc, "Do not directly call your base class Finalize method. It is called automatically from your destructor");
7119                                 else
7120                                         ec.Report.Error (245, loc, "Destructors and object.Finalize cannot be called directly. Consider calling IDisposable.Dispose if available");
7121                                 return null;
7122                         }
7123
7124                         IsSpecialMethodInvocation (ec, method, loc);
7125                         
7126                         eclass = ExprClass.Value;
7127                         return this;
7128                 }
7129
7130                 protected virtual Expression DoResolveDynamic (ResolveContext ec, Expression memberExpr)
7131                 {
7132                         Arguments args;
7133                         DynamicMemberBinder dmb = memberExpr as DynamicMemberBinder;
7134                         if (dmb != null) {
7135                                 args = dmb.Arguments;
7136                                 if (arguments != null)
7137                                         args.AddRange (arguments);
7138                         } else if (mg == null) {
7139                                 if (arguments == null)
7140                                         args = new Arguments (1);
7141                                 else
7142                                         args = arguments;
7143
7144                                 args.Insert (0, new Argument (memberExpr));
7145                                 this.expr = null;
7146                         } else {
7147                                 if (mg.IsBase) {
7148                                         ec.Report.Error (1971, loc,
7149                                                 "The base call to method `{0}' cannot be dynamically dispatched. Consider casting the dynamic arguments or eliminating the base access",
7150                                                 mg.Name);
7151                                         return null;
7152                                 }
7153
7154                                 if (arguments == null)
7155                                         args = new Arguments (1);
7156                                 else
7157                                         args = arguments;
7158
7159                                 MemberAccess ma = expr as MemberAccess;
7160                                 if (ma != null) {
7161                                         var inst = mg.InstanceExpression;
7162                                         var left_type = inst as TypeExpr;
7163                                         if (left_type != null) {
7164                                                 args.Insert (0, new Argument (new TypeOf (left_type.Type, loc).Resolve (ec), Argument.AType.DynamicTypeName));
7165                                         } else if (inst != null) {
7166                                                 //
7167                                                 // Any value type has to be pass as by-ref to get back the same
7168                                                 // instance on which the member was called
7169                                                 //
7170                                                 var mod = inst is IMemoryLocation && TypeSpec.IsValueType (inst.Type) ?
7171                                                         Argument.AType.Ref : Argument.AType.None;
7172                                                 args.Insert (0, new Argument (inst.Resolve (ec), mod));
7173                                         }
7174                                 } else {        // is SimpleName
7175                                         if (ec.IsStatic) {
7176                                                 args.Insert (0, new Argument (new TypeOf (ec.CurrentType, loc).Resolve (ec), Argument.AType.DynamicTypeName));
7177                                         } else {
7178                                                 args.Insert (0, new Argument (new This (loc).Resolve (ec)));
7179                                         }
7180                                 }
7181                         }
7182
7183                         return new DynamicInvocation (expr as ATypeNameExpression, args, loc).Resolve (ec);
7184                 }
7185
7186                 protected virtual MethodGroupExpr DoResolveOverload (ResolveContext ec)
7187                 {
7188                         return mg.OverloadResolve (ec, ref arguments, null, OverloadResolver.Restrictions.None);
7189                 }
7190
7191                 public override void FlowAnalysis (FlowAnalysisContext fc)
7192                 {
7193                         if (mg.IsConditionallyExcluded)
7194                                 return;
7195
7196                         var da = conditional_access_receiver ? fc.BranchDefiniteAssignment () : null;
7197
7198                         mg.FlowAnalysis (fc);
7199
7200                         if (arguments != null)
7201                                 arguments.FlowAnalysis (fc);
7202
7203                         if (conditional_access_receiver)
7204                                 fc.DefiniteAssignment = da;
7205                 }
7206
7207                 public override string GetSignatureForError ()
7208                 {
7209                         return mg.GetSignatureForError ();
7210                 }
7211
7212                 public override bool HasConditionalAccess ()
7213                 {
7214                         return expr.HasConditionalAccess ();
7215                 }
7216
7217                 //
7218                 // If a member is a method or event, or if it is a constant, field or property of either a delegate type
7219                 // or the type dynamic, then the member is invocable
7220                 //
7221                 public static bool IsMemberInvocable (MemberSpec member)
7222                 {
7223                         switch (member.Kind) {
7224                         case MemberKind.Event:
7225                                 return true;
7226                         case MemberKind.Field:
7227                         case MemberKind.Property:
7228                                 var m = member as IInterfaceMemberSpec;
7229                                 return m.MemberType.IsDelegate || m.MemberType.BuiltinType == BuiltinTypeSpec.Type.Dynamic;
7230                         default:
7231                                 return false;
7232                         }
7233                 }
7234
7235                 public static bool IsSpecialMethodInvocation (ResolveContext ec, MethodSpec method, Location loc)
7236                 {
7237                         if (!method.IsReservedMethod)
7238                                 return false;
7239
7240                         if (ec.HasSet (ResolveContext.Options.InvokeSpecialName) || ec.CurrentMemberDefinition.IsCompilerGenerated)
7241                                 return false;
7242
7243                         ec.Report.SymbolRelatedToPreviousError (method);
7244                         ec.Report.Error (571, loc, "`{0}': cannot explicitly call operator or accessor",
7245                                 method.GetSignatureForError ());
7246         
7247                         return true;
7248                 }
7249
7250                 public override void Emit (EmitContext ec)
7251                 {
7252                         if (mg.IsConditionallyExcluded)
7253                                 return;
7254
7255                         if (conditional_access_receiver)
7256                                 mg.EmitCall (ec, arguments, type, false);
7257                         else
7258                                 mg.EmitCall (ec, arguments, false);
7259                 }
7260                 
7261                 public override void EmitStatement (EmitContext ec)
7262                 {
7263                         if (mg.IsConditionallyExcluded)
7264                                 return;
7265
7266                         if (conditional_access_receiver)
7267                                 mg.EmitCall (ec, arguments, type, true);
7268                         else
7269                                 mg.EmitCall (ec, arguments, true);
7270                 }
7271
7272                 public override SLE.Expression MakeExpression (BuilderContext ctx)
7273                 {
7274                         return MakeExpression (ctx, mg.InstanceExpression, mg.BestCandidate, arguments);
7275                 }
7276
7277                 public static SLE.Expression MakeExpression (BuilderContext ctx, Expression instance, MethodSpec mi, Arguments args)
7278                 {
7279 #if STATIC
7280                         throw new NotSupportedException ();
7281 #else
7282                         var instance_expr = instance == null ? null : instance.MakeExpression (ctx);
7283                         return SLE.Expression.Call (instance_expr, (MethodInfo) mi.GetMetaInfo (), Arguments.MakeExpression (args, ctx));
7284 #endif
7285                 }
7286
7287                 public override object Accept (StructuralVisitor visitor)
7288                 {
7289                         return visitor.Visit (this);
7290                 }
7291         }
7292
7293         //
7294         // Implements simple new expression 
7295         //
7296         public class New : ExpressionStatement, IMemoryLocation
7297         {
7298                 protected Arguments arguments;
7299
7300                 //
7301                 // During bootstrap, it contains the RequestedType,
7302                 // but if `type' is not null, it *might* contain a NewDelegate
7303                 // (because of field multi-initialization)
7304                 //
7305                 protected Expression RequestedType;
7306
7307                 protected MethodSpec method;
7308
7309                 public New (Expression requested_type, Arguments arguments, Location l)
7310                 {
7311                         RequestedType = requested_type;
7312                         this.arguments = arguments;
7313                         loc = l;
7314                 }
7315
7316                 #region Properties
7317                 public Arguments Arguments {
7318                         get {
7319                                 return arguments;
7320                         }
7321                 }
7322
7323                 //
7324                 // Returns true for resolved `new S()' when S does not declare parameterless constructor
7325                 //
7326                 public bool IsGeneratedStructConstructor {
7327                         get {
7328                                 return arguments == null && method == null && type.IsStruct && GetType () == typeof (New);
7329                         }
7330                 }
7331
7332                 public Expression TypeExpression {
7333                         get {
7334                                 return RequestedType;
7335                         }
7336                 }
7337
7338                 #endregion
7339
7340                 /// <summary>
7341                 /// Converts complex core type syntax like 'new int ()' to simple constant
7342                 /// </summary>
7343                 public static Constant Constantify (TypeSpec t, Location loc)
7344                 {
7345                         switch (t.BuiltinType) {
7346                         case BuiltinTypeSpec.Type.Int:
7347                                 return new IntConstant (t, 0, loc);
7348                         case BuiltinTypeSpec.Type.UInt:
7349                                 return new UIntConstant (t, 0, loc);
7350                         case BuiltinTypeSpec.Type.Long:
7351                                 return new LongConstant (t, 0, loc);
7352                         case BuiltinTypeSpec.Type.ULong:
7353                                 return new ULongConstant (t, 0, loc);
7354                         case BuiltinTypeSpec.Type.Float:
7355                                 return new FloatConstant (t, 0, loc);
7356                         case BuiltinTypeSpec.Type.Double:
7357                                 return new DoubleConstant (t, 0, loc);
7358                         case BuiltinTypeSpec.Type.Short:
7359                                 return new ShortConstant (t, 0, loc);
7360                         case BuiltinTypeSpec.Type.UShort:
7361                                 return new UShortConstant (t, 0, loc);
7362                         case BuiltinTypeSpec.Type.SByte:
7363                                 return new SByteConstant (t, 0, loc);
7364                         case BuiltinTypeSpec.Type.Byte:
7365                                 return new ByteConstant (t, 0, loc);
7366                         case BuiltinTypeSpec.Type.Char:
7367                                 return new CharConstant (t, '\0', loc);
7368                         case BuiltinTypeSpec.Type.Bool:
7369                                 return new BoolConstant (t, false, loc);
7370                         case BuiltinTypeSpec.Type.Decimal:
7371                                 return new DecimalConstant (t, 0, loc);
7372                         }
7373
7374                         if (t.IsEnum)
7375                                 return new EnumConstant (Constantify (EnumSpec.GetUnderlyingType (t), loc), t);
7376
7377                         if (t.IsNullableType)
7378                                 return Nullable.LiftedNull.Create (t, loc);
7379
7380                         return null;
7381                 }
7382
7383                 public override bool ContainsEmitWithAwait ()
7384                 {
7385                         return arguments != null && arguments.ContainsEmitWithAwait ();
7386                 }
7387
7388                 //
7389                 // Checks whether the type is an interface that has the
7390                 // [ComImport, CoClass] attributes and must be treated
7391                 // specially
7392                 //
7393                 public Expression CheckComImport (ResolveContext ec)
7394                 {
7395                         if (!type.IsInterface)
7396                                 return null;
7397
7398                         //
7399                         // Turn the call into:
7400                         // (the-interface-stated) (new class-referenced-in-coclassattribute ())
7401                         //
7402                         var real_class = type.MemberDefinition.GetAttributeCoClass ();
7403                         if (real_class == null)
7404                                 return null;
7405
7406                         New proxy = new New (new TypeExpression (real_class, loc), arguments, loc);
7407                         Cast cast = new Cast (new TypeExpression (type, loc), proxy, loc);
7408                         return cast.Resolve (ec);
7409                 }
7410
7411                 public override Expression CreateExpressionTree (ResolveContext ec)
7412                 {
7413                         Arguments args;
7414                         if (method == null) {
7415                                 args = new Arguments (1);
7416                                 args.Add (new Argument (new TypeOf (type, loc)));
7417                         } else {
7418                                 args = Arguments.CreateForExpressionTree (ec,
7419                                         arguments, new TypeOfMethod (method, loc));
7420                         }
7421
7422                         return CreateExpressionFactoryCall (ec, "New", args);
7423                 }
7424                 
7425                 protected override Expression DoResolve (ResolveContext ec)
7426                 {
7427                         type = RequestedType.ResolveAsType (ec);
7428                         if (type == null)
7429                                 return null;
7430
7431                         eclass = ExprClass.Value;
7432
7433                         if (type.IsPointer) {
7434                                 ec.Report.Error (1919, loc, "Unsafe type `{0}' cannot be used in an object creation expression",
7435                                         type.GetSignatureForError ());
7436                                 return null;
7437                         }
7438
7439                         if (arguments == null) {
7440                                 Constant c = Constantify (type, RequestedType.Location);
7441                                 if (c != null)
7442                                         return ReducedExpression.Create (c, this);
7443                         }
7444
7445                         if (type.IsDelegate) {
7446                                 return (new NewDelegate (type, arguments, loc)).Resolve (ec);
7447                         }
7448
7449                         var tparam = type as TypeParameterSpec;
7450                         if (tparam != null) {
7451                                 //
7452                                 // Check whether the type of type parameter can be constructed. BaseType can be a struct for method overrides
7453                                 // where type parameter constraint is inflated to struct
7454                                 //
7455                                 if ((tparam.SpecialConstraint & (SpecialConstraint.Struct | SpecialConstraint.Constructor)) == 0 && !TypeSpec.IsValueType (tparam)) {
7456                                         ec.Report.Error (304, loc,
7457                                                 "Cannot create an instance of the variable type `{0}' because it does not have the new() constraint",
7458                                                 type.GetSignatureForError ());
7459                                 }
7460
7461                                 if ((arguments != null) && (arguments.Count != 0)) {
7462                                         ec.Report.Error (417, loc,
7463                                                 "`{0}': cannot provide arguments when creating an instance of a variable type",
7464                                                 type.GetSignatureForError ());
7465                                 }
7466
7467                                 return this;
7468                         }
7469
7470                         if (type.IsStatic) {
7471                                 ec.Report.SymbolRelatedToPreviousError (type);
7472                                 ec.Report.Error (712, loc, "Cannot create an instance of the static class `{0}'", type.GetSignatureForError ());
7473                                 return null;
7474                         }
7475
7476                         if (type.IsInterface || type.IsAbstract){
7477                                 if (!TypeManager.IsGenericType (type)) {
7478                                         RequestedType = CheckComImport (ec);
7479                                         if (RequestedType != null)
7480                                                 return RequestedType;
7481                                 }
7482                                 
7483                                 ec.Report.SymbolRelatedToPreviousError (type);
7484                                 ec.Report.Error (144, loc, "Cannot create an instance of the abstract class or interface `{0}'", type.GetSignatureForError ());
7485                                 return null;
7486                         }
7487
7488                         bool dynamic;
7489                         if (arguments != null) {
7490                                 arguments.Resolve (ec, out dynamic);
7491                         } else {
7492                                 dynamic = false;
7493                         }
7494
7495                         method = ConstructorLookup (ec, type, ref arguments, loc);
7496
7497                         if (dynamic) {
7498                                 arguments.Insert (0, new Argument (new TypeOf (type, loc).Resolve (ec), Argument.AType.DynamicTypeName));
7499                                 return new DynamicConstructorBinder (type, arguments, loc).Resolve (ec);
7500                         }
7501
7502                         return this;
7503                 }
7504
7505                 void DoEmitTypeParameter (EmitContext ec)
7506                 {
7507                         var m = ec.Module.PredefinedMembers.ActivatorCreateInstance.Resolve (loc);
7508                         if (m == null)
7509                                 return;
7510
7511                         var ctor_factory = m.MakeGenericMethod (ec.MemberContext, type);
7512                         ec.Emit (OpCodes.Call, ctor_factory);
7513                 }
7514
7515                 //
7516                 // This Emit can be invoked in two contexts:
7517                 //    * As a mechanism that will leave a value on the stack (new object)
7518                 //    * As one that wont (init struct)
7519                 //
7520                 // If we are dealing with a ValueType, we have a few
7521                 // situations to deal with:
7522                 //
7523                 //    * The target is a ValueType, and we have been provided
7524                 //      the instance (this is easy, we are being assigned).
7525                 //
7526                 //    * The target of New is being passed as an argument,
7527                 //      to a boxing operation or a function that takes a
7528                 //      ValueType.
7529                 //
7530                 //      In this case, we need to create a temporary variable
7531                 //      that is the argument of New.
7532                 //
7533                 // Returns whether a value is left on the stack
7534                 //
7535                 // *** Implementation note ***
7536                 //
7537                 // To benefit from this optimization, each assignable expression
7538                 // has to manually cast to New and call this Emit.
7539                 //
7540                 // TODO: It's worth to implement it for arrays and fields
7541                 //
7542                 public virtual bool Emit (EmitContext ec, IMemoryLocation target)
7543                 {
7544                         bool is_value_type = type.IsStructOrEnum;
7545                         VariableReference vr = target as VariableReference;
7546
7547                         if (target != null && is_value_type && (vr != null || method == null)) {
7548                                 target.AddressOf (ec, AddressOp.Store);
7549                         } else if (vr != null && vr.IsRef) {
7550                                 vr.EmitLoad (ec);
7551                         }
7552
7553                         if (arguments != null) {
7554                                 if (ec.HasSet (BuilderContext.Options.AsyncBody) && (arguments.Count > (this is NewInitialize ? 0 : 1)) && arguments.ContainsEmitWithAwait ())
7555                                         arguments = arguments.Emit (ec, false, true);
7556
7557                                 arguments.Emit (ec);
7558                         }
7559
7560                         if (is_value_type) {
7561                                 if (method == null) {
7562                                         ec.Emit (OpCodes.Initobj, type);
7563                                         return false;
7564                                 }
7565
7566                                 if (vr != null) {
7567                                         ec.MarkCallEntry (loc);
7568                                         ec.Emit (OpCodes.Call, method);
7569                                         return false;
7570                                 }
7571                         }
7572                         
7573                         if (type is TypeParameterSpec) {
7574                                 DoEmitTypeParameter (ec);
7575                                 return true;
7576                         }
7577
7578                         ec.MarkCallEntry (loc);
7579                         ec.Emit (OpCodes.Newobj, method);
7580                         return true;
7581                 }
7582
7583                 public override void Emit (EmitContext ec)
7584                 {
7585                         LocalTemporary v = null;
7586                         if (method == null && type.IsStructOrEnum) {
7587                                 // TODO: Use temporary variable from pool
7588                                 v = new LocalTemporary (type);
7589                         }
7590
7591                         if (!Emit (ec, v))
7592                                 v.Emit (ec);
7593                 }
7594
7595                 public override void EmitStatement (EmitContext ec)
7596                 {
7597                         LocalTemporary v = null;
7598                         if (method == null && TypeSpec.IsValueType (type)) {
7599                                 // TODO: Use temporary variable from pool
7600                                 v = new LocalTemporary (type);
7601                         }
7602
7603                         if (Emit (ec, v))
7604                                 ec.Emit (OpCodes.Pop);
7605                 }
7606
7607                 public override void FlowAnalysis (FlowAnalysisContext fc)
7608                 {
7609                         if (arguments != null)
7610                                 arguments.FlowAnalysis (fc);
7611                 }
7612
7613                 public void AddressOf (EmitContext ec, AddressOp mode)
7614                 {
7615                         EmitAddressOf (ec, mode);
7616                 }
7617
7618                 protected virtual IMemoryLocation EmitAddressOf (EmitContext ec, AddressOp mode)
7619                 {
7620                         LocalTemporary value_target = new LocalTemporary (type);
7621
7622                         if (type is TypeParameterSpec) {
7623                                 DoEmitTypeParameter (ec);
7624                                 value_target.Store (ec);
7625                                 value_target.AddressOf (ec, mode);
7626                                 return value_target;
7627                         }
7628
7629                         value_target.AddressOf (ec, AddressOp.Store);
7630
7631                         if (method == null) {
7632                                 ec.Emit (OpCodes.Initobj, type);
7633                         } else {
7634                                 if (arguments != null)
7635                                         arguments.Emit (ec);
7636
7637                                 ec.Emit (OpCodes.Call, method);
7638                         }
7639                         
7640                         value_target.AddressOf (ec, mode);
7641                         return value_target;
7642                 }
7643
7644                 protected override void CloneTo (CloneContext clonectx, Expression t)
7645                 {
7646                         New target = (New) t;
7647
7648                         target.RequestedType = RequestedType.Clone (clonectx);
7649                         if (arguments != null){
7650                                 target.arguments = arguments.Clone (clonectx);
7651                         }
7652                 }
7653
7654                 public override SLE.Expression MakeExpression (BuilderContext ctx)
7655                 {
7656 #if STATIC
7657                         return base.MakeExpression (ctx);
7658 #else
7659                         return SLE.Expression.New ((ConstructorInfo) method.GetMetaInfo (), Arguments.MakeExpression (arguments, ctx));
7660 #endif
7661                 }
7662                 
7663                 public override object Accept (StructuralVisitor visitor)
7664                 {
7665                         return visitor.Visit (this);
7666                 }
7667         }
7668
7669         //
7670         // Array initializer expression, the expression is allowed in
7671         // variable or field initialization only which makes it tricky as
7672         // the type has to be infered based on the context either from field
7673         // type or variable type (think of multiple declarators)
7674         //
7675         public class ArrayInitializer : Expression
7676         {
7677                 List<Expression> elements;
7678                 BlockVariable variable;
7679
7680                 public ArrayInitializer (List<Expression> init, Location loc)
7681                 {
7682                         elements = init;
7683                         this.loc = loc;
7684                 }
7685
7686                 public ArrayInitializer (int count, Location loc)
7687                         : this (new List<Expression> (count), loc)
7688                 {
7689                 }
7690
7691                 public ArrayInitializer (Location loc)
7692                         : this (4, loc)
7693                 {
7694                 }
7695
7696                 #region Properties
7697
7698                 public int Count {
7699                         get { return elements.Count; }
7700                 }
7701
7702                 public List<Expression> Elements {
7703                         get {
7704                                 return elements;
7705                         }
7706                 }
7707
7708                 public Expression this [int index] {
7709                         get {
7710                                 return elements [index];
7711                         }
7712                 }
7713
7714                 public BlockVariable VariableDeclaration {
7715                         get {
7716                                 return variable;
7717                         }
7718                         set {
7719                                 variable = value;
7720                         }
7721                 }
7722
7723                 #endregion
7724
7725                 public void Add (Expression expr)
7726                 {
7727                         elements.Add (expr);
7728                 }
7729
7730                 public override bool ContainsEmitWithAwait ()
7731                 {
7732                         throw new NotSupportedException ();
7733                 }
7734
7735                 public override Expression CreateExpressionTree (ResolveContext ec)
7736                 {
7737                         throw new NotSupportedException ("ET");
7738                 }
7739
7740                 protected override void CloneTo (CloneContext clonectx, Expression t)
7741                 {
7742                         var target = (ArrayInitializer) t;
7743
7744                         target.elements = new List<Expression> (elements.Count);
7745                         foreach (var element in elements)
7746                                 target.elements.Add (element.Clone (clonectx));
7747                 }
7748
7749                 protected override Expression DoResolve (ResolveContext rc)
7750                 {
7751                         var current_field = rc.CurrentMemberDefinition as FieldBase;
7752                         TypeExpression type;
7753                         if (current_field != null && rc.CurrentAnonymousMethod == null) {
7754                                 type = new TypeExpression (current_field.MemberType, current_field.Location);
7755                         } else if (variable != null) {
7756                                 if (variable.TypeExpression is VarExpr) {
7757                                         rc.Report.Error (820, loc, "An implicitly typed local variable declarator cannot use an array initializer");
7758                                         return EmptyExpression.Null;
7759                                 }
7760
7761                                 type = new TypeExpression (variable.Variable.Type, variable.Variable.Location);
7762                         } else {
7763                                 throw new NotImplementedException ("Unexpected array initializer context");
7764                         }
7765
7766                         return new ArrayCreation (type, this).Resolve (rc);
7767                 }
7768
7769                 public override void Emit (EmitContext ec)
7770                 {
7771                         throw new InternalErrorException ("Missing Resolve call");
7772                 }
7773
7774                 public override void FlowAnalysis (FlowAnalysisContext fc)
7775                 {
7776                         throw new InternalErrorException ("Missing Resolve call");
7777                 }
7778                 
7779                 public override object Accept (StructuralVisitor visitor)
7780                 {
7781                         return visitor.Visit (this);
7782                 }
7783         }
7784
7785         /// <summary>
7786         ///   14.5.10.2: Represents an array creation expression.
7787         /// </summary>
7788         ///
7789         /// <remarks>
7790         ///   There are two possible scenarios here: one is an array creation
7791         ///   expression that specifies the dimensions and optionally the
7792         ///   initialization data and the other which does not need dimensions
7793         ///   specified but where initialization data is mandatory.
7794         /// </remarks>
7795         public class ArrayCreation : Expression
7796         {
7797                 FullNamedExpression requested_base_type;
7798                 ArrayInitializer initializers;
7799
7800                 //
7801                 // The list of Argument types.
7802                 // This is used to construct the `newarray' or constructor signature
7803                 //
7804                 protected List<Expression> arguments;
7805                 
7806                 protected TypeSpec array_element_type;
7807                 int num_arguments;
7808                 protected int dimensions;
7809                 protected readonly ComposedTypeSpecifier rank;
7810                 Expression first_emit;
7811                 LocalTemporary first_emit_temp;
7812
7813                 protected List<Expression> array_data;
7814
7815                 Dictionary<int, int> bounds;
7816
7817 #if STATIC
7818                 // The number of constants in array initializers
7819                 int const_initializers_count;
7820                 bool only_constant_initializers;
7821 #endif
7822                 public ArrayCreation (FullNamedExpression requested_base_type, List<Expression> exprs, ComposedTypeSpecifier rank, ArrayInitializer initializers, Location l)
7823                         : this (requested_base_type, rank, initializers, l)
7824                 {
7825                         arguments = new List<Expression> (exprs);
7826                         num_arguments = arguments.Count;
7827                 }
7828
7829                 //
7830                 // For expressions like int[] foo = new int[] { 1, 2, 3 };
7831                 //
7832                 public ArrayCreation (FullNamedExpression requested_base_type, ComposedTypeSpecifier rank, ArrayInitializer initializers, Location loc)
7833                 {
7834                         this.requested_base_type = requested_base_type;
7835                         this.rank = rank;
7836                         this.initializers = initializers;
7837                         this.loc = loc;
7838
7839                         if (rank != null)
7840                                 num_arguments = rank.Dimension;
7841                 }
7842
7843                 //
7844                 // For compiler generated single dimensional arrays only
7845                 //
7846                 public ArrayCreation (FullNamedExpression requested_base_type, ArrayInitializer initializers, Location loc)
7847                         : this (requested_base_type, ComposedTypeSpecifier.SingleDimension, initializers, loc)
7848                 {
7849                 }
7850
7851                 //
7852                 // For expressions like int[] foo = { 1, 2, 3 };
7853                 //
7854                 public ArrayCreation (FullNamedExpression requested_base_type, ArrayInitializer initializers)
7855                         : this (requested_base_type, null, initializers, initializers.Location)
7856                 {
7857                 }
7858
7859                 public ComposedTypeSpecifier Rank {
7860                         get {
7861                                 return this.rank;
7862                         }
7863                 }
7864                 
7865                 public FullNamedExpression TypeExpression {
7866                         get {
7867                                 return this.requested_base_type;
7868                         }
7869                 }
7870                 
7871                 public ArrayInitializer Initializers {
7872                         get {
7873                                 return this.initializers;
7874                         }
7875                 }
7876
7877                 bool CheckIndices (ResolveContext ec, ArrayInitializer probe, int idx, bool specified_dims, int child_bounds)
7878                 {
7879                         if (initializers != null && bounds == null) {
7880                                 //
7881                                 // We use this to store all the data values in the order in which we
7882                                 // will need to store them in the byte blob later
7883                                 //
7884                                 array_data = new List<Expression> (probe.Count);
7885                                 bounds = new Dictionary<int, int> ();
7886                         }
7887
7888                         if (specified_dims) { 
7889                                 Expression a = arguments [idx];
7890                                 a = a.Resolve (ec);
7891                                 if (a == null)
7892                                         return false;
7893
7894                                 a = ConvertExpressionToArrayIndex (ec, a);
7895                                 if (a == null)
7896                                         return false;
7897
7898                                 arguments[idx] = a;
7899
7900                                 if (initializers != null) {
7901                                         Constant c = a as Constant;
7902                                         if (c == null && a is ArrayIndexCast)
7903                                                 c = ((ArrayIndexCast) a).Child as Constant;
7904
7905                                         if (c == null) {
7906                                                 ec.Report.Error (150, a.Location, "A constant value is expected");
7907                                                 return false;
7908                                         }
7909
7910                                         int value;
7911                                         try {
7912                                                 value = System.Convert.ToInt32 (c.GetValue ());
7913                                         } catch {
7914                                                 ec.Report.Error (150, a.Location, "A constant value is expected");
7915                                                 return false;
7916                                         }
7917
7918                                         // TODO: probe.Count does not fit ulong in
7919                                         if (value != probe.Count) {
7920                                                 ec.Report.Error (847, loc, "An array initializer of length `{0}' was expected", value.ToString ());
7921                                                 return false;
7922                                         }
7923
7924                                         bounds[idx] = value;
7925                                 }
7926                         }
7927
7928                         if (initializers == null)
7929                                 return true;
7930
7931                         for (int i = 0; i < probe.Count; ++i) {
7932                                 var o = probe [i];
7933                                 if (o is ArrayInitializer) {
7934                                         var sub_probe = o as ArrayInitializer;
7935                                         if (idx + 1 >= dimensions){
7936                                                 ec.Report.Error (623, loc, "Array initializers can only be used in a variable or field initializer. Try using a new expression instead");
7937                                                 return false;
7938                                         }
7939
7940                                         // When we don't have explicitly specified dimensions, record whatever dimension we first encounter at each level
7941                                         if (!bounds.ContainsKey(idx + 1))
7942                                                 bounds[idx + 1] = sub_probe.Count;
7943
7944                                         if (bounds[idx + 1] != sub_probe.Count) {
7945                                                 ec.Report.Error(847, sub_probe.Location, "An array initializer of length `{0}' was expected", bounds[idx + 1].ToString());
7946                                                 return false;
7947                                         }
7948
7949                                         bool ret = CheckIndices (ec, sub_probe, idx + 1, specified_dims, child_bounds - 1);
7950                                         if (!ret)
7951                                                 return false;
7952                                 } else if (child_bounds > 1) {
7953                                         ec.Report.Error (846, o.Location, "A nested array initializer was expected");
7954                                 } else {
7955                                         Expression element = ResolveArrayElement (ec, o);
7956                                         if (element == null)
7957                                                 continue;
7958 #if STATIC
7959                                         // Initializers with the default values can be ignored
7960                                         Constant c = element as Constant;
7961                                         if (c != null) {
7962                                                 if (!c.IsDefaultInitializer (array_element_type)) {
7963                                                         ++const_initializers_count;
7964                                                 }
7965                                         } else {
7966                                                 only_constant_initializers = false;
7967                                         }
7968 #endif                                  
7969                                         array_data.Add (element);
7970                                 }
7971                         }
7972
7973                         return true;
7974                 }
7975
7976                 public override bool ContainsEmitWithAwait ()
7977                 {
7978                         foreach (var arg in arguments) {
7979                                 if (arg.ContainsEmitWithAwait ())
7980                                         return true;
7981                         }
7982
7983                         return InitializersContainAwait ();
7984                 }
7985
7986                 public override Expression CreateExpressionTree (ResolveContext ec)
7987                 {
7988                         Arguments args;
7989
7990                         if (array_data == null) {
7991                                 args = new Arguments (arguments.Count + 1);
7992                                 args.Add (new Argument (new TypeOf (array_element_type, loc)));
7993                                 foreach (Expression a in arguments)
7994                                         args.Add (new Argument (a.CreateExpressionTree (ec)));
7995
7996                                 return CreateExpressionFactoryCall (ec, "NewArrayBounds", args);
7997                         }
7998
7999                         if (dimensions > 1) {
8000                                 ec.Report.Error (838, loc, "An expression tree cannot contain a multidimensional array initializer");
8001                                 return null;
8002                         }
8003
8004                         args = new Arguments (array_data == null ? 1 : array_data.Count + 1);
8005                         args.Add (new Argument (new TypeOf (array_element_type, loc)));
8006                         if (array_data != null) {
8007                                 for (int i = 0; i < array_data.Count; ++i) {
8008                                         Expression e = array_data [i];
8009                                         args.Add (new Argument (e.CreateExpressionTree (ec)));
8010                                 }
8011                         }
8012
8013                         return CreateExpressionFactoryCall (ec, "NewArrayInit", args);
8014                 }               
8015                 
8016                 void UpdateIndices (ResolveContext rc)
8017                 {
8018                         int i = 0;
8019                         for (var probe = initializers; probe != null;) {
8020                                 Expression e = new IntConstant (rc.BuiltinTypes, probe.Count, Location.Null);
8021                                 arguments.Add (e);
8022                                 bounds[i++] = probe.Count;
8023
8024                                 if (probe.Count > 0 && probe [0] is ArrayInitializer) {
8025                                         probe = (ArrayInitializer) probe[0];
8026                                 } else if (dimensions > i) {
8027                                         continue;
8028                                 } else {
8029                                         return;
8030                                 }
8031                         }
8032                 }
8033
8034                 protected override void Error_NegativeArrayIndex (ResolveContext ec, Location loc)
8035                 {
8036                         ec.Report.Error (248, loc, "Cannot create an array with a negative size");
8037                 }
8038
8039                 public override void FlowAnalysis (FlowAnalysisContext fc)
8040                 {
8041                         foreach (var arg in arguments)
8042                                 arg.FlowAnalysis (fc);
8043
8044                         if (array_data != null) {
8045                                 foreach (var ad in array_data)
8046                                         ad.FlowAnalysis (fc);
8047                         }
8048                 }
8049
8050                 bool InitializersContainAwait ()
8051                 {
8052                         if (array_data == null)
8053                                 return false;
8054
8055                         foreach (var expr in array_data) {
8056                                 if (expr.ContainsEmitWithAwait ())
8057                                         return true;
8058                         }
8059
8060                         return false;
8061                 }
8062
8063                 protected virtual Expression ResolveArrayElement (ResolveContext ec, Expression element)
8064                 {
8065                         element = element.Resolve (ec);
8066                         if (element == null)
8067                                 return null;
8068
8069                         if (element is CompoundAssign.TargetExpression) {
8070                                 if (first_emit != null)
8071                                         throw new InternalErrorException ("Can only handle one mutator at a time");
8072                                 first_emit = element;
8073                                 element = first_emit_temp = new LocalTemporary (element.Type);
8074                         }
8075
8076                         return Convert.ImplicitConversionRequired (
8077                                 ec, element, array_element_type, loc);
8078                 }
8079
8080                 protected bool ResolveInitializers (ResolveContext ec)
8081                 {
8082 #if STATIC
8083                         only_constant_initializers = true;
8084 #endif
8085
8086                         if (arguments != null) {
8087                                 bool res = true;
8088                                 for (int i = 0; i < arguments.Count; ++i) {
8089                                         res &= CheckIndices (ec, initializers, i, true, dimensions);
8090                                         if (initializers != null)
8091                                                 break;
8092                                 }
8093
8094                                 return res;
8095                         }
8096
8097                         arguments = new List<Expression> ();
8098
8099                         if (!CheckIndices (ec, initializers, 0, false, dimensions))
8100                                 return false;
8101                                 
8102                         UpdateIndices (ec);
8103                                 
8104                         return true;
8105                 }
8106
8107                 //
8108                 // Resolved the type of the array
8109                 //
8110                 bool ResolveArrayType (ResolveContext ec)
8111                 {
8112                         //
8113                         // Lookup the type
8114                         //
8115                         FullNamedExpression array_type_expr;
8116                         if (num_arguments > 0) {
8117                                 array_type_expr = new ComposedCast (requested_base_type, rank);
8118                         } else {
8119                                 array_type_expr = requested_base_type;
8120                         }
8121
8122                         type = array_type_expr.ResolveAsType (ec);
8123                         if (array_type_expr == null)
8124                                 return false;
8125
8126                         var ac = type as ArrayContainer;
8127                         if (ac == null) {
8128                                 ec.Report.Error (622, loc, "Can only use array initializer expressions to assign to array types. Try using a new expression instead");
8129                                 return false;
8130                         }
8131
8132                         array_element_type = ac.Element;
8133                         dimensions = ac.Rank;
8134
8135                         return true;
8136                 }
8137
8138                 protected override Expression DoResolve (ResolveContext ec)
8139                 {
8140                         if (type != null)
8141                                 return this;
8142
8143                         if (!ResolveArrayType (ec))
8144                                 return null;
8145
8146                         //
8147                         // validate the initializers and fill in any missing bits
8148                         //
8149                         if (!ResolveInitializers (ec))
8150                                 return null;
8151
8152                         eclass = ExprClass.Value;
8153                         return this;
8154                 }
8155
8156                 byte [] MakeByteBlob ()
8157                 {
8158                         int factor;
8159                         byte [] data;
8160                         byte [] element;
8161                         int count = array_data.Count;
8162
8163                         TypeSpec element_type = array_element_type;
8164                         if (element_type.IsEnum)
8165                                 element_type = EnumSpec.GetUnderlyingType (element_type);
8166
8167                         factor = BuiltinTypeSpec.GetSize (element_type);
8168                         if (factor == 0)
8169                                 throw new Exception ("unrecognized type in MakeByteBlob: " + element_type);
8170
8171                         data = new byte [(count * factor + 3) & ~3];
8172                         int idx = 0;
8173
8174                         for (int i = 0; i < count; ++i) {
8175                                 var c = array_data[i] as Constant;
8176                                 if (c == null) {
8177                                         idx += factor;
8178                                         continue;
8179                                 }
8180
8181                                 object v = c.GetValue ();
8182
8183                                 switch (element_type.BuiltinType) {
8184                                 case BuiltinTypeSpec.Type.Long:
8185                                         long lval = (long) v;
8186
8187                                         for (int j = 0; j < factor; ++j) {
8188                                                 data[idx + j] = (byte) (lval & 0xFF);
8189                                                 lval = (lval >> 8);
8190                                         }
8191                                         break;
8192                                 case BuiltinTypeSpec.Type.ULong:
8193                                         ulong ulval = (ulong) v;
8194
8195                                         for (int j = 0; j < factor; ++j) {
8196                                                 data[idx + j] = (byte) (ulval & 0xFF);
8197                                                 ulval = (ulval >> 8);
8198                                         }
8199                                         break;
8200                                 case BuiltinTypeSpec.Type.Float:
8201                                         var fval = SingleConverter.SingleToInt32Bits((float) v);
8202
8203                                         data[idx] = (byte) (fval & 0xff);
8204                                         data[idx + 1] = (byte) ((fval >> 8) & 0xff);
8205                                         data[idx + 2] = (byte) ((fval >> 16) & 0xff);
8206                                         data[idx + 3] = (byte) (fval >> 24);
8207                                         break;
8208                                 case BuiltinTypeSpec.Type.Double:
8209                                         element = BitConverter.GetBytes ((double) v);
8210
8211                                         for (int j = 0; j < factor; ++j)
8212                                                 data[idx + j] = element[j];
8213
8214                                         // FIXME: Handle the ARM float format.
8215                                         if (!BitConverter.IsLittleEndian)
8216                                                 System.Array.Reverse (data, idx, 8);
8217                                         break;
8218                                 case BuiltinTypeSpec.Type.Char:
8219                                         int chval = (int) ((char) v);
8220
8221                                         data[idx] = (byte) (chval & 0xff);
8222                                         data[idx + 1] = (byte) (chval >> 8);
8223                                         break;
8224                                 case BuiltinTypeSpec.Type.Short:
8225                                         int sval = (int) ((short) v);
8226
8227                                         data[idx] = (byte) (sval & 0xff);
8228                                         data[idx + 1] = (byte) (sval >> 8);
8229                                         break;
8230                                 case BuiltinTypeSpec.Type.UShort:
8231                                         int usval = (int) ((ushort) v);
8232
8233                                         data[idx] = (byte) (usval & 0xff);
8234                                         data[idx + 1] = (byte) (usval >> 8);
8235                                         break;
8236                                 case BuiltinTypeSpec.Type.Int:
8237                                         int val = (int) v;
8238
8239                                         data[idx] = (byte) (val & 0xff);
8240                                         data[idx + 1] = (byte) ((val >> 8) & 0xff);
8241                                         data[idx + 2] = (byte) ((val >> 16) & 0xff);
8242                                         data[idx + 3] = (byte) (val >> 24);
8243                                         break;
8244                                 case BuiltinTypeSpec.Type.UInt:
8245                                         uint uval = (uint) v;
8246
8247                                         data[idx] = (byte) (uval & 0xff);
8248                                         data[idx + 1] = (byte) ((uval >> 8) & 0xff);
8249                                         data[idx + 2] = (byte) ((uval >> 16) & 0xff);
8250                                         data[idx + 3] = (byte) (uval >> 24);
8251                                         break;
8252                                 case BuiltinTypeSpec.Type.SByte:
8253                                         data[idx] = (byte) (sbyte) v;
8254                                         break;
8255                                 case BuiltinTypeSpec.Type.Byte:
8256                                         data[idx] = (byte) v;
8257                                         break;
8258                                 case BuiltinTypeSpec.Type.Bool:
8259                                         data[idx] = (byte) ((bool) v ? 1 : 0);
8260                                         break;
8261                                 case BuiltinTypeSpec.Type.Decimal:
8262                                         int[] bits = Decimal.GetBits ((decimal) v);
8263                                         int p = idx;
8264
8265                                         // FIXME: For some reason, this doesn't work on the MS runtime.
8266                                         int[] nbits = new int[4];
8267                                         nbits[0] = bits[3];
8268                                         nbits[1] = bits[2];
8269                                         nbits[2] = bits[0];
8270                                         nbits[3] = bits[1];
8271
8272                                         for (int j = 0; j < 4; j++) {
8273                                                 data[p++] = (byte) (nbits[j] & 0xff);
8274                                                 data[p++] = (byte) ((nbits[j] >> 8) & 0xff);
8275                                                 data[p++] = (byte) ((nbits[j] >> 16) & 0xff);
8276                                                 data[p++] = (byte) (nbits[j] >> 24);
8277                                         }
8278                                         break;
8279                                 default:
8280                                         throw new Exception ("Unrecognized type in MakeByteBlob: " + element_type);
8281                                 }
8282
8283                                 idx += factor;
8284                         }
8285
8286                         return data;
8287                 }
8288
8289                 public override SLE.Expression MakeExpression (BuilderContext ctx)
8290                 {
8291 #if STATIC
8292                         return base.MakeExpression (ctx);
8293 #else
8294                         var initializers = new SLE.Expression [array_data.Count];
8295                         for (var i = 0; i < initializers.Length; i++) {
8296                                 if (array_data [i] == null)
8297                                         initializers [i] = SLE.Expression.Default (array_element_type.GetMetaInfo ());
8298                                 else
8299                                         initializers [i] = array_data [i].MakeExpression (ctx);
8300                         }
8301
8302                         return SLE.Expression.NewArrayInit (array_element_type.GetMetaInfo (), initializers);
8303 #endif
8304                 }
8305 #if STATIC
8306                 //
8307                 // Emits the initializers for the array
8308                 //
8309                 void EmitStaticInitializers (EmitContext ec, FieldExpr stackArray)
8310                 {
8311                         var m = ec.Module.PredefinedMembers.RuntimeHelpersInitializeArray.Resolve (loc);
8312                         if (m == null)
8313                                 return;
8314
8315                         //
8316                         // First, the static data
8317                         //
8318                         byte [] data = MakeByteBlob ();
8319                         var fb = ec.CurrentTypeDefinition.Module.MakeStaticData (data, loc);
8320
8321                         if (stackArray == null) {
8322                                 ec.Emit (OpCodes.Dup);
8323                         } else {
8324                                 stackArray.Emit (ec);
8325                         }
8326
8327                         ec.Emit (OpCodes.Ldtoken, fb);
8328                         ec.Emit (OpCodes.Call, m);
8329                 }
8330 #endif
8331
8332                 //
8333                 // Emits pieces of the array that can not be computed at compile
8334                 // time (variables and string locations).
8335                 //
8336                 // This always expect the top value on the stack to be the array
8337                 //
8338                 void EmitDynamicInitializers (EmitContext ec, bool emitConstants, StackFieldExpr stackArray)
8339                 {
8340                         int dims = bounds.Count;
8341                         var current_pos = new int [dims];
8342
8343                         for (int i = 0; i < array_data.Count; i++){
8344
8345                                 Expression e = array_data [i];
8346                                 var c = e as Constant;
8347
8348                                 // Constant can be initialized via StaticInitializer
8349                                 if (c == null || (c != null && emitConstants && !c.IsDefaultInitializer (array_element_type))) {
8350
8351                                         var etype = e.Type;
8352
8353                                         if (stackArray != null) {
8354                                                 if (e.ContainsEmitWithAwait ()) {
8355                                                         e = e.EmitToField (ec);
8356                                                 }
8357
8358                                                 stackArray.EmitLoad (ec);
8359                                         } else {
8360                                                 ec.Emit (OpCodes.Dup);
8361                                         }
8362
8363                                         for (int idx = 0; idx < dims; idx++) 
8364                                                 ec.EmitInt (current_pos [idx]);
8365
8366                                         //
8367                                         // If we are dealing with a struct, get the
8368                                         // address of it, so we can store it.
8369                                         //
8370                                         if (dims == 1 && etype.IsStruct && !BuiltinTypeSpec.IsPrimitiveType (etype))
8371                                                 ec.Emit (OpCodes.Ldelema, etype);
8372
8373                                         e.Emit (ec);
8374
8375                                         ec.EmitArrayStore ((ArrayContainer) type);
8376                                 }
8377                                 
8378                                 //
8379                                 // Advance counter
8380                                 //
8381                                 for (int j = dims - 1; j >= 0; j--){
8382                                         current_pos [j]++;
8383                                         if (current_pos [j] < bounds [j])
8384                                                 break;
8385                                         current_pos [j] = 0;
8386                                 }
8387                         }
8388
8389                         if (stackArray != null)
8390                                 stackArray.PrepareCleanup (ec);
8391                 }
8392
8393                 public override void Emit (EmitContext ec)
8394                 {
8395                         var await_field = EmitToFieldSource (ec);
8396                         if (await_field != null)
8397                                 await_field.Emit (ec);
8398                 }
8399
8400                 protected sealed override FieldExpr EmitToFieldSource (EmitContext ec)
8401                 {
8402                         if (first_emit != null) {
8403                                 first_emit.Emit (ec);
8404                                 first_emit_temp.Store (ec);
8405                         }
8406
8407                         StackFieldExpr await_stack_field;
8408                         if (ec.HasSet (BuilderContext.Options.AsyncBody) && InitializersContainAwait ()) {
8409                                 await_stack_field = ec.GetTemporaryField (type);
8410                                 ec.EmitThis ();
8411                         } else {
8412                                 await_stack_field = null;
8413                         }
8414
8415                         EmitExpressionsList (ec, arguments);
8416
8417                         ec.EmitArrayNew ((ArrayContainer) type);
8418                         
8419                         if (initializers == null)
8420                                 return await_stack_field;
8421
8422                         if (await_stack_field != null)
8423                                 await_stack_field.EmitAssignFromStack (ec);
8424
8425 #if STATIC
8426                         //
8427                         // Emit static initializer for arrays which contain more than 2 items and
8428                         // the static initializer will initialize at least 25% of array values or there
8429                         // is more than 10 items to be initialized
8430                         //
8431                         // NOTE: const_initializers_count does not contain default constant values.
8432                         //
8433                         if (const_initializers_count > 2 && (array_data.Count > 10 || const_initializers_count * 4 > (array_data.Count)) &&
8434                                 (BuiltinTypeSpec.IsPrimitiveType (array_element_type) || array_element_type.IsEnum)) {
8435                                 EmitStaticInitializers (ec, await_stack_field);
8436
8437                                 if (!only_constant_initializers)
8438                                         EmitDynamicInitializers (ec, false, await_stack_field);
8439                         } else
8440 #endif
8441                         {
8442                                 EmitDynamicInitializers (ec, true, await_stack_field);
8443                         }
8444
8445                         if (first_emit_temp != null)
8446                                 first_emit_temp.Release (ec);
8447
8448                         return await_stack_field;
8449                 }
8450
8451                 public override void EncodeAttributeValue (IMemberContext rc, AttributeEncoder enc, TypeSpec targetType, TypeSpec parameterType)
8452                 {
8453                         // no multi dimensional or jagged arrays
8454                         if (arguments.Count != 1 || array_element_type.IsArray) {
8455                                 base.EncodeAttributeValue (rc, enc, targetType, parameterType);
8456                                 return;
8457                         }
8458
8459                         // No array covariance, except for array -> object
8460                         if (type != targetType) {
8461                                 if (targetType.BuiltinType != BuiltinTypeSpec.Type.Object) {
8462                                         base.EncodeAttributeValue (rc, enc, targetType, parameterType);
8463                                         return;
8464                                 }
8465
8466                                 if (enc.Encode (type) == AttributeEncoder.EncodedTypeProperties.DynamicType) {
8467                                         Attribute.Error_AttributeArgumentIsDynamic (rc, loc);
8468                                         return;
8469                                 }
8470                         }
8471
8472                         // Single dimensional array of 0 size
8473                         if (array_data == null) {
8474                                 IntConstant ic = arguments[0] as IntConstant;
8475                                 if (ic == null || !ic.IsDefaultValue) {
8476                                         base.EncodeAttributeValue (rc, enc, targetType, parameterType);
8477                                 } else {
8478                                         enc.Encode (0);
8479                                 }
8480
8481                                 return;
8482                         }
8483
8484                         enc.Encode (array_data.Count);
8485                         foreach (var element in array_data) {
8486                                 element.EncodeAttributeValue (rc, enc, array_element_type, parameterType);
8487                         }
8488                 }
8489                 
8490                 protected override void CloneTo (CloneContext clonectx, Expression t)
8491                 {
8492                         ArrayCreation target = (ArrayCreation) t;
8493
8494                         if (requested_base_type != null)
8495                                 target.requested_base_type = (FullNamedExpression)requested_base_type.Clone (clonectx);
8496
8497                         if (arguments != null){
8498                                 target.arguments = new List<Expression> (arguments.Count);
8499                                 foreach (Expression e in arguments)
8500                                         target.arguments.Add (e.Clone (clonectx));
8501                         }
8502
8503                         if (initializers != null)
8504                                 target.initializers = (ArrayInitializer) initializers.Clone (clonectx);
8505                 }
8506                 
8507                 public override object Accept (StructuralVisitor visitor)
8508                 {
8509                         return visitor.Visit (this);
8510                 }
8511         }
8512         
8513         //
8514         // Represents an implicitly typed array epxression
8515         //
8516         class ImplicitlyTypedArrayCreation : ArrayCreation
8517         {
8518                 TypeInferenceContext best_type_inference;
8519
8520                 public ImplicitlyTypedArrayCreation (ComposedTypeSpecifier rank, ArrayInitializer initializers, Location loc)
8521                         : base (null, rank, initializers, loc)
8522                 {                       
8523                 }
8524
8525                 public ImplicitlyTypedArrayCreation (ArrayInitializer initializers, Location loc)
8526                         : base (null, initializers, loc)
8527                 {
8528                 }
8529
8530                 protected override Expression DoResolve (ResolveContext ec)
8531                 {
8532                         if (type != null)
8533                                 return this;
8534
8535                         dimensions = rank.Dimension;
8536
8537                         best_type_inference = new TypeInferenceContext ();
8538
8539                         if (!ResolveInitializers (ec))
8540                                 return null;
8541
8542                         best_type_inference.FixAllTypes (ec);
8543                         array_element_type = best_type_inference.InferredTypeArguments[0];
8544                         best_type_inference = null;
8545
8546                         if (array_element_type == null ||
8547                                 array_element_type == InternalType.NullLiteral || array_element_type == InternalType.MethodGroup || array_element_type == InternalType.AnonymousMethod ||
8548                                 arguments.Count != rank.Dimension) {
8549                                 ec.Report.Error (826, loc,
8550                                         "The type of an implicitly typed array cannot be inferred from the initializer. Try specifying array type explicitly");
8551                                 return null;
8552                         }
8553
8554                         //
8555                         // At this point we found common base type for all initializer elements
8556                         // but we have to be sure that all static initializer elements are of
8557                         // same type
8558                         //
8559                         UnifyInitializerElement (ec);
8560
8561                         type = ArrayContainer.MakeType (ec.Module, array_element_type, dimensions);
8562                         eclass = ExprClass.Value;
8563                         return this;
8564                 }
8565
8566                 //
8567                 // Converts static initializer only
8568                 //
8569                 void UnifyInitializerElement (ResolveContext ec)
8570                 {
8571                         for (int i = 0; i < array_data.Count; ++i) {
8572                                 Expression e = array_data[i];
8573                                 if (e != null)
8574                                         array_data [i] = Convert.ImplicitConversion (ec, e, array_element_type, Location.Null);
8575                         }
8576                 }
8577
8578                 protected override Expression ResolveArrayElement (ResolveContext ec, Expression element)
8579                 {
8580                         element = element.Resolve (ec);
8581                         if (element != null)
8582                                 best_type_inference.AddCommonTypeBound (element.Type);
8583
8584                         return element;
8585                 }
8586         }       
8587         
8588         sealed class CompilerGeneratedThis : This
8589         {
8590                 public CompilerGeneratedThis (TypeSpec type, Location loc)
8591                         : base (loc)
8592                 {
8593                         this.type = type;
8594                 }
8595
8596                 protected override Expression DoResolve (ResolveContext rc)
8597                 {
8598                         eclass = ExprClass.Variable;
8599
8600                         var block = rc.CurrentBlock;
8601                         if (block != null) {
8602                                 var top = block.ParametersBlock.TopBlock;
8603                                 if (top.ThisVariable != null)
8604                                         variable_info = top.ThisVariable.VariableInfo;
8605
8606                         }
8607
8608                         return this;
8609                 }
8610
8611                 public override Expression DoResolveLValue (ResolveContext rc, Expression right_side)
8612                 {
8613                         return DoResolve (rc);
8614                 }
8615
8616                 public override HoistedVariable GetHoistedVariable (AnonymousExpression ae)
8617                 {
8618                         return null;
8619                 }
8620         }
8621         
8622         /// <summary>
8623         ///   Represents the `this' construct
8624         /// </summary>
8625
8626         public class This : VariableReference
8627         {
8628                 sealed class ThisVariable : ILocalVariable
8629                 {
8630                         public static readonly ILocalVariable Instance = new ThisVariable ();
8631
8632                         public void Emit (EmitContext ec)
8633                         {
8634                                 ec.EmitThis ();
8635                         }
8636
8637                         public void EmitAssign (EmitContext ec)
8638                         {
8639                                 throw new InvalidOperationException ();
8640                         }
8641
8642                         public void EmitAddressOf (EmitContext ec)
8643                         {
8644                                 ec.EmitThis ();
8645                         }
8646                 }
8647
8648                 protected VariableInfo variable_info;
8649
8650                 public This (Location loc)
8651                 {
8652                         this.loc = loc;
8653                 }
8654
8655                 #region Properties
8656
8657                 public override string Name {
8658                         get { return "this"; }
8659                 }
8660
8661                 public override bool IsLockedByStatement {
8662                         get {
8663                                 return false;
8664                         }
8665                         set {
8666                         }
8667                 }
8668
8669                 public override bool IsRef {
8670                         get { return type.IsStruct; }
8671                 }
8672
8673                 public override bool IsSideEffectFree {
8674                         get {
8675                                 return true;
8676                         }
8677                 }
8678
8679                 protected override ILocalVariable Variable {
8680                         get { return ThisVariable.Instance; }
8681                 }
8682
8683                 public override VariableInfo VariableInfo {
8684                         get { return variable_info; }
8685                 }
8686
8687                 public override bool IsFixed {
8688                         get { return false; }
8689                 }
8690
8691                 #endregion
8692
8693                 void CheckStructThisDefiniteAssignment (FlowAnalysisContext fc)
8694                 {
8695                         //
8696                         // It's null for all cases when we don't need to check `this'
8697                         // definitive assignment
8698                         //
8699                         if (variable_info == null)
8700                                 return;
8701
8702                         if (fc.IsDefinitelyAssigned (variable_info))
8703                                 return;
8704
8705                         fc.Report.Error (188, loc, "The `this' object cannot be used before all of its fields are assigned to");
8706                 }
8707
8708                 protected virtual void Error_ThisNotAvailable (ResolveContext ec)
8709                 {
8710                         if (ec.IsStatic && !ec.HasSet (ResolveContext.Options.ConstantScope)) {
8711                                 ec.Report.Error (26, loc, "Keyword `this' is not valid in a static property, static method, or static field initializer");
8712                         } else if (ec.CurrentAnonymousMethod != null) {
8713                                 ec.Report.Error (1673, loc,
8714                                         "Anonymous methods inside structs cannot access instance members of `this'. " +
8715                                         "Consider copying `this' to a local variable outside the anonymous method and using the local instead");
8716                         } else {
8717                                 ec.Report.Error (27, loc, "Keyword `this' is not available in the current context");
8718                         }
8719                 }
8720
8721                 public override void FlowAnalysis (FlowAnalysisContext fc)
8722                 {
8723                         CheckStructThisDefiniteAssignment (fc);
8724                 }
8725
8726                 public override HoistedVariable GetHoistedVariable (AnonymousExpression ae)
8727                 {
8728                         if (ae == null)
8729                                 return null;
8730
8731                         AnonymousMethodStorey storey = ae.Storey;
8732                         return storey != null ? storey.HoistedThis : null;
8733                 }
8734
8735                 public static bool IsThisAvailable (ResolveContext ec, bool ignoreAnonymous)
8736                 {
8737                         if (ec.IsStatic || ec.HasAny (ResolveContext.Options.FieldInitializerScope | ResolveContext.Options.BaseInitializer | ResolveContext.Options.ConstantScope))
8738                                 return false;
8739
8740                         if (ignoreAnonymous || ec.CurrentAnonymousMethod == null)
8741                                 return true;
8742
8743                         if (ec.CurrentType.IsStruct && !(ec.CurrentAnonymousMethod is StateMachineInitializer))
8744                                 return false;
8745
8746                         return true;
8747                 }
8748
8749                 public virtual void ResolveBase (ResolveContext ec)
8750                 {
8751                         eclass = ExprClass.Variable;
8752                         type = ec.CurrentType;
8753
8754                         if (!IsThisAvailable (ec, false)) {
8755                                 Error_ThisNotAvailable (ec);
8756                                 return;
8757                         }
8758
8759                         var block = ec.CurrentBlock;
8760                         if (block != null) {
8761                                 var top = block.ParametersBlock.TopBlock;
8762                                 if (top.ThisVariable != null)
8763                                         variable_info = top.ThisVariable.VariableInfo;
8764
8765                                 AnonymousExpression am = ec.CurrentAnonymousMethod;
8766                                 if (am != null && ec.IsVariableCapturingRequired && !block.Explicit.HasCapturedThis) {
8767                                         //
8768                                         // Hoisted this is almost like hoisted variable but not exactly. When
8769                                         // there is no variable hoisted we can simply emit an instance method
8770                                         // without lifting this into a storey. Unfotunatelly this complicates
8771                                         // things in other cases because we don't know where this will be hoisted
8772                                         // until top-level block is fully resolved
8773                                         //
8774                                         top.AddThisReferenceFromChildrenBlock (block.Explicit);
8775                                         am.SetHasThisAccess ();
8776                                 }
8777                         }
8778                 }
8779
8780                 protected override Expression DoResolve (ResolveContext ec)
8781                 {
8782                         ResolveBase (ec);
8783                         return this;
8784                 }
8785
8786                 public override Expression DoResolveLValue (ResolveContext ec, Expression right_side)
8787                 {
8788                         if (eclass == ExprClass.Unresolved)
8789                                 ResolveBase (ec);
8790
8791                         if (type.IsClass){
8792                                 if (right_side == EmptyExpression.UnaryAddress)
8793                                         ec.Report.Error (459, loc, "Cannot take the address of `this' because it is read-only");
8794                                 else if (right_side == EmptyExpression.OutAccess)
8795                                         ec.Report.Error (1605, loc, "Cannot pass `this' as a ref or out argument because it is read-only");
8796                                 else
8797                                         ec.Report.Error (1604, loc, "Cannot assign to `this' because it is read-only");
8798                         }
8799
8800                         return this;
8801                 }
8802
8803                 public override int GetHashCode()
8804                 {
8805                         throw new NotImplementedException ();
8806                 }
8807
8808                 public override bool Equals (object obj)
8809                 {
8810                         This t = obj as This;
8811                         if (t == null)
8812                                 return false;
8813
8814                         return true;
8815                 }
8816
8817                 protected override void CloneTo (CloneContext clonectx, Expression t)
8818                 {
8819                         // Nothing
8820                 }
8821
8822                 public override void SetHasAddressTaken ()
8823                 {
8824                         // Nothing
8825                 }
8826                 
8827                 public override object Accept (StructuralVisitor visitor)
8828                 {
8829                         return visitor.Visit (this);
8830                 }
8831         }
8832
8833         /// <summary>
8834         ///   Represents the `__arglist' construct
8835         /// </summary>
8836         public class ArglistAccess : Expression
8837         {
8838                 public ArglistAccess (Location loc)
8839                 {
8840                         this.loc = loc;
8841                 }
8842
8843                 protected override void CloneTo (CloneContext clonectx, Expression target)
8844                 {
8845                         // nothing.
8846                 }
8847
8848                 public override bool ContainsEmitWithAwait ()
8849                 {
8850                         return false;
8851                 }
8852
8853                 public override Expression CreateExpressionTree (ResolveContext ec)
8854                 {
8855                         throw new NotSupportedException ("ET");
8856                 }
8857
8858                 protected override Expression DoResolve (ResolveContext ec)
8859                 {
8860                         eclass = ExprClass.Variable;
8861                         type = ec.Module.PredefinedTypes.RuntimeArgumentHandle.Resolve ();
8862
8863                         if (ec.HasSet (ResolveContext.Options.FieldInitializerScope) || !ec.CurrentBlock.ParametersBlock.Parameters.HasArglist) {
8864                                 ec.Report.Error (190, loc,
8865                                         "The __arglist construct is valid only within a variable argument method");
8866                         }
8867
8868                         return this;
8869                 }
8870
8871                 public override void Emit (EmitContext ec)
8872                 {
8873                         ec.Emit (OpCodes.Arglist);
8874                 }
8875
8876                 public override object Accept (StructuralVisitor visitor)
8877                 {
8878                         return visitor.Visit (this);
8879                 }
8880         }
8881
8882         /// <summary>
8883         ///   Represents the `__arglist (....)' construct
8884         /// </summary>
8885         public class Arglist : Expression
8886         {
8887                 Arguments arguments;
8888
8889                 public Arglist (Location loc)
8890                         : this (null, loc)
8891                 {
8892                 }
8893
8894                 public Arglist (Arguments args, Location l)
8895                 {
8896                         arguments = args;
8897                         loc = l;
8898                 }
8899
8900                 public Arguments Arguments {
8901                         get {
8902                                 return arguments;
8903                         }
8904                 }
8905
8906                 public MetaType[] ArgumentTypes {
8907                     get {
8908                                 if (arguments == null)
8909                                         return MetaType.EmptyTypes;
8910
8911                                 var retval = new MetaType[arguments.Count];
8912                                 for (int i = 0; i < retval.Length; i++)
8913                                         retval[i] = arguments[i].Expr.Type.GetMetaInfo ();
8914
8915                         return retval;
8916                     }
8917                 }
8918
8919                 public override bool ContainsEmitWithAwait ()
8920                 {
8921                         throw new NotImplementedException ();
8922                 }
8923                 
8924                 public override Expression CreateExpressionTree (ResolveContext ec)
8925                 {
8926                         ec.Report.Error (1952, loc, "An expression tree cannot contain a method with variable arguments");
8927                         return null;
8928                 }
8929
8930                 protected override Expression DoResolve (ResolveContext ec)
8931                 {
8932                         eclass = ExprClass.Variable;
8933                         type = InternalType.Arglist;
8934                         if (arguments != null) {
8935                                 bool dynamic;   // Can be ignored as there is always only 1 overload
8936                                 arguments.Resolve (ec, out dynamic);
8937                         }
8938
8939                         return this;
8940                 }
8941
8942                 public override void Emit (EmitContext ec)
8943                 {
8944                         if (arguments != null)
8945                                 arguments.Emit (ec);
8946                 }
8947
8948                 protected override void CloneTo (CloneContext clonectx, Expression t)
8949                 {
8950                         Arglist target = (Arglist) t;
8951
8952                         if (arguments != null)
8953                                 target.arguments = arguments.Clone (clonectx);
8954                 }
8955
8956                 public override object Accept (StructuralVisitor visitor)
8957                 {
8958                         return visitor.Visit (this);
8959                 }
8960         }
8961
8962         public class RefValueExpr : ShimExpression, IAssignMethod, IMemoryLocation
8963         {
8964                 FullNamedExpression texpr;
8965
8966                 public RefValueExpr (Expression expr, FullNamedExpression texpr, Location loc)
8967                         : base (expr)
8968                 {
8969                         this.texpr = texpr;
8970                         this.loc = loc;
8971                 }
8972
8973                 public FullNamedExpression TypeExpression {
8974                         get {
8975                                 return texpr;
8976                         }
8977                 }
8978
8979                 public override bool ContainsEmitWithAwait ()
8980                 {
8981                         return false;
8982                 }
8983
8984                 public void AddressOf (EmitContext ec, AddressOp mode)
8985                 {
8986                         expr.Emit (ec);
8987                         ec.Emit (OpCodes.Refanyval, type);
8988                 }
8989
8990                 protected override Expression DoResolve (ResolveContext rc)
8991                 {
8992                         expr = expr.Resolve (rc);
8993                         type = texpr.ResolveAsType (rc);
8994                         if (expr == null || type == null)
8995                                 return null;
8996
8997                         expr = Convert.ImplicitConversionRequired (rc, expr, rc.Module.PredefinedTypes.TypedReference.Resolve (), loc);
8998                         eclass = ExprClass.Variable;
8999                         return this;
9000                 }
9001
9002                 public override Expression DoResolveLValue (ResolveContext rc, Expression right_side)
9003                 {
9004                         return DoResolve (rc);
9005                 }
9006
9007                 public override void Emit (EmitContext ec)
9008                 {
9009                         expr.Emit (ec);
9010                         ec.Emit (OpCodes.Refanyval, type);
9011                         ec.EmitLoadFromPtr (type);
9012                 }
9013
9014                 public void Emit (EmitContext ec, bool leave_copy)
9015                 {
9016                         throw new NotImplementedException ();
9017                 }
9018
9019                 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool isCompound)
9020                 {
9021                         expr.Emit (ec);
9022                         ec.Emit (OpCodes.Refanyval, type);
9023                         source.Emit (ec);
9024
9025                         LocalTemporary temporary = null;
9026                         if (leave_copy) {
9027                                 ec.Emit (OpCodes.Dup);
9028                                 temporary = new LocalTemporary (source.Type);
9029                                 temporary.Store (ec);
9030                         }
9031
9032                         ec.EmitStoreFromPtr (type);
9033
9034                         if (temporary != null) {
9035                                 temporary.Emit (ec);
9036                                 temporary.Release (ec);
9037                         }
9038                 }
9039
9040                 public override object Accept (StructuralVisitor visitor)
9041                 {
9042                         return visitor.Visit (this);
9043                 }
9044         }
9045
9046         public class RefTypeExpr : ShimExpression
9047         {
9048                 public RefTypeExpr (Expression expr, Location loc)
9049                         : base (expr)
9050                 {
9051                         this.loc = loc;
9052                 }
9053
9054                 protected override Expression DoResolve (ResolveContext rc)
9055                 {
9056                         expr = expr.Resolve (rc);
9057                         if (expr == null)
9058                                 return null;
9059
9060                         expr = Convert.ImplicitConversionRequired (rc, expr, rc.Module.PredefinedTypes.TypedReference.Resolve (), loc);
9061                         if (expr == null)
9062                                 return null;
9063
9064                         type = rc.BuiltinTypes.Type;
9065                         eclass = ExprClass.Value;
9066                         return this;
9067                 }
9068
9069                 public override void Emit (EmitContext ec)
9070                 {
9071                         expr.Emit (ec);
9072                         ec.Emit (OpCodes.Refanytype);
9073                         var m = ec.Module.PredefinedMembers.TypeGetTypeFromHandle.Resolve (loc);
9074                         if (m != null)
9075                                 ec.Emit (OpCodes.Call, m);
9076                 }
9077                 
9078                 public override object Accept (StructuralVisitor visitor)
9079                 {
9080                         return visitor.Visit (this);
9081                 }
9082         }
9083
9084         public class MakeRefExpr : ShimExpression
9085         {
9086                 public MakeRefExpr (Expression expr, Location loc)
9087                         : base (expr)
9088                 {
9089                         this.loc = loc;
9090                 }
9091
9092                 public override bool ContainsEmitWithAwait ()
9093                 {
9094                         throw new NotImplementedException ();
9095                 }
9096
9097                 protected override Expression DoResolve (ResolveContext rc)
9098                 {
9099                         expr = expr.ResolveLValue (rc, EmptyExpression.LValueMemberAccess);
9100                         type = rc.Module.PredefinedTypes.TypedReference.Resolve ();
9101                         eclass = ExprClass.Value;
9102                         return this;
9103                 }
9104
9105                 public override void Emit (EmitContext ec)
9106                 {
9107                         ((IMemoryLocation) expr).AddressOf (ec, AddressOp.Load);
9108                         ec.Emit (OpCodes.Mkrefany, expr.Type);
9109                 }
9110                 
9111                 public override object Accept (StructuralVisitor visitor)
9112                 {
9113                         return visitor.Visit (this);
9114                 }
9115         }
9116
9117         /// <summary>
9118         ///   Implements the typeof operator
9119         /// </summary>
9120         public class TypeOf : Expression {
9121                 FullNamedExpression QueriedType;
9122                 TypeSpec typearg;
9123
9124                 public TypeOf (FullNamedExpression queried_type, Location l)
9125                 {
9126                         QueriedType = queried_type;
9127                         loc = l;
9128                 }
9129
9130                 //
9131                 // Use this constructor for any compiler generated typeof expression
9132                 //
9133                 public TypeOf (TypeSpec type, Location loc)
9134                 {
9135                         this.typearg = type;
9136                         this.loc = loc;
9137                 }
9138
9139                 #region Properties
9140
9141                 public override bool IsSideEffectFree {
9142                         get {
9143                                 return true;
9144                         }
9145                 }
9146
9147                 public TypeSpec TypeArgument {
9148                         get {
9149                                 return typearg;
9150                         }
9151                 }
9152
9153                 public FullNamedExpression TypeExpression {
9154                         get {
9155                                 return QueriedType;
9156                         }
9157                 }
9158
9159                 #endregion
9160
9161
9162                 protected override void CloneTo (CloneContext clonectx, Expression t)
9163                 {
9164                         TypeOf target = (TypeOf) t;
9165                         if (QueriedType != null)
9166                                 target.QueriedType = (FullNamedExpression) QueriedType.Clone (clonectx);
9167                 }
9168
9169                 public override bool ContainsEmitWithAwait ()
9170                 {
9171                         return false;
9172                 }
9173
9174                 public override Expression CreateExpressionTree (ResolveContext ec)
9175                 {
9176                         Arguments args = new Arguments (2);
9177                         args.Add (new Argument (this));
9178                         args.Add (new Argument (new TypeOf (new TypeExpression (type, loc), loc)));
9179                         return CreateExpressionFactoryCall (ec, "Constant", args);
9180                 }
9181
9182                 protected override Expression DoResolve (ResolveContext ec)
9183                 {
9184                         if (eclass != ExprClass.Unresolved)
9185                                 return this;
9186
9187                         if (typearg == null) {
9188                                 //
9189                                 // Pointer types are allowed without explicit unsafe, they are just tokens
9190                                 //
9191                                 using (ec.Set (ResolveContext.Options.UnsafeScope)) {
9192                                         typearg = QueriedType.ResolveAsType (ec, true);
9193                                 }
9194
9195                                 if (typearg == null)
9196                                         return null;
9197
9198                                 if (typearg.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
9199                                         ec.Report.Error (1962, QueriedType.Location,
9200                                                 "The typeof operator cannot be used on the dynamic type");
9201                                 }
9202                         }
9203
9204                         type = ec.BuiltinTypes.Type;
9205
9206                         // Even though what is returned is a type object, it's treated as a value by the compiler.
9207                         // In particular, 'typeof (Foo).X' is something totally different from 'Foo.X'.
9208                         eclass = ExprClass.Value;
9209                         return this;
9210                 }
9211
9212                 static bool ContainsDynamicType (TypeSpec type)
9213                 {
9214                         if (type.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
9215                                 return true;
9216
9217                         var element_container = type as ElementTypeSpec;
9218                         if (element_container != null)
9219                                 return ContainsDynamicType (element_container.Element);
9220
9221                         foreach (var t in type.TypeArguments) {
9222                                 if (ContainsDynamicType (t)) {
9223                                         return true;
9224                                 }
9225                         }
9226
9227                         return false;
9228                 }
9229
9230                 public override void EncodeAttributeValue (IMemberContext rc, AttributeEncoder enc, TypeSpec targetType, TypeSpec parameterType)
9231                 {
9232                         // Target type is not System.Type therefore must be object
9233                         // and we need to use different encoding sequence
9234                         if (targetType != type)
9235                                 enc.Encode (type);
9236
9237                         if (typearg is InflatedTypeSpec) {
9238                                 var gt = typearg;
9239                                 do {
9240                                         if (InflatedTypeSpec.ContainsTypeParameter (gt)) {
9241                                                 rc.Module.Compiler.Report.Error (416, loc, "`{0}': an attribute argument cannot use type parameters",
9242                                                         typearg.GetSignatureForError ());
9243                                                 return;
9244                                         }
9245
9246                                         gt = gt.DeclaringType;
9247                                 } while (gt != null);
9248                         }
9249
9250                         if (ContainsDynamicType (typearg)) {
9251                                 Attribute.Error_AttributeArgumentIsDynamic (rc, loc);
9252                                 return;
9253                         }
9254
9255                         enc.EncodeTypeName (typearg);
9256                 }
9257
9258                 public override void Emit (EmitContext ec)
9259                 {
9260                         ec.Emit (OpCodes.Ldtoken, typearg);
9261                         var m = ec.Module.PredefinedMembers.TypeGetTypeFromHandle.Resolve (loc);
9262                         if (m != null)
9263                                 ec.Emit (OpCodes.Call, m);
9264                 }
9265                 
9266                 public override object Accept (StructuralVisitor visitor)
9267                 {
9268                         return visitor.Visit (this);
9269                 }
9270         }
9271
9272         sealed class TypeOfMethod : TypeOfMember<MethodSpec>
9273         {
9274                 public TypeOfMethod (MethodSpec method, Location loc)
9275                         : base (method, loc)
9276                 {
9277                 }
9278
9279                 protected override Expression DoResolve (ResolveContext ec)
9280                 {
9281                         if (member.IsConstructor) {
9282                                 type = ec.Module.PredefinedTypes.ConstructorInfo.Resolve ();
9283                         } else {
9284                                 type = ec.Module.PredefinedTypes.MethodInfo.Resolve ();
9285                         }
9286
9287                         if (type == null)
9288                                 return null;
9289
9290                         return base.DoResolve (ec);
9291                 }
9292
9293                 public override void Emit (EmitContext ec)
9294                 {
9295                         ec.Emit (OpCodes.Ldtoken, member);
9296
9297                         base.Emit (ec);
9298                         ec.Emit (OpCodes.Castclass, type);
9299                 }
9300
9301                 protected override PredefinedMember<MethodSpec> GetTypeFromHandle (EmitContext ec)
9302                 {
9303                         return ec.Module.PredefinedMembers.MethodInfoGetMethodFromHandle;
9304                 }
9305
9306                 protected override PredefinedMember<MethodSpec> GetTypeFromHandleGeneric (EmitContext ec)
9307                 {
9308                         return ec.Module.PredefinedMembers.MethodInfoGetMethodFromHandle2;
9309                 }
9310         }
9311
9312         abstract class TypeOfMember<T> : Expression where T : MemberSpec
9313         {
9314                 protected readonly T member;
9315
9316                 protected TypeOfMember (T member, Location loc)
9317                 {
9318                         this.member = member;
9319                         this.loc = loc;
9320                 }
9321
9322                 public override bool IsSideEffectFree {
9323                         get {
9324                                 return true;
9325                         }
9326                 }
9327
9328                 public override bool ContainsEmitWithAwait ()
9329                 {
9330                         return false;
9331                 }
9332
9333                 public override Expression CreateExpressionTree (ResolveContext ec)
9334                 {
9335                         Arguments args = new Arguments (2);
9336                         args.Add (new Argument (this));
9337                         args.Add (new Argument (new TypeOf (type, loc)));
9338                         return CreateExpressionFactoryCall (ec, "Constant", args);
9339                 }
9340
9341                 protected override Expression DoResolve (ResolveContext ec)
9342                 {
9343                         eclass = ExprClass.Value;
9344                         return this;
9345                 }
9346
9347                 public override void Emit (EmitContext ec)
9348                 {
9349                         bool is_generic = member.DeclaringType.IsGenericOrParentIsGeneric;
9350                         PredefinedMember<MethodSpec> p;
9351                         if (is_generic) {
9352                                 p = GetTypeFromHandleGeneric (ec);
9353                                 ec.Emit (OpCodes.Ldtoken, member.DeclaringType);
9354                         } else {
9355                                 p = GetTypeFromHandle (ec);
9356                         }
9357
9358                         var mi = p.Resolve (loc);
9359                         if (mi != null)
9360                                 ec.Emit (OpCodes.Call, mi);
9361                 }
9362
9363                 protected abstract PredefinedMember<MethodSpec> GetTypeFromHandle (EmitContext ec);
9364                 protected abstract PredefinedMember<MethodSpec> GetTypeFromHandleGeneric (EmitContext ec);
9365         }
9366
9367         sealed class TypeOfField : TypeOfMember<FieldSpec>
9368         {
9369                 public TypeOfField (FieldSpec field, Location loc)
9370                         : base (field, loc)
9371                 {
9372                 }
9373
9374                 protected override Expression DoResolve (ResolveContext ec)
9375                 {
9376                         type = ec.Module.PredefinedTypes.FieldInfo.Resolve ();
9377                         if (type == null)
9378                                 return null;
9379
9380                         return base.DoResolve (ec);
9381                 }
9382
9383                 public override void Emit (EmitContext ec)
9384                 {
9385                         ec.Emit (OpCodes.Ldtoken, member);
9386                         base.Emit (ec);
9387                 }
9388
9389                 protected override PredefinedMember<MethodSpec> GetTypeFromHandle (EmitContext ec)
9390                 {
9391                         return ec.Module.PredefinedMembers.FieldInfoGetFieldFromHandle;
9392                 }
9393
9394                 protected override PredefinedMember<MethodSpec> GetTypeFromHandleGeneric (EmitContext ec)
9395                 {
9396                         return ec.Module.PredefinedMembers.FieldInfoGetFieldFromHandle2;
9397                 }
9398         }
9399
9400         /// <summary>
9401         ///   Implements the sizeof expression
9402         /// </summary>
9403         public class SizeOf : Expression {
9404                 readonly Expression texpr;
9405                 TypeSpec type_queried;
9406                 
9407                 public SizeOf (Expression queried_type, Location l)
9408                 {
9409                         this.texpr = queried_type;
9410                         loc = l;
9411                 }
9412
9413                 public override bool IsSideEffectFree {
9414                         get {
9415                                 return true;
9416                         }
9417                 }
9418
9419                 public Expression TypeExpression {
9420                         get {
9421                                 return texpr;
9422                         }
9423                 }
9424
9425                 public override bool ContainsEmitWithAwait ()
9426                 {
9427                         return false;
9428                 }
9429
9430                 public override Expression CreateExpressionTree (ResolveContext ec)
9431                 {
9432                         Error_PointerInsideExpressionTree (ec);
9433                         return null;
9434                 }
9435
9436                 protected override Expression DoResolve (ResolveContext ec)
9437                 {
9438                         type_queried = texpr.ResolveAsType (ec);
9439                         if (type_queried == null)
9440                                 return null;
9441
9442                         if (type_queried.IsEnum)
9443                                 type_queried = EnumSpec.GetUnderlyingType (type_queried);
9444
9445                         int size_of = BuiltinTypeSpec.GetSize (type_queried);
9446                         if (size_of > 0) {
9447                                 return new IntConstant (ec.BuiltinTypes, size_of, loc);
9448                         }
9449
9450                         if (!TypeManager.VerifyUnmanaged (ec.Module, type_queried, loc)){
9451                                 return null;
9452                         }
9453
9454                         if (!ec.IsUnsafe) {
9455                                 ec.Report.Error (233, loc,
9456                                         "`{0}' does not have a predefined size, therefore sizeof can only be used in an unsafe context (consider using System.Runtime.InteropServices.Marshal.SizeOf)",
9457                                         type_queried.GetSignatureForError ());
9458                         }
9459                         
9460                         type = ec.BuiltinTypes.Int;
9461                         eclass = ExprClass.Value;
9462                         return this;
9463                 }
9464
9465                 public override void Emit (EmitContext ec)
9466                 {
9467                         ec.Emit (OpCodes.Sizeof, type_queried);
9468                 }
9469
9470                 protected override void CloneTo (CloneContext clonectx, Expression t)
9471                 {
9472                 }
9473                 
9474                 public override object Accept (StructuralVisitor visitor)
9475                 {
9476                         return visitor.Visit (this);
9477                 }
9478         }
9479
9480         /// <summary>
9481         ///   Implements the qualified-alias-member (::) expression.
9482         /// </summary>
9483         public class QualifiedAliasMember : MemberAccess
9484         {
9485                 readonly string alias;
9486                 public static readonly string GlobalAlias = "global";
9487
9488                 public QualifiedAliasMember (string alias, string identifier, Location l)
9489                         : base (null, identifier, l)
9490                 {
9491                         this.alias = alias;
9492                 }
9493
9494                 public QualifiedAliasMember (string alias, string identifier, TypeArguments targs, Location l)
9495                         : base (null, identifier, targs, l)
9496                 {
9497                         this.alias = alias;
9498                 }
9499
9500                 public QualifiedAliasMember (string alias, string identifier, int arity, Location l)
9501                         : base (null, identifier, arity, l)
9502                 {
9503                         this.alias = alias;
9504                 }
9505
9506                 public string Alias {
9507                         get {
9508                                 return alias;
9509                         }
9510                 }
9511
9512                 public FullNamedExpression CreateExpressionFromAlias (IMemberContext mc)
9513                 {
9514                         if (alias == GlobalAlias)
9515                                 return new NamespaceExpression (mc.Module.GlobalRootNamespace, loc);
9516
9517                         int errors = mc.Module.Compiler.Report.Errors;
9518                         var expr = mc.LookupNamespaceAlias (alias);
9519                         if (expr == null) {
9520                                 if (errors == mc.Module.Compiler.Report.Errors)
9521                                         mc.Module.Compiler.Report.Error (432, loc, "Alias `{0}' not found", alias);
9522
9523                                 return null;
9524                         }
9525
9526                         return expr;
9527                 }
9528
9529                 public override FullNamedExpression ResolveAsTypeOrNamespace (IMemberContext mc, bool allowUnboundTypeArguments)
9530                 {
9531                         expr = CreateExpressionFromAlias (mc);
9532                         if (expr == null)
9533                                 return null;
9534
9535                         return base.ResolveAsTypeOrNamespace (mc, allowUnboundTypeArguments);
9536                 }
9537
9538                 protected override Expression DoResolve (ResolveContext rc)
9539                 {
9540                         return ResolveAsTypeOrNamespace (rc, false);
9541                 }
9542
9543                 public override string GetSignatureForError ()
9544                 {
9545                         string name = Name;
9546                         if (targs != null) {
9547                                 name = Name + "<" + targs.GetSignatureForError () + ">";
9548                         }
9549
9550                         return alias + "::" + name;
9551                 }
9552
9553                 public override bool HasConditionalAccess ()
9554                 {
9555                         return false;
9556                 }
9557
9558                 public override Expression LookupNameExpression (ResolveContext rc, MemberLookupRestrictions restrictions)
9559                 {
9560                         if ((restrictions & MemberLookupRestrictions.InvocableOnly) != 0) {
9561                                 rc.Module.Compiler.Report.Error (687, loc,
9562                                         "The namespace alias qualifier `::' cannot be used to invoke a method. Consider using `.' instead",
9563                                         GetSignatureForError ());
9564
9565                                 return null;
9566                         }
9567
9568                         return DoResolve (rc);
9569                 }
9570
9571                 protected override void CloneTo (CloneContext clonectx, Expression t)
9572                 {
9573                         // Nothing 
9574                 }
9575                 
9576                 public override object Accept (StructuralVisitor visitor)
9577                 {
9578                         return visitor.Visit (this);
9579                 }
9580         }
9581
9582         /// <summary>
9583         ///   Implements the member access expression
9584         /// </summary>
9585         public class MemberAccess : ATypeNameExpression
9586         {
9587                 protected Expression expr;
9588
9589                 public MemberAccess (Expression expr, string id)
9590                         : base (id, expr.Location)
9591                 {
9592                         this.expr = expr;
9593                 }
9594
9595                 public MemberAccess (Expression expr, string identifier, Location loc)
9596                         : base (identifier, loc)
9597                 {
9598                         this.expr = expr;
9599                 }
9600
9601                 public MemberAccess (Expression expr, string identifier, TypeArguments args, Location loc)
9602                         : base (identifier, args, loc)
9603                 {
9604                         this.expr = expr;
9605                 }
9606
9607                 public MemberAccess (Expression expr, string identifier, int arity, Location loc)
9608                         : base (identifier, arity, loc)
9609                 {
9610                         this.expr = expr;
9611                 }
9612
9613                 public Expression LeftExpression {
9614                         get {
9615                                 return expr;
9616                         }
9617                 }
9618
9619                 public override Location StartLocation {
9620                         get {
9621                                 return expr == null ? loc : expr.StartLocation;
9622                         }
9623                 }
9624
9625                 protected override Expression DoResolve (ResolveContext rc)
9626                 {
9627                         var e = LookupNameExpression (rc, MemberLookupRestrictions.ReadAccess | MemberLookupRestrictions.DontSetConditionalAccess);
9628                         if (e != null)
9629                                 e = e.Resolve (rc, ResolveFlags.VariableOrValue | ResolveFlags.Type | ResolveFlags.MethodGroup);
9630
9631                         return e;
9632                 }
9633
9634                 public override Expression DoResolveLValue (ResolveContext rc, Expression rhs)
9635                 {
9636                         var e = LookupNameExpression (rc, MemberLookupRestrictions.None);
9637
9638                         if (e is TypeExpr) {
9639                                 e.Error_UnexpectedKind (rc, ResolveFlags.VariableOrValue, loc);
9640                                 return null;
9641                         }
9642
9643                         if (e != null)
9644                                 e = e.ResolveLValue (rc, rhs);
9645
9646                         return e;
9647                 }
9648
9649                 protected virtual void Error_OperatorCannotBeApplied (ResolveContext rc, TypeSpec type)
9650                 {
9651                         if (type == InternalType.NullLiteral && rc.IsRuntimeBinder)
9652                                 rc.Report.Error (Report.RuntimeErrorId, loc, "Cannot perform member binding on `null' value");
9653                         else
9654                                 expr.Error_OperatorCannotBeApplied (rc, loc, ".", type);
9655                 }
9656
9657                 public override bool HasConditionalAccess ()
9658                 {
9659                         return LeftExpression.HasConditionalAccess ();
9660                 }
9661
9662                 public static bool IsValidDotExpression (TypeSpec type)
9663                 {
9664                         const MemberKind dot_kinds = MemberKind.Class | MemberKind.Struct | MemberKind.Delegate | MemberKind.Enum |
9665                                 MemberKind.Interface | MemberKind.TypeParameter | MemberKind.ArrayType;
9666
9667                         return (type.Kind & dot_kinds) != 0 || type.BuiltinType == BuiltinTypeSpec.Type.Dynamic;
9668                 }
9669
9670                 public override Expression LookupNameExpression (ResolveContext rc, MemberLookupRestrictions restrictions)
9671                 {
9672                         var sn = expr as SimpleName;
9673                         const ResolveFlags flags = ResolveFlags.VariableOrValue | ResolveFlags.Type;
9674
9675                         if (sn != null) {
9676                                 expr = sn.LookupNameExpression (rc, MemberLookupRestrictions.ReadAccess | MemberLookupRestrictions.ExactArity);
9677
9678                                 //
9679                                 // Resolve expression which does have type set as we need expression type
9680                                 // with disable flow analysis as we don't know whether left side expression
9681                                 // is used as variable or type
9682                                 //
9683                                 if (expr is VariableReference || expr is ConstantExpr || expr is Linq.TransparentMemberAccess || expr is EventExpr) {
9684                                         expr = expr.Resolve (rc);
9685                                 } else if (expr is TypeParameterExpr) {
9686                                         expr.Error_UnexpectedKind (rc, flags, sn.Location);
9687                                         expr = null;
9688                                 }
9689                         } else {
9690                                 if ((restrictions & MemberLookupRestrictions.DontSetConditionalAccess) != 0) {
9691                                         using (rc.Set (ResolveContext.Options.DontSetConditionalAccessReceiver)) {
9692                                                 expr = expr.Resolve (rc, flags);
9693                                         }
9694                                 } else {
9695                                         expr = expr.Resolve (rc, flags);
9696                                 }
9697                         }
9698
9699                         if (expr == null)
9700                                 return null;
9701
9702                         var ns = expr as NamespaceExpression;
9703                         if (ns != null) {
9704                                 var retval = ns.LookupTypeOrNamespace (rc, Name, Arity, LookupMode.Normal, loc);
9705
9706                                 if (retval == null) {
9707                                         ns.Error_NamespaceDoesNotExist (rc, Name, Arity, loc);
9708                                         return null;
9709                                 }
9710
9711                                 if (Arity > 0) {
9712                                         if (HasTypeArguments)
9713                                                 return new GenericTypeExpr (retval.Type, targs, loc);
9714
9715                                         targs.Resolve (rc, false);
9716                                 }
9717
9718                                 return retval;
9719                         }
9720
9721                         MemberExpr me;
9722                         TypeSpec expr_type = expr.Type;
9723                         if (expr_type.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
9724                                 me = expr as MemberExpr;
9725                                 if (me != null)
9726                                         me.ResolveInstanceExpression (rc, null);
9727
9728                                 Arguments args = new Arguments (1);
9729                                 args.Add (new Argument (expr));
9730                                 return new DynamicMemberBinder (Name, args, loc);
9731                         }
9732
9733                         var cma = this as ConditionalMemberAccess;
9734                         if (cma != null) {
9735                                 if (!IsNullPropagatingValid (expr.Type)) {
9736                                         expr.Error_OperatorCannotBeApplied (rc, loc, "?", expr.Type);
9737                                         return null;
9738                                 }
9739
9740                                 if (expr_type.IsNullableType) {
9741                                         expr = Nullable.Unwrap.Create (expr.Resolve (rc), true);
9742                                         expr_type = expr.Type;
9743                                 }
9744                         }
9745
9746                         if (!IsValidDotExpression (expr_type)) {
9747                                 Error_OperatorCannotBeApplied (rc, expr_type);
9748                                 return null;
9749                         }
9750
9751                         var lookup_arity = Arity;
9752                         bool errorMode = false;
9753                         Expression member_lookup;
9754                         while (true) {
9755                                 member_lookup = MemberLookup (rc, errorMode, expr_type, Name, lookup_arity, restrictions, loc);
9756                                 if (member_lookup == null) {
9757                                         //
9758                                         // Try to look for extension method when member lookup failed
9759                                         //
9760                                         if (MethodGroupExpr.IsExtensionMethodArgument (expr)) {
9761                                                 var methods = rc.LookupExtensionMethod (Name, lookup_arity);
9762                                                 if (methods != null) {
9763                                                         var emg = new ExtensionMethodGroupExpr (methods, expr, loc);
9764                                                         if (HasTypeArguments) {
9765                                                                 if (!targs.Resolve (rc, false))
9766                                                                         return null;
9767
9768                                                                 emg.SetTypeArguments (rc, targs);
9769                                                         }
9770
9771                                                         if (cma != null)
9772                                                                 emg.ConditionalAccess = true;
9773
9774                                                         // TODO: it should really skip the checks bellow
9775                                                         return emg.Resolve (rc);
9776                                                 }
9777                                         }
9778                                 }
9779
9780                                 if (errorMode) {
9781                                         if (member_lookup == null) {
9782                                                 var dep = expr_type.GetMissingDependencies ();
9783                                                 if (dep != null) {
9784                                                         ImportedTypeDefinition.Error_MissingDependency (rc, dep, loc);
9785                                                 } else if (expr is TypeExpr) {
9786                                                         base.Error_TypeDoesNotContainDefinition (rc, expr_type, Name);
9787                                                 } else {
9788                                                         Error_TypeDoesNotContainDefinition (rc, expr_type, Name);
9789                                                 }
9790
9791                                                 return null;
9792                                         }
9793
9794                                         if (member_lookup is MethodGroupExpr || member_lookup is PropertyExpr) {
9795                                                 // Leave it to overload resolution to report correct error
9796                                         } else if (!(member_lookup is TypeExpr)) {
9797                                                 // TODO: rc.SymbolRelatedToPreviousError
9798                                                 ErrorIsInaccesible (rc, member_lookup.GetSignatureForError (), loc);
9799                                         }
9800                                         break;
9801                                 }
9802
9803                                 if (member_lookup != null)
9804                                         break;
9805
9806                                 lookup_arity = 0;
9807                                 restrictions &= ~MemberLookupRestrictions.InvocableOnly;
9808                                 errorMode = true;
9809                         }
9810
9811                         TypeExpr texpr = member_lookup as TypeExpr;
9812                         if (texpr != null) {
9813                                 if (!(expr is TypeExpr) && (sn == null || expr.ProbeIdenticalTypeName (rc, expr, sn) == expr)) {
9814                                         rc.Report.Error (572, loc, "`{0}': cannot reference a type through an expression. Consider using `{1}' instead",
9815                                                 Name, texpr.GetSignatureForError ());
9816                                 }
9817
9818                                 if (!texpr.Type.IsAccessible (rc)) {
9819                                         rc.Report.SymbolRelatedToPreviousError (member_lookup.Type);
9820                                         ErrorIsInaccesible (rc, member_lookup.Type.GetSignatureForError (), loc);
9821                                         return null;
9822                                 }
9823
9824                                 if (HasTypeArguments) {
9825                                         return new GenericTypeExpr (member_lookup.Type, targs, loc);
9826                                 }
9827
9828                                 return member_lookup;
9829                         }
9830
9831                         me = member_lookup as MemberExpr;
9832
9833                         if (sn != null && me.IsStatic && (expr = me.ProbeIdenticalTypeName (rc, expr, sn)) != expr) {
9834                                 sn = null;
9835                         }
9836
9837                         if (cma != null) {
9838                                 me.ConditionalAccess = true;
9839                         }
9840
9841                         me = me.ResolveMemberAccess (rc, expr, sn);
9842
9843                         if (Arity > 0) {
9844                                 if (!targs.Resolve (rc, false))
9845                                         return null;
9846
9847                                 me.SetTypeArguments (rc, targs);
9848                         }
9849
9850                         return me;
9851                 }
9852
9853                 public override FullNamedExpression ResolveAsTypeOrNamespace (IMemberContext rc, bool allowUnboundTypeArguments)
9854                 {
9855                         FullNamedExpression fexpr = expr as FullNamedExpression;
9856                         if (fexpr == null) {
9857                                 expr.ResolveAsType (rc);
9858                                 return null;
9859                         }
9860
9861                         FullNamedExpression expr_resolved = fexpr.ResolveAsTypeOrNamespace (rc, allowUnboundTypeArguments);
9862
9863                         if (expr_resolved == null)
9864                                 return null;
9865
9866                         var ns = expr_resolved as NamespaceExpression;
9867                         if (ns != null) {
9868                                 FullNamedExpression retval = ns.LookupTypeOrNamespace (rc, Name, Arity, LookupMode.Normal, loc);
9869
9870                                 if (retval == null) {
9871                                         ns.Error_NamespaceDoesNotExist (rc, Name, Arity, loc);
9872                                 } else if (Arity > 0) {
9873                                         if (HasTypeArguments) {
9874                                                 retval = new GenericTypeExpr (retval.Type, targs, loc);
9875                                                 if (retval.ResolveAsType (rc) == null)
9876                                                         return null;
9877                                         } else {
9878                                                 targs.Resolve (rc, allowUnboundTypeArguments);
9879
9880                                                 retval = new GenericOpenTypeExpr (retval.Type, loc);
9881                                         }
9882                                 }
9883
9884                                 return retval;
9885                         }
9886
9887                         var tnew_expr = expr_resolved.ResolveAsType (rc);
9888                         if (tnew_expr == null)
9889                                 return null;
9890
9891                         TypeSpec expr_type = tnew_expr;
9892                         if (TypeManager.IsGenericParameter (expr_type)) {
9893                                 rc.Module.Compiler.Report.Error (704, loc, "A nested type cannot be specified through a type parameter `{0}'",
9894                                         tnew_expr.GetSignatureForError ());
9895                                 return null;
9896                         }
9897
9898                         var qam = this as QualifiedAliasMember;
9899                         if (qam != null) {
9900                                 rc.Module.Compiler.Report.Error (431, loc,
9901                                         "Alias `{0}' cannot be used with `::' since it denotes a type. Consider replacing `::' with `.'",
9902                                         qam.Alias);
9903
9904                         }
9905
9906                         TypeSpec nested = null;
9907                         while (expr_type != null) {
9908                                 nested = MemberCache.FindNestedType (expr_type, Name, Arity);
9909                                 if (nested == null) {
9910                                         if (expr_type == tnew_expr) {
9911                                                 Error_IdentifierNotFound (rc, expr_type);
9912                                                 return null;
9913                                         }
9914
9915                                         expr_type = tnew_expr;
9916                                         nested = MemberCache.FindNestedType (expr_type, Name, Arity);
9917                                         ErrorIsInaccesible (rc, nested.GetSignatureForError (), loc);
9918                                         break;
9919                                 }
9920
9921                                 if (nested.IsAccessible (rc))
9922                                         break;
9923
9924                                 //
9925                                 // Keep looking after inaccessible candidate but only if
9926                                 // we are not in same context as the definition itself
9927                                 //
9928                                 if (expr_type.MemberDefinition == rc.CurrentMemberDefinition)
9929                                         break;
9930
9931                                 expr_type = expr_type.BaseType;
9932                         }
9933                         
9934                         TypeExpr texpr;
9935                         if (Arity > 0) {
9936                                 if (HasTypeArguments) {
9937                                         texpr = new GenericTypeExpr (nested, targs, loc);
9938                                 } else {
9939                                         targs.Resolve (rc, allowUnboundTypeArguments && !(expr_resolved is GenericTypeExpr));
9940
9941                                         texpr = new GenericOpenTypeExpr (nested, loc);
9942                                 }
9943                         } else if (expr_resolved is GenericOpenTypeExpr) {
9944                                 texpr = new GenericOpenTypeExpr (nested, loc);
9945                         } else {
9946                                 texpr = new TypeExpression (nested, loc);
9947                         }
9948
9949                         if (texpr.ResolveAsType (rc) == null)
9950                                 return null;
9951
9952                         return texpr;
9953                 }
9954
9955                 public void Error_IdentifierNotFound (IMemberContext rc, TypeSpec expr_type)
9956                 {
9957                         var nested = MemberCache.FindNestedType (expr_type, Name, -System.Math.Max (1, Arity));
9958
9959                         if (nested != null) {
9960                                 Error_TypeArgumentsCannotBeUsed (rc, nested, expr.Location);
9961                                 return;
9962                         }
9963
9964                         var any_other_member = MemberLookup (rc, false, expr_type, Name, 0, MemberLookupRestrictions.None, loc);
9965                         if (any_other_member != null) {
9966                                 Error_UnexpectedKind (rc, any_other_member, "type", any_other_member.ExprClassName, loc);
9967                                 return;
9968                         }
9969
9970                         rc.Module.Compiler.Report.Error (426, loc, "The nested type `{0}' does not exist in the type `{1}'",
9971                                 Name, expr_type.GetSignatureForError ());
9972                 }
9973
9974                 protected override void Error_InvalidExpressionStatement (Report report, Location loc)
9975                 {
9976                         base.Error_InvalidExpressionStatement (report, LeftExpression.Location);
9977                 }
9978
9979                 public override void Error_TypeDoesNotContainDefinition (ResolveContext ec, TypeSpec type, string name)
9980                 {
9981                         if (ec.Module.Compiler.Settings.Version > LanguageVersion.ISO_2 && !ec.IsRuntimeBinder && MethodGroupExpr.IsExtensionMethodArgument (expr)) {
9982                                 ec.Report.SymbolRelatedToPreviousError (type);
9983
9984                                 var cand = ec.Module.GlobalRootNamespace.FindExtensionMethodNamespaces (ec, name, Arity);
9985                                 string missing;
9986                                 // a using directive or an assembly reference
9987                                 if (cand != null) {
9988                                         missing = "`" + string.Join ("' or `", cand.ToArray ()) + "' using directive";
9989                                 } else {
9990                                         missing = "an assembly reference";
9991                                 }
9992
9993                                 ec.Report.Error (1061, loc,
9994                                         "Type `{0}' does not contain a definition for `{1}' and no extension method `{1}' of type `{0}' could be found. Are you missing {2}?",
9995                                         type.GetSignatureForError (), name, missing);
9996                                 return;
9997                         }
9998
9999                         base.Error_TypeDoesNotContainDefinition (ec, type, name);
10000                 }
10001
10002                 public override string GetSignatureForError ()
10003                 {
10004                         return expr.GetSignatureForError () + "." + base.GetSignatureForError ();
10005                 }
10006
10007                 protected override void CloneTo (CloneContext clonectx, Expression t)
10008                 {
10009                         MemberAccess target = (MemberAccess) t;
10010
10011                         target.expr = expr.Clone (clonectx);
10012                 }
10013                 
10014                 public override object Accept (StructuralVisitor visitor)
10015                 {
10016                         return visitor.Visit (this);
10017                 }
10018         }
10019
10020         public class ConditionalMemberAccess : MemberAccess
10021         {
10022                 public ConditionalMemberAccess (Expression expr, string identifier, TypeArguments args, Location loc)
10023                         : base (expr, identifier, args, loc)
10024                 {
10025                 }
10026
10027                 public override bool HasConditionalAccess ()
10028                 {
10029                         return true;
10030                 }
10031         }
10032
10033         /// <summary>
10034         ///   Implements checked expressions
10035         /// </summary>
10036         public class CheckedExpr : Expression {
10037
10038                 public Expression Expr;
10039
10040                 public CheckedExpr (Expression e, Location l)
10041                 {
10042                         Expr = e;
10043                         loc = l;
10044                 }
10045
10046                 public override bool ContainsEmitWithAwait ()
10047                 {
10048                         return Expr.ContainsEmitWithAwait ();
10049                 }
10050                 
10051                 public override Expression CreateExpressionTree (ResolveContext ec)
10052                 {
10053                         using (ec.With (ResolveContext.Options.AllCheckStateFlags, true))
10054                                 return Expr.CreateExpressionTree (ec);
10055                 }
10056
10057                 protected override Expression DoResolve (ResolveContext ec)
10058                 {
10059                         using (ec.With (ResolveContext.Options.AllCheckStateFlags, true))
10060                                 Expr = Expr.Resolve (ec);
10061                         
10062                         if (Expr == null)
10063                                 return null;
10064
10065                         if (Expr is Constant || Expr is MethodGroupExpr || Expr is AnonymousMethodExpression || Expr is DefaultValueExpression)
10066                                 return Expr;
10067                         
10068                         eclass = Expr.eclass;
10069                         type = Expr.Type;
10070                         return this;
10071                 }
10072
10073                 public override void Emit (EmitContext ec)
10074                 {
10075                         using (ec.With (EmitContext.Options.CheckedScope, true))
10076                                 Expr.Emit (ec);
10077                 }
10078
10079                 public override void EmitBranchable (EmitContext ec, Label target, bool on_true)
10080                 {
10081                         using (ec.With (EmitContext.Options.CheckedScope, true))
10082                                 Expr.EmitBranchable (ec, target, on_true);
10083                 }
10084
10085                 public override void FlowAnalysis (FlowAnalysisContext fc)
10086                 {
10087                         Expr.FlowAnalysis (fc);
10088                 }
10089
10090                 public override SLE.Expression MakeExpression (BuilderContext ctx)
10091                 {
10092                         using (ctx.With (BuilderContext.Options.CheckedScope, true)) {
10093                                 return Expr.MakeExpression (ctx);
10094                         }
10095                 }
10096
10097                 protected override void CloneTo (CloneContext clonectx, Expression t)
10098                 {
10099                         CheckedExpr target = (CheckedExpr) t;
10100
10101                         target.Expr = Expr.Clone (clonectx);
10102                 }
10103
10104                 public override object Accept (StructuralVisitor visitor)
10105                 {
10106                         return visitor.Visit (this);
10107                 }
10108         }
10109
10110         /// <summary>
10111         ///   Implements the unchecked expression
10112         /// </summary>
10113         public class UnCheckedExpr : Expression {
10114
10115                 public Expression Expr;
10116
10117                 public UnCheckedExpr (Expression e, Location l)
10118                 {
10119                         Expr = e;
10120                         loc = l;
10121                 }
10122
10123                 public override bool ContainsEmitWithAwait ()
10124                 {
10125                         return Expr.ContainsEmitWithAwait ();
10126                 }
10127                 
10128                 public override Expression CreateExpressionTree (ResolveContext ec)
10129                 {
10130                         using (ec.With (ResolveContext.Options.AllCheckStateFlags, false))
10131                                 return Expr.CreateExpressionTree (ec);
10132                 }
10133
10134                 protected override Expression DoResolve (ResolveContext ec)
10135                 {
10136                         using (ec.With (ResolveContext.Options.AllCheckStateFlags, false))
10137                                 Expr = Expr.Resolve (ec);
10138
10139                         if (Expr == null)
10140                                 return null;
10141
10142                         if (Expr is Constant || Expr is MethodGroupExpr || Expr is AnonymousMethodExpression || Expr is DefaultValueExpression)
10143                                 return Expr;
10144                         
10145                         eclass = Expr.eclass;
10146                         type = Expr.Type;
10147                         return this;
10148                 }
10149
10150                 public override void Emit (EmitContext ec)
10151                 {
10152                         using (ec.With (EmitContext.Options.CheckedScope, false))
10153                                 Expr.Emit (ec);
10154                 }
10155
10156                 public override void EmitBranchable (EmitContext ec, Label target, bool on_true)
10157                 {
10158                         using (ec.With (EmitContext.Options.CheckedScope, false))
10159                                 Expr.EmitBranchable (ec, target, on_true);
10160                 }
10161
10162                 public override void FlowAnalysis (FlowAnalysisContext fc)
10163                 {
10164                         Expr.FlowAnalysis (fc);
10165                 }
10166
10167                 protected override void CloneTo (CloneContext clonectx, Expression t)
10168                 {
10169                         UnCheckedExpr target = (UnCheckedExpr) t;
10170
10171                         target.Expr = Expr.Clone (clonectx);
10172                 }
10173
10174                 public override object Accept (StructuralVisitor visitor)
10175                 {
10176                         return visitor.Visit (this);
10177                 }
10178         }
10179
10180         /// <summary>
10181         ///   An Element Access expression.
10182         ///
10183         ///   During semantic analysis these are transformed into 
10184         ///   IndexerAccess, ArrayAccess or a PointerArithmetic.
10185         /// </summary>
10186         public class ElementAccess : Expression
10187         {
10188                 public Arguments Arguments;
10189                 public Expression Expr;
10190                 bool conditional_access_receiver;
10191
10192                 public ElementAccess (Expression e, Arguments args, Location loc)
10193                 {
10194                         Expr = e;
10195                         this.loc = loc;
10196                         this.Arguments = args;
10197                 }
10198
10199                 public bool ConditionalAccess { get; set; }
10200
10201                 public override Location StartLocation {
10202                         get {
10203                                 return Expr.StartLocation;
10204                         }
10205                 }
10206
10207                 public override bool ContainsEmitWithAwait ()
10208                 {
10209                         return Expr.ContainsEmitWithAwait () || Arguments.ContainsEmitWithAwait ();
10210                 }
10211
10212                 //
10213                 // We perform some simple tests, and then to "split" the emit and store
10214                 // code we create an instance of a different class, and return that.
10215                 //
10216                 Expression CreateAccessExpression (ResolveContext ec, bool conditionalAccessReceiver)
10217                 {
10218                         if (conditionalAccessReceiver)
10219                                 ec.Set (ResolveContext.Options.DontSetConditionalAccessReceiver);
10220                         
10221                         Expr = Expr.Resolve (ec);
10222
10223                         if (conditionalAccessReceiver)
10224                                 ec.With (ResolveContext.Options.DontSetConditionalAccessReceiver, false);
10225
10226                         if (Expr == null)
10227                                 return null;
10228
10229                         type = Expr.Type;
10230
10231                         if (ConditionalAccess && !IsNullPropagatingValid (type)) {
10232                                 Error_OperatorCannotBeApplied (ec, loc, "?", type);
10233                                 return null;
10234                         }
10235
10236                         if (type.IsArray) {
10237                                 var aa = new ArrayAccess (this, loc) {
10238                                         ConditionalAccess = ConditionalAccess,
10239                                 };
10240
10241                                 if (conditionalAccessReceiver)
10242                                         aa.SetConditionalAccessReceiver ();
10243
10244                                 return aa;
10245                         }
10246
10247                         if (type.IsPointer)
10248                                 return Expr.MakePointerAccess (ec, type, Arguments);
10249
10250                         FieldExpr fe = Expr as FieldExpr;
10251                         if (fe != null) {
10252                                 var ff = fe.Spec as FixedFieldSpec;
10253                                 if (ff != null) {
10254                                         return Expr.MakePointerAccess (ec, ff.ElementType, Arguments);
10255                                 }
10256                         }
10257
10258                         var indexers = MemberCache.FindMembers (type, MemberCache.IndexerNameAlias, false);
10259                         if (indexers != null || type.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
10260                                 var indexer = new IndexerExpr (indexers, type, this) {
10261                                         ConditionalAccess = ConditionalAccess
10262                                 };
10263
10264                                 if (conditionalAccessReceiver)
10265                                         indexer.SetConditionalAccessReceiver ();
10266
10267                                 return indexer;
10268                         }
10269
10270                         Error_CannotApplyIndexing (ec, type, loc);
10271
10272                         return null;
10273                 }
10274
10275                 public override Expression CreateExpressionTree (ResolveContext ec)
10276                 {
10277                         Arguments args = Arguments.CreateForExpressionTree (ec, Arguments,
10278                                 Expr.CreateExpressionTree (ec));
10279
10280                         return CreateExpressionFactoryCall (ec, "ArrayIndex", args);
10281                 }
10282
10283                 public static void Error_CannotApplyIndexing (ResolveContext rc, TypeSpec type, Location loc)
10284                 {
10285                         if (type != InternalType.ErrorType) {
10286                                 rc.Report.Error (21, loc, "Cannot apply indexing with [] to an expression of type `{0}'",
10287                                         type.GetSignatureForError ());
10288                         }
10289                 }
10290
10291                 public override bool HasConditionalAccess ()
10292                 {
10293                         return ConditionalAccess || Expr.HasConditionalAccess ();
10294                 }
10295
10296                 void ResolveConditionalAccessReceiver (ResolveContext rc)
10297                 {
10298                         if (!rc.HasSet (ResolveContext.Options.DontSetConditionalAccessReceiver) && HasConditionalAccess ()) {
10299                                 conditional_access_receiver = true;
10300                         }
10301                 }
10302
10303                 protected override Expression DoResolve (ResolveContext rc)
10304                 {
10305                         ResolveConditionalAccessReceiver (rc);
10306
10307                         var expr = CreateAccessExpression (rc, conditional_access_receiver);
10308                         if (expr == null)
10309                                 return null;
10310
10311                         return expr.Resolve (rc);
10312                 }
10313
10314                 public override Expression DoResolveLValue (ResolveContext ec, Expression rhs)
10315                 {
10316                         var res = CreateAccessExpression (ec, false);
10317                         if (res == null)
10318                                 return null;
10319
10320                         return res.ResolveLValue (ec, rhs);
10321                 }
10322                 
10323                 public override void Emit (EmitContext ec)
10324                 {
10325                         throw new Exception ("Should never be reached");
10326                 }
10327
10328                 public override void FlowAnalysis (FlowAnalysisContext fc)
10329                 {
10330                         Expr.FlowAnalysis (fc);
10331
10332                         Arguments.FlowAnalysis (fc);
10333                 }
10334
10335                 public override string GetSignatureForError ()
10336                 {
10337                         return Expr.GetSignatureForError ();
10338                 }
10339
10340                 protected override void CloneTo (CloneContext clonectx, Expression t)
10341                 {
10342                         ElementAccess target = (ElementAccess) t;
10343
10344                         target.Expr = Expr.Clone (clonectx);
10345                         if (Arguments != null)
10346                                 target.Arguments = Arguments.Clone (clonectx);
10347                 }
10348                 
10349                 public override object Accept (StructuralVisitor visitor)
10350                 {
10351                         return visitor.Visit (this);
10352                 }
10353         }
10354
10355         /// <summary>
10356         ///   Implements array access 
10357         /// </summary>
10358         public class ArrayAccess : Expression, IDynamicAssign, IMemoryLocation {
10359                 //
10360                 // Points to our "data" repository
10361                 //
10362                 ElementAccess ea;
10363
10364                 LocalTemporary temp;
10365                 bool prepared;
10366                 bool? has_await_args;
10367                 bool conditional_access_receiver;
10368                 
10369                 public ArrayAccess (ElementAccess ea_data, Location l)
10370                 {
10371                         ea = ea_data;
10372                         loc = l;
10373                 }
10374
10375                 public bool ConditionalAccess { get; set; }
10376
10377                 public void AddressOf (EmitContext ec, AddressOp mode)
10378                 {
10379                         var ac = (ArrayContainer) ea.Expr.Type;
10380
10381                         if (!has_await_args.HasValue && ec.HasSet (BuilderContext.Options.AsyncBody) && ea.Arguments.ContainsEmitWithAwait ()) {
10382                                 LoadInstanceAndArguments (ec, false, true);
10383                         }
10384
10385                         LoadInstanceAndArguments (ec, false, false);
10386
10387                         if (ac.Element.IsGenericParameter && mode == AddressOp.Load)
10388                                 ec.Emit (OpCodes.Readonly);
10389
10390                         ec.EmitArrayAddress (ac);
10391                 }
10392
10393                 public override Expression CreateExpressionTree (ResolveContext ec)
10394                 {
10395                         if (ConditionalAccess)
10396                                 Error_NullShortCircuitInsideExpressionTree (ec);
10397
10398                         return ea.CreateExpressionTree (ec);
10399                 }
10400
10401                 public override bool ContainsEmitWithAwait ()
10402                 {
10403                         return ea.ContainsEmitWithAwait ();
10404                 }
10405
10406                 public override Expression DoResolveLValue (ResolveContext ec, Expression right_side)
10407                 {
10408                         if (HasConditionalAccess ())
10409                                 Error_NullPropagatingLValue (ec);
10410
10411                         return DoResolve (ec);
10412                 }
10413
10414                 protected override Expression DoResolve (ResolveContext ec)
10415                 {
10416                         // dynamic is used per argument in ConvertExpressionToArrayIndex case
10417                         bool dynamic;
10418                         ea.Arguments.Resolve (ec, out dynamic);
10419
10420                         var ac = ea.Expr.Type as ArrayContainer;
10421                         int rank = ea.Arguments.Count;
10422                         if (ac.Rank != rank) {
10423                                 ec.Report.Error (22, ea.Location, "Wrong number of indexes `{0}' inside [], expected `{1}'",
10424                                           rank.ToString (), ac.Rank.ToString ());
10425                                 return null;
10426                         }
10427
10428                         type = ac.Element;
10429                         if (type.IsPointer && !ec.IsUnsafe) {
10430                                 UnsafeError (ec, ea.Location);
10431                         }
10432
10433                         if (conditional_access_receiver)
10434                                 type = LiftMemberType (ec, type);
10435
10436                         foreach (Argument a in ea.Arguments) {
10437                                 var na = a as NamedArgument;
10438                                 if (na != null)
10439                                         ElementAccess.Error_NamedArgument (na, ec.Report);
10440
10441                                 a.Expr = ConvertExpressionToArrayIndex (ec, a.Expr);
10442                         }
10443                         
10444                         eclass = ExprClass.Variable;
10445
10446                         return this;
10447                 }
10448
10449                 protected override void Error_NegativeArrayIndex (ResolveContext ec, Location loc)
10450                 {
10451                         ec.Report.Warning (251, 2, loc, "Indexing an array with a negative index (array indices always start at zero)");
10452                 }
10453
10454                 public override void FlowAnalysis (FlowAnalysisContext fc)
10455                 {
10456                         var da = conditional_access_receiver ? fc.BranchDefiniteAssignment () : null;
10457
10458                         ea.FlowAnalysis (fc);
10459
10460                         if (conditional_access_receiver)
10461                                 fc.DefiniteAssignment = da;
10462                 }
10463
10464                 public override bool HasConditionalAccess ()
10465                 {
10466                         return ConditionalAccess || ea.Expr.HasConditionalAccess ();
10467                 }
10468
10469                 //
10470                 // Load the array arguments into the stack.
10471                 //
10472                 void LoadInstanceAndArguments (EmitContext ec, bool duplicateArguments, bool prepareAwait)
10473                 {
10474                         if (prepareAwait) {
10475                                 ea.Expr = ea.Expr.EmitToField (ec);
10476                         } else {
10477                                 var ie = new InstanceEmitter (ea.Expr, false);
10478                                 ie.Emit (ec, ConditionalAccess);
10479
10480                                 if (duplicateArguments) {
10481                                         ec.Emit (OpCodes.Dup);
10482
10483                                         var copy = new LocalTemporary (ea.Expr.Type);
10484                                         copy.Store (ec);
10485                                         ea.Expr = copy;
10486                                 }
10487                         }
10488
10489                         var dup_args = ea.Arguments.Emit (ec, duplicateArguments, prepareAwait);
10490                         if (dup_args != null)
10491                                 ea.Arguments = dup_args;
10492                 }
10493
10494                 public void Emit (EmitContext ec, bool leave_copy)
10495                 {
10496                         if (prepared) {
10497                                 ec.EmitLoadFromPtr (type);
10498                         } else {
10499                                 if (!has_await_args.HasValue && ec.HasSet (BuilderContext.Options.AsyncBody) && ea.Arguments.ContainsEmitWithAwait ()) {
10500                                         LoadInstanceAndArguments (ec, false, true);
10501                                 }
10502
10503                                 if (conditional_access_receiver)
10504                                         ec.ConditionalAccess = new ConditionalAccessContext (type, ec.DefineLabel ());
10505
10506                                 var ac = (ArrayContainer) ea.Expr.Type;
10507                                 LoadInstanceAndArguments (ec, false, false);
10508                                 ec.EmitArrayLoad (ac);
10509
10510                                 if (conditional_access_receiver)
10511                                         ec.CloseConditionalAccess (type.IsNullableType && type != ac.Element ? type : null);
10512                         }       
10513
10514                         if (leave_copy) {
10515                                 ec.Emit (OpCodes.Dup);
10516                                 temp = new LocalTemporary (this.type);
10517                                 temp.Store (ec);
10518                         }
10519                 }
10520                 
10521                 public override void Emit (EmitContext ec)
10522                 {
10523                         Emit (ec, false);
10524                 }
10525
10526                 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool isCompound)
10527                 {
10528                         var ac = (ArrayContainer) ea.Expr.Type;
10529                         TypeSpec t = source.Type;
10530
10531                         has_await_args = ec.HasSet (BuilderContext.Options.AsyncBody) && (ea.Arguments.ContainsEmitWithAwait () || source.ContainsEmitWithAwait ());
10532
10533                         //
10534                         // When we are dealing with a struct, get the address of it to avoid value copy
10535                         // Same cannot be done for reference type because array covariance and the
10536                         // check in ldelema requires to specify the type of array element stored at the index
10537                         //
10538                         if (t.IsStruct && ((isCompound && !(source is DynamicExpressionStatement)) || !BuiltinTypeSpec.IsPrimitiveType (t))) {
10539                                 LoadInstanceAndArguments (ec, false, has_await_args.Value);
10540
10541                                 if (has_await_args.Value) {
10542                                         if (source.ContainsEmitWithAwait ()) {
10543                                                 source = source.EmitToField (ec);
10544                                                 isCompound = false;
10545                                                 prepared = true;
10546                                         }
10547
10548                                         LoadInstanceAndArguments (ec, isCompound, false);
10549                                 } else {
10550                                         prepared = true;
10551                                 }
10552
10553                                 ec.EmitArrayAddress (ac);
10554
10555                                 if (isCompound) {
10556                                         ec.Emit (OpCodes.Dup);
10557                                         prepared = true;
10558                                 }
10559                         } else {
10560                                 LoadInstanceAndArguments (ec, isCompound, has_await_args.Value);
10561
10562                                 if (has_await_args.Value) {
10563                                         if (source.ContainsEmitWithAwait ())
10564                                                 source = source.EmitToField (ec);
10565
10566                                         LoadInstanceAndArguments (ec, false, false);
10567                                 }
10568                         }
10569
10570                         source.Emit (ec);
10571
10572                         if (isCompound) {
10573                                 var lt = ea.Expr as LocalTemporary;
10574                                 if (lt != null)
10575                                         lt.Release (ec);
10576                         }
10577
10578                         if (leave_copy) {
10579                                 ec.Emit (OpCodes.Dup);
10580                                 temp = new LocalTemporary (this.type);
10581                                 temp.Store (ec);
10582                         }
10583
10584                         if (prepared) {
10585                                 ec.EmitStoreFromPtr (t);
10586                         } else {
10587                                 ec.EmitArrayStore (ac);
10588                         }
10589                         
10590                         if (temp != null) {
10591                                 temp.Emit (ec);
10592                                 temp.Release (ec);
10593                         }
10594                 }
10595
10596                 public override Expression EmitToField (EmitContext ec)
10597                 {
10598                         //
10599                         // Have to be specialized for arrays to get access to
10600                         // underlying element. Instead of another result copy we
10601                         // need direct access to element 
10602                         //
10603                         // Consider:
10604                         //
10605                         // CallRef (ref a[await Task.Factory.StartNew (() => 1)]);
10606                         //
10607                         ea.Expr = ea.Expr.EmitToField (ec);
10608                         ea.Arguments = ea.Arguments.Emit (ec, false, true);
10609                         return this;
10610                 }
10611
10612                 public SLE.Expression MakeAssignExpression (BuilderContext ctx, Expression source)
10613                 {
10614                         return SLE.Expression.ArrayAccess (ea.Expr.MakeExpression (ctx), MakeExpressionArguments (ctx));
10615                 }
10616
10617                 public override SLE.Expression MakeExpression (BuilderContext ctx)
10618                 {
10619                         return SLE.Expression.ArrayIndex (ea.Expr.MakeExpression (ctx), MakeExpressionArguments (ctx));
10620                 }
10621
10622                 SLE.Expression[] MakeExpressionArguments (BuilderContext ctx)
10623                 {
10624                         using (ctx.With (BuilderContext.Options.CheckedScope, true)) {
10625                                 return Arguments.MakeExpression (ea.Arguments, ctx);
10626                         }
10627                 }
10628
10629                 public void SetConditionalAccessReceiver ()
10630                 {
10631                         conditional_access_receiver = true;
10632                 }
10633         }
10634
10635         //
10636         // Indexer access expression
10637         //
10638         class IndexerExpr : PropertyOrIndexerExpr<IndexerSpec>, OverloadResolver.IBaseMembersProvider
10639         {
10640                 IList<MemberSpec> indexers;
10641                 Arguments arguments;
10642                 TypeSpec queried_type;
10643                 
10644                 public IndexerExpr (IList<MemberSpec> indexers, TypeSpec queriedType, ElementAccess ea)
10645                         : this (indexers, queriedType, ea.Expr, ea.Arguments, ea.Location)
10646                 {
10647                 }
10648
10649                 public IndexerExpr (IList<MemberSpec> indexers, TypeSpec queriedType, Expression instance, Arguments args, Location loc)
10650                         : base (loc)
10651                 {
10652                         this.indexers = indexers;
10653                         this.queried_type = queriedType;
10654                         this.InstanceExpression = instance;
10655                         this.arguments = args;
10656                 }
10657
10658                 #region Properties
10659
10660                 protected override Arguments Arguments {
10661                         get {
10662                                 return arguments;
10663                         }
10664                         set {
10665                                 arguments = value;
10666                         }
10667                 }
10668
10669                 protected override TypeSpec DeclaringType {
10670                         get {
10671                                 return best_candidate.DeclaringType;
10672                         }
10673                 }
10674
10675                 public override bool IsInstance {
10676                         get {
10677                                 return true;
10678                         }
10679                 }
10680
10681                 public override bool IsStatic {
10682                         get {
10683                                 return false;
10684                         }
10685                 }
10686
10687                 public override string KindName {
10688                         get { return "indexer"; }
10689                 }
10690
10691                 public override string Name {
10692                         get {
10693                                 return "this";
10694                         }
10695                 }
10696
10697                 #endregion
10698
10699                 public override bool ContainsEmitWithAwait ()
10700                 {
10701                         return base.ContainsEmitWithAwait () || arguments.ContainsEmitWithAwait ();
10702                 }
10703
10704                 public override Expression CreateExpressionTree (ResolveContext ec)
10705                 {
10706                         if (ConditionalAccess) {
10707                                 Error_NullShortCircuitInsideExpressionTree (ec);
10708                         }
10709
10710                         Arguments args = Arguments.CreateForExpressionTree (ec, arguments,
10711                                 InstanceExpression.CreateExpressionTree (ec),
10712                                 new TypeOfMethod (Getter, loc));
10713
10714                         return CreateExpressionFactoryCall (ec, "Call", args);
10715                 }
10716         
10717                 public override void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool isCompound)
10718                 {
10719                         LocalTemporary await_source_arg = null;
10720
10721                         if (isCompound) {
10722                                 emitting_compound_assignment = true;
10723                                 if (source is DynamicExpressionStatement) {
10724                                         Emit (ec, false);
10725                                 } else {
10726                                         source.Emit (ec);
10727                                 }
10728                                 emitting_compound_assignment = false;
10729
10730                                 if (has_await_arguments) {
10731                                         await_source_arg = new LocalTemporary (Type);
10732                                         await_source_arg.Store (ec);
10733
10734                                         arguments.Add (new Argument (await_source_arg));
10735
10736                                         if (leave_copy) {
10737                                                 temp = await_source_arg;
10738                                         }
10739
10740                                         has_await_arguments = false;
10741                                 } else {
10742                                         arguments = null;
10743
10744                                         if (leave_copy) {
10745                                                 ec.Emit (OpCodes.Dup);
10746                                                 temp = new LocalTemporary (Type);
10747                                                 temp.Store (ec);
10748                                         }
10749                                 }
10750                         } else {
10751                                 if (leave_copy) {
10752                                         if (ec.HasSet (BuilderContext.Options.AsyncBody) && (arguments.ContainsEmitWithAwait () || source.ContainsEmitWithAwait ())) {
10753                                                 source = source.EmitToField (ec);
10754                                         } else {
10755                                                 temp = new LocalTemporary (Type);
10756                                                 source.Emit (ec);
10757                                                 temp.Store (ec);
10758                                                 source = temp;
10759                                         }
10760                                 }
10761
10762                                 arguments.Add (new Argument (source));
10763                         }
10764
10765                         var call = new CallEmitter ();
10766                         call.InstanceExpression = InstanceExpression;
10767                         if (arguments == null)
10768                                 call.InstanceExpressionOnStack = true;
10769
10770                         call.Emit (ec, Setter, arguments, loc);
10771
10772                         if (temp != null) {
10773                                 temp.Emit (ec);
10774                                 temp.Release (ec);
10775                         } else if (leave_copy) {
10776                                 source.Emit (ec);
10777                         }
10778
10779                         if (await_source_arg != null) {
10780                                 await_source_arg.Release (ec);
10781                         }
10782                 }
10783
10784                 public override void FlowAnalysis (FlowAnalysisContext fc)
10785                 {
10786                         var da = conditional_access_receiver ? fc.BranchDefiniteAssignment () : null;
10787
10788                         base.FlowAnalysis (fc);
10789                         arguments.FlowAnalysis (fc);
10790
10791                         if (conditional_access_receiver)
10792                                 fc.DefiniteAssignment = da;
10793                 }
10794
10795                 public override string GetSignatureForError ()
10796                 {
10797                         return best_candidate.GetSignatureForError ();
10798                 }
10799                 
10800                 public override SLE.Expression MakeAssignExpression (BuilderContext ctx, Expression source)
10801                 {
10802 #if STATIC
10803                         throw new NotSupportedException ();
10804 #else
10805                         var value = new[] { source.MakeExpression (ctx) };
10806                         var args = Arguments.MakeExpression (arguments, ctx).Concat (value);
10807                         return SLE.Expression.Block (
10808                                         SLE.Expression.Call (InstanceExpression.MakeExpression (ctx), (MethodInfo) Setter.GetMetaInfo (), args),
10809                                         value [0]);
10810 #endif
10811                 }
10812
10813                 public override SLE.Expression MakeExpression (BuilderContext ctx)
10814                 {
10815 #if STATIC
10816                         return base.MakeExpression (ctx);
10817 #else
10818                         var args = Arguments.MakeExpression (arguments, ctx);
10819                         return SLE.Expression.Call (InstanceExpression.MakeExpression (ctx), (MethodInfo) Getter.GetMetaInfo (), args);
10820 #endif
10821                 }
10822
10823                 protected override Expression OverloadResolve (ResolveContext rc, Expression right_side)
10824                 {
10825                         if (best_candidate != null)
10826                                 return this;
10827
10828                         eclass = ExprClass.IndexerAccess;
10829
10830                         bool dynamic;
10831                         using (rc.With (ResolveContext.Options.DontSetConditionalAccessReceiver, false)) {
10832                                 arguments.Resolve (rc, out dynamic);
10833                         }
10834
10835                         if (indexers == null && InstanceExpression.Type.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
10836                                 dynamic = true;
10837                         } else {
10838                                 var res = new OverloadResolver (indexers, OverloadResolver.Restrictions.None, loc);
10839                                 res.BaseMembersProvider = this;
10840                                 res.InstanceQualifier = this;
10841
10842                                 // TODO: Do I need 2 argument sets?
10843                                 best_candidate = res.ResolveMember<IndexerSpec> (rc, ref arguments);
10844                                 if (best_candidate != null)
10845                                         type = res.BestCandidateReturnType;
10846                                 else if (!res.BestCandidateIsDynamic)
10847                                         return null;
10848                         }
10849
10850                         //
10851                         // It has dynamic arguments
10852                         //
10853                         if (dynamic) {
10854                                 Arguments args = new Arguments (arguments.Count + 1);
10855                                 if (IsBase) {
10856                                         rc.Report.Error (1972, loc,
10857                                                 "The indexer base access cannot be dynamically dispatched. Consider casting the dynamic arguments or eliminating the base access");
10858                                 } else {
10859                                         args.Add (new Argument (InstanceExpression));
10860                                 }
10861                                 args.AddRange (arguments);
10862
10863                                 best_candidate = null;
10864                                 return new DynamicIndexBinder (args, loc);
10865                         }
10866
10867                         //
10868                         // Try to avoid resolving left expression again
10869                         //
10870                         if (right_side != null)
10871                                 ResolveInstanceExpression (rc, right_side);
10872
10873                         return this;
10874                 }
10875
10876                 protected override void CloneTo (CloneContext clonectx, Expression t)
10877                 {
10878                         IndexerExpr target = (IndexerExpr) t;
10879
10880                         if (arguments != null)
10881                                 target.arguments = arguments.Clone (clonectx);
10882                 }
10883
10884                 public void SetConditionalAccessReceiver ()
10885                 {
10886                         conditional_access_receiver = true;
10887                 }
10888
10889                 public override void SetTypeArguments (ResolveContext ec, TypeArguments ta)
10890                 {
10891                         Error_TypeArgumentsCannotBeUsed (ec, "indexer", GetSignatureForError (), loc);
10892                 }
10893
10894                 #region IBaseMembersProvider Members
10895
10896                 IList<MemberSpec> OverloadResolver.IBaseMembersProvider.GetBaseMembers (TypeSpec baseType)
10897                 {
10898                         return baseType == null ? null : MemberCache.FindMembers (baseType, MemberCache.IndexerNameAlias, false);
10899                 }
10900
10901                 IParametersMember OverloadResolver.IBaseMembersProvider.GetOverrideMemberParameters (MemberSpec member)
10902                 {
10903                         if (queried_type == member.DeclaringType)
10904                                 return null;
10905
10906                         var filter = new MemberFilter (MemberCache.IndexerNameAlias, 0, MemberKind.Indexer, ((IndexerSpec) member).Parameters, null);
10907                         return MemberCache.FindMember (queried_type, filter, BindingRestriction.InstanceOnly | BindingRestriction.OverrideOnly) as IParametersMember;
10908                 }
10909
10910                 MethodGroupExpr OverloadResolver.IBaseMembersProvider.LookupExtensionMethod (ResolveContext rc)
10911                 {
10912                         return null;
10913                 }
10914
10915                 #endregion
10916         }
10917
10918         //
10919         // A base access expression
10920         //
10921         public class BaseThis : This
10922         {
10923                 public BaseThis (Location loc)
10924                         : base (loc)
10925                 {
10926                 }
10927
10928                 public BaseThis (TypeSpec type, Location loc)
10929                         : base (loc)
10930                 {
10931                         this.type = type;
10932                         eclass = ExprClass.Variable;
10933                 }
10934
10935                 #region Properties
10936
10937                 public override string Name {
10938                         get {
10939                                 return "base";
10940                         }
10941                 }
10942
10943                 #endregion
10944
10945                 public override Expression CreateExpressionTree (ResolveContext ec)
10946                 {
10947                         ec.Report.Error (831, loc, "An expression tree may not contain a base access");
10948                         return base.CreateExpressionTree (ec);
10949                 }
10950
10951                 public override void Emit (EmitContext ec)
10952                 {
10953                         base.Emit (ec);
10954
10955                         if (type == ec.Module.Compiler.BuiltinTypes.ValueType) {
10956                                 var context_type = ec.CurrentType;
10957                                 ec.Emit (OpCodes.Ldobj, context_type);
10958                                 ec.Emit (OpCodes.Box, context_type);
10959                         }
10960                 }
10961
10962                 protected override void Error_ThisNotAvailable (ResolveContext ec)
10963                 {
10964                         if (ec.IsStatic) {
10965                                 ec.Report.Error (1511, loc, "Keyword `base' is not available in a static method");
10966                         } else {
10967                                 ec.Report.Error (1512, loc, "Keyword `base' is not available in the current context");
10968                         }
10969                 }
10970
10971                 public override void ResolveBase (ResolveContext ec)
10972                 {
10973                         base.ResolveBase (ec);
10974                         type = ec.CurrentType.BaseType;
10975                 }
10976
10977                 public override object Accept (StructuralVisitor visitor)
10978                 {
10979                         return visitor.Visit (this);
10980                 }
10981         }
10982
10983         /// <summary>
10984         ///   This class exists solely to pass the Type around and to be a dummy
10985         ///   that can be passed to the conversion functions (this is used by
10986         ///   foreach implementation to typecast the object return value from
10987         ///   get_Current into the proper type.  All code has been generated and
10988         ///   we only care about the side effect conversions to be performed
10989         ///
10990         ///   This is also now used as a placeholder where a no-action expression
10991         ///   is needed (the `New' class).
10992         /// </summary>
10993         public class EmptyExpression : Expression
10994         {
10995                 sealed class OutAccessExpression : EmptyExpression
10996                 {
10997                         public OutAccessExpression (TypeSpec t)
10998                                 : base (t)
10999                         {
11000                         }
11001
11002                         public override Expression DoResolveLValue (ResolveContext rc, Expression right_side)
11003                         {
11004                                 rc.Report.Error (206, right_side.Location,
11005                                         "A property, indexer or dynamic member access may not be passed as `ref' or `out' parameter");
11006
11007                                 return null;
11008                         }
11009                 }
11010
11011                 public static readonly EmptyExpression LValueMemberAccess = new EmptyExpression (InternalType.FakeInternalType);
11012                 public static readonly EmptyExpression LValueMemberOutAccess = new EmptyExpression (InternalType.FakeInternalType);
11013                 public static readonly EmptyExpression UnaryAddress = new EmptyExpression (InternalType.FakeInternalType);
11014                 public static readonly EmptyExpression EventAddition = new EmptyExpression (InternalType.FakeInternalType);
11015                 public static readonly EmptyExpression EventSubtraction = new EmptyExpression (InternalType.FakeInternalType);
11016                 public static readonly EmptyExpression MissingValue = new EmptyExpression (InternalType.FakeInternalType);
11017                 public static readonly Expression Null = new EmptyExpression (InternalType.FakeInternalType);
11018                 public static readonly EmptyExpression OutAccess = new OutAccessExpression (InternalType.FakeInternalType);
11019
11020                 public EmptyExpression (TypeSpec t)
11021                 {
11022                         type = t;
11023                         eclass = ExprClass.Value;
11024                         loc = Location.Null;
11025                 }
11026
11027                 protected override void CloneTo (CloneContext clonectx, Expression target)
11028                 {
11029                 }
11030
11031                 public override bool ContainsEmitWithAwait ()
11032                 {
11033                         return false;
11034                 }
11035
11036                 public override Expression CreateExpressionTree (ResolveContext ec)
11037                 {
11038                         throw new NotSupportedException ("ET");
11039                 }
11040                 
11041                 protected override Expression DoResolve (ResolveContext ec)
11042                 {
11043                         return this;
11044                 }
11045
11046                 public override void Emit (EmitContext ec)
11047                 {
11048                         // nothing, as we only exist to not do anything.
11049                 }
11050
11051                 public override void EmitBranchable (EmitContext ec, Label target, bool on_true)
11052                 {
11053                 }
11054
11055                 public override void EmitSideEffect (EmitContext ec)
11056                 {
11057                 }
11058
11059                 public override object Accept (StructuralVisitor visitor)
11060                 {
11061                         return visitor.Visit (this);
11062                 }
11063         }
11064         
11065         sealed class EmptyAwaitExpression : EmptyExpression
11066         {
11067                 public EmptyAwaitExpression (TypeSpec type)
11068                         : base (type)
11069                 {
11070                 }
11071                 
11072                 public override bool ContainsEmitWithAwait ()
11073                 {
11074                         return true;
11075                 }
11076         }
11077         
11078         //
11079         // Empty statement expression
11080         //
11081         public sealed class EmptyExpressionStatement : ExpressionStatement
11082         {
11083                 public static readonly EmptyExpressionStatement Instance = new EmptyExpressionStatement ();
11084
11085                 private EmptyExpressionStatement ()
11086                 {
11087                         loc = Location.Null;
11088                 }
11089
11090                 public override bool ContainsEmitWithAwait ()
11091                 {
11092                         return false;
11093                 }
11094
11095                 public override Expression CreateExpressionTree (ResolveContext ec)
11096                 {
11097                         return null;
11098                 }
11099
11100                 public override void EmitStatement (EmitContext ec)
11101                 {
11102                         // Do nothing
11103                 }
11104
11105                 protected override Expression DoResolve (ResolveContext ec)
11106                 {
11107                         eclass = ExprClass.Value;
11108                         type = ec.BuiltinTypes.Object;
11109                         return this;
11110                 }
11111
11112                 public override void Emit (EmitContext ec)
11113                 {
11114                         // Do nothing
11115                 }
11116                 
11117                 public override object Accept (StructuralVisitor visitor)
11118                 {
11119                         return visitor.Visit (this);
11120                 }
11121         }
11122
11123         public class ErrorExpression : EmptyExpression
11124         {
11125                 public static readonly ErrorExpression Instance = new ErrorExpression ();
11126
11127                 private ErrorExpression ()
11128                         : base (InternalType.ErrorType)
11129                 {
11130                 }
11131
11132                 public override Expression CreateExpressionTree (ResolveContext ec)
11133                 {
11134                         return this;
11135                 }
11136
11137                 public override Expression DoResolveLValue (ResolveContext rc, Expression right_side)
11138                 {
11139                         return this;
11140                 }
11141
11142                 public override void Error_ValueAssignment (ResolveContext rc, Expression rhs)
11143                 {
11144                 }
11145
11146                 public override void Error_UnexpectedKind (ResolveContext ec, ResolveFlags flags, Location loc)
11147                 {
11148                 }
11149
11150                 public override void Error_ValueCannotBeConverted (ResolveContext ec, TypeSpec target, bool expl)
11151                 {
11152                 }
11153
11154                 public override void Error_OperatorCannotBeApplied (ResolveContext rc, Location loc, string oper, TypeSpec t)
11155                 {
11156                 }
11157                 
11158                 public override object Accept (StructuralVisitor visitor)
11159                 {
11160                         return visitor.Visit (this);
11161                 }
11162         }
11163
11164         public class UserCast : Expression {
11165                 MethodSpec method;
11166                 Expression source;
11167                 
11168                 public UserCast (MethodSpec method, Expression source, Location l)
11169                 {
11170                         if (source == null)
11171                                 throw new ArgumentNullException ("source");
11172
11173                         this.method = method;
11174                         this.source = source;
11175                         type = method.ReturnType;
11176                         loc = l;
11177                 }
11178
11179                 public Expression Source {
11180                         get {
11181                                 return source;
11182                         }
11183                         set {
11184                                 source = value;
11185                         }
11186                 }
11187
11188                 public override bool ContainsEmitWithAwait ()
11189                 {
11190                         return source.ContainsEmitWithAwait ();
11191                 }
11192
11193                 public override Expression CreateExpressionTree (ResolveContext ec)
11194                 {
11195                         Arguments args = new Arguments (3);
11196                         args.Add (new Argument (source.CreateExpressionTree (ec)));
11197                         args.Add (new Argument (new TypeOf (type, loc)));
11198                         args.Add (new Argument (new TypeOfMethod (method, loc)));
11199                         return CreateExpressionFactoryCall (ec, "Convert", args);
11200                 }
11201                         
11202                 protected override Expression DoResolve (ResolveContext ec)
11203                 {
11204                         method.CheckObsoleteness (ec, source.Location);
11205
11206                         eclass = ExprClass.Value;
11207                         return this;
11208                 }
11209
11210                 public override void Emit (EmitContext ec)
11211                 {
11212                         source.Emit (ec);
11213                         ec.MarkCallEntry (loc);
11214                         ec.Emit (OpCodes.Call, method);
11215                 }
11216
11217                 public override void FlowAnalysis (FlowAnalysisContext fc)
11218                 {
11219                         source.FlowAnalysis (fc);
11220                 }
11221
11222                 public override string GetSignatureForError ()
11223                 {
11224                         return TypeManager.CSharpSignature (method);
11225                 }
11226
11227                 public override SLE.Expression MakeExpression (BuilderContext ctx)
11228                 {
11229 #if STATIC
11230                         return base.MakeExpression (ctx);
11231 #else
11232                         return SLE.Expression.Convert (source.MakeExpression (ctx), type.GetMetaInfo (), (MethodInfo) method.GetMetaInfo ());
11233 #endif
11234                 }
11235         }
11236
11237         //
11238         // Holds additional type specifiers like ?, *, []
11239         //
11240         public class ComposedTypeSpecifier
11241         {
11242                 public static readonly ComposedTypeSpecifier SingleDimension = new ComposedTypeSpecifier (1, Location.Null);
11243
11244                 public readonly int Dimension;
11245                 public readonly Location Location;
11246
11247                 public ComposedTypeSpecifier (int specifier, Location loc)
11248                 {
11249                         this.Dimension = specifier;
11250                         this.Location = loc;
11251                 }
11252
11253                 #region Properties
11254                 public bool IsNullable {
11255                         get {
11256                                 return Dimension == -1;
11257                         }
11258                 }
11259
11260                 public bool IsPointer {
11261                         get {
11262                                 return Dimension == -2;
11263                         }
11264                 }
11265
11266                 public ComposedTypeSpecifier Next { get; set; }
11267
11268                 #endregion
11269
11270                 public static ComposedTypeSpecifier CreateArrayDimension (int dimension, Location loc)
11271                 {
11272                         return new ComposedTypeSpecifier (dimension, loc);
11273                 }
11274
11275                 public static ComposedTypeSpecifier CreateNullable (Location loc)
11276                 {
11277                         return new ComposedTypeSpecifier (-1, loc);
11278                 }
11279
11280                 public static ComposedTypeSpecifier CreatePointer (Location loc)
11281                 {
11282                         return new ComposedTypeSpecifier (-2, loc);
11283                 }
11284
11285                 public string GetSignatureForError ()
11286                 {
11287                         string s =
11288                                 IsPointer ? "*" :
11289                                 IsNullable ? "?" :
11290                                 ArrayContainer.GetPostfixSignature (Dimension);
11291
11292                         return Next != null ? s + Next.GetSignatureForError () : s;
11293                 }
11294         }
11295
11296         // <summary>
11297         //   This class is used to "construct" the type during a typecast
11298         //   operation.  Since the Type.GetType class in .NET can parse
11299         //   the type specification, we just use this to construct the type
11300         //   one bit at a time.
11301         // </summary>
11302         public class ComposedCast : TypeExpr {
11303                 FullNamedExpression left;
11304                 ComposedTypeSpecifier spec;
11305                 
11306                 public ComposedCast (FullNamedExpression left, ComposedTypeSpecifier spec)
11307                 {
11308                         if (spec == null)
11309                                 throw new ArgumentNullException ("spec");
11310
11311                         this.left = left;
11312                         this.spec = spec;
11313                         this.loc = left.Location;
11314                 }
11315
11316                 public override TypeSpec ResolveAsType (IMemberContext ec, bool allowUnboundTypeArguments)
11317                 {
11318                         type = left.ResolveAsType (ec);
11319                         if (type == null)
11320                                 return null;
11321
11322                         eclass = ExprClass.Type;
11323
11324                         var single_spec = spec;
11325
11326                         if (single_spec.IsNullable) {
11327                                 type = new Nullable.NullableType (type, loc).ResolveAsType (ec);
11328                                 if (type == null)
11329                                         return null;
11330
11331                                 single_spec = single_spec.Next;
11332                         } else if (single_spec.IsPointer) {
11333                                 //
11334                                 // Declared fields cannot have unmanaged check done before all types are defined
11335                                 //
11336                                 if (!(ec.CurrentMemberDefinition is Field) && !TypeManager.VerifyUnmanaged (ec.Module, type, loc))
11337                                         return null;
11338
11339                                 if (!ec.IsUnsafe) {
11340                                         UnsafeError (ec.Module.Compiler.Report, loc);
11341                                 }
11342
11343                                 do {
11344                                         type = PointerContainer.MakeType (ec.Module, type);
11345                                         single_spec = single_spec.Next;
11346                                 } while (single_spec != null && single_spec.IsPointer);
11347                         }
11348
11349                         if (single_spec != null && single_spec.Dimension > 0) {
11350                                 if (type.IsSpecialRuntimeType) {
11351                                         ec.Module.Compiler.Report.Error (611, loc, "Array elements cannot be of type `{0}'", type.GetSignatureForError ());
11352                                 } else if (type.IsStatic) {
11353                                         ec.Module.Compiler.Report.SymbolRelatedToPreviousError (type);
11354                                         ec.Module.Compiler.Report.Error (719, loc, "Array elements cannot be of static type `{0}'",
11355                                                 type.GetSignatureForError ());
11356                                 } else {
11357                                         MakeArray (ec.Module, single_spec);
11358                                 }
11359                         }
11360
11361                         return type;
11362                 }
11363
11364                 void MakeArray (ModuleContainer module, ComposedTypeSpecifier spec)
11365                 {
11366                         if (spec.Next != null)
11367                                 MakeArray (module, spec.Next);
11368
11369                         type = ArrayContainer.MakeType (module, type, spec.Dimension);
11370                 }
11371
11372                 public override string GetSignatureForError ()
11373                 {
11374                         return left.GetSignatureForError () + spec.GetSignatureForError ();
11375                 }
11376
11377                 public override object Accept (StructuralVisitor visitor)
11378                 {
11379                         return visitor.Visit (this);
11380                 }
11381         }
11382
11383         class FixedBufferPtr : Expression
11384         {
11385                 readonly Expression array;
11386
11387                 public FixedBufferPtr (Expression array, TypeSpec array_type, Location l)
11388                 {
11389                         this.type = array_type;
11390                         this.array = array;
11391                         this.loc = l;
11392                 }
11393
11394                 public override bool ContainsEmitWithAwait ()
11395                 {
11396                         throw new NotImplementedException ();
11397                 }
11398
11399                 public override Expression CreateExpressionTree (ResolveContext ec)
11400                 {
11401                         Error_PointerInsideExpressionTree (ec);
11402                         return null;
11403                 }
11404
11405                 public override void Emit(EmitContext ec)
11406                 {
11407                         array.Emit (ec);
11408                 }
11409
11410                 protected override Expression DoResolve (ResolveContext ec)
11411                 {
11412                         type = PointerContainer.MakeType (ec.Module, type);
11413                         eclass = ExprClass.Value;
11414                         return this;
11415                 }
11416         }
11417
11418
11419         //
11420         // This class is used to represent the address of an array, used
11421         // only by the Fixed statement, this generates "&a [0]" construct
11422         // for fixed (char *pa = a)
11423         //
11424         class ArrayPtr : FixedBufferPtr
11425         {
11426                 public ArrayPtr (Expression array, TypeSpec array_type, Location l):
11427                         base (array, array_type, l)
11428                 {
11429                 }
11430
11431                 public override void Emit (EmitContext ec)
11432                 {
11433                         base.Emit (ec);
11434                         
11435                         ec.EmitInt (0);
11436                         ec.Emit (OpCodes.Ldelema, ((PointerContainer) type).Element);
11437                 }
11438         }
11439
11440         //
11441         // Encapsulates a conversion rules required for array indexes
11442         //
11443         public class ArrayIndexCast : TypeCast
11444         {
11445                 public ArrayIndexCast (Expression expr, TypeSpec returnType)
11446                         : base (expr, returnType)
11447                 {
11448                         if (expr.Type == returnType) // int -> int
11449                                 throw new ArgumentException ("unnecessary array index conversion");
11450                 }
11451
11452                 public override Expression CreateExpressionTree (ResolveContext ec)
11453                 {
11454                         using (ec.Set (ResolveContext.Options.CheckedScope)) {
11455                                 return base.CreateExpressionTree (ec);
11456                         }
11457                 }
11458
11459                 public override void Emit (EmitContext ec)
11460                 {
11461                         child.Emit (ec);
11462
11463                         switch (child.Type.BuiltinType) {
11464                         case BuiltinTypeSpec.Type.UInt:
11465                                 ec.Emit (OpCodes.Conv_U);
11466                                 break;
11467                         case BuiltinTypeSpec.Type.Long:
11468                                 ec.Emit (OpCodes.Conv_Ovf_I);
11469                                 break;
11470                         case BuiltinTypeSpec.Type.ULong:
11471                                 ec.Emit (OpCodes.Conv_Ovf_I_Un);
11472                                 break;
11473                         default:
11474                                 throw new InternalErrorException ("Cannot emit cast to unknown array element type", type);
11475                         }
11476                 }
11477         }
11478
11479         //
11480         // Implements the `stackalloc' keyword
11481         //
11482         public class StackAlloc : Expression {
11483                 TypeSpec otype;
11484                 Expression texpr;
11485                 Expression count;
11486                 
11487                 public StackAlloc (Expression type, Expression count, Location l)
11488                 {
11489                         texpr = type;
11490                         this.count = count;
11491                         loc = l;
11492                 }
11493
11494                 public Expression TypeExpression {
11495                         get {
11496                                 return texpr;
11497                         }
11498                 }
11499
11500                 public Expression CountExpression {
11501                         get {
11502                                 return this.count;
11503                         }
11504                 }
11505
11506                 public override bool ContainsEmitWithAwait ()
11507                 {
11508                         return false;
11509                 }
11510
11511                 public override Expression CreateExpressionTree (ResolveContext ec)
11512                 {
11513                         throw new NotSupportedException ("ET");
11514                 }
11515
11516                 protected override Expression DoResolve (ResolveContext ec)
11517                 {
11518                         count = count.Resolve (ec);
11519                         if (count == null)
11520                                 return null;
11521                         
11522                         if (count.Type.BuiltinType != BuiltinTypeSpec.Type.UInt){
11523                                 count = Convert.ImplicitConversionRequired (ec, count, ec.BuiltinTypes.Int, loc);
11524                                 if (count == null)
11525                                         return null;
11526                         }
11527
11528                         Constant c = count as Constant;
11529                         if (c != null && c.IsNegative) {
11530                                 ec.Report.Error (247, loc, "Cannot use a negative size with stackalloc");
11531                         }
11532
11533                         if (ec.HasAny (ResolveContext.Options.CatchScope | ResolveContext.Options.FinallyScope)) {
11534                                 ec.Report.Error (255, loc, "Cannot use stackalloc in finally or catch");
11535                         }
11536
11537                         otype = texpr.ResolveAsType (ec);
11538                         if (otype == null)
11539                                 return null;
11540
11541                         if (!TypeManager.VerifyUnmanaged (ec.Module, otype, loc))
11542                                 return null;
11543
11544                         type = PointerContainer.MakeType (ec.Module, otype);
11545                         eclass = ExprClass.Value;
11546
11547                         return this;
11548                 }
11549
11550                 public override void Emit (EmitContext ec)
11551                 {
11552                         int size = BuiltinTypeSpec.GetSize (otype);
11553
11554                         count.Emit (ec);
11555
11556                         if (size == 0)
11557                                 ec.Emit (OpCodes.Sizeof, otype);
11558                         else
11559                                 ec.EmitInt (size);
11560
11561                         ec.Emit (OpCodes.Mul_Ovf_Un);
11562                         ec.Emit (OpCodes.Localloc);
11563                 }
11564
11565                 protected override void CloneTo (CloneContext clonectx, Expression t)
11566                 {
11567                         StackAlloc target = (StackAlloc) t;
11568                         target.count = count.Clone (clonectx);
11569                         target.texpr = texpr.Clone (clonectx);
11570                 }
11571                 
11572                 public override object Accept (StructuralVisitor visitor)
11573                 {
11574                         return visitor.Visit (this);
11575                 }
11576         }
11577
11578         //
11579         // An object initializer expression
11580         //
11581         public class ElementInitializer : Assign
11582         {
11583                 public readonly string Name;
11584
11585                 public ElementInitializer (string name, Expression initializer, Location loc)
11586                         : base (null, initializer, loc)
11587                 {
11588                         this.Name = name;
11589                 }
11590
11591                 public bool IsDictionaryInitializer {
11592                         get {
11593                                 return Name == null;
11594                         }
11595                 }
11596                 
11597                 protected override void CloneTo (CloneContext clonectx, Expression t)
11598                 {
11599                         ElementInitializer target = (ElementInitializer) t;
11600                         target.source = source.Clone (clonectx);
11601                 }
11602
11603                 public override Expression CreateExpressionTree (ResolveContext ec)
11604                 {
11605                         Arguments args = new Arguments (2);
11606                         FieldExpr fe = target as FieldExpr;
11607                         if (fe != null)
11608                                 args.Add (new Argument (fe.CreateTypeOfExpression ()));
11609                         else
11610                                 args.Add (new Argument (((PropertyExpr) target).CreateSetterTypeOfExpression (ec)));
11611
11612                         string mname;
11613                         Expression arg_expr;
11614                         var cinit = source as CollectionOrObjectInitializers;
11615                         if (cinit == null) {
11616                                 mname = "Bind";
11617                                 arg_expr = source.CreateExpressionTree (ec);
11618                         } else {
11619                                 mname = cinit.IsEmpty || cinit.Initializers[0] is ElementInitializer ? "MemberBind" : "ListBind";
11620                                 arg_expr = cinit.CreateExpressionTree (ec, !cinit.IsEmpty);
11621                         }
11622
11623                         args.Add (new Argument (arg_expr));
11624                         return CreateExpressionFactoryCall (ec, mname, args);
11625                 }
11626
11627                 protected override Expression DoResolve (ResolveContext ec)
11628                 {
11629                         if (source == null)
11630                                 return EmptyExpressionStatement.Instance;
11631
11632                         if (!ResolveElement (ec))
11633                                 return null;
11634
11635                         if (source is CollectionOrObjectInitializers) {
11636                                 target = target.Resolve (ec);
11637                                 if (target == null)
11638                                         return null;
11639                                 
11640                                 Expression previous = ec.CurrentInitializerVariable;
11641                                 ec.CurrentInitializerVariable = target;
11642                                 source = source.Resolve (ec);
11643                                 ec.CurrentInitializerVariable = previous;
11644                                 if (source == null)
11645                                         return null;
11646                                         
11647                                 eclass = source.eclass;
11648                                 type = source.Type;
11649
11650                                 return this;
11651                         }
11652
11653                         return base.DoResolve (ec);
11654                 }
11655         
11656                 public override void EmitStatement (EmitContext ec)
11657                 {
11658                         if (source is CollectionOrObjectInitializers)
11659                                 source.Emit (ec);
11660                         else
11661                                 base.EmitStatement (ec);
11662                 }
11663
11664                 protected virtual bool ResolveElement (ResolveContext rc)
11665                 {
11666                         var t = rc.CurrentInitializerVariable.Type;
11667                         if (t.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
11668                                 Arguments args = new Arguments (1);
11669                                 args.Add (new Argument (rc.CurrentInitializerVariable));
11670                                 target = new DynamicMemberBinder (Name, args, loc);
11671                         } else {
11672
11673                                 var member = MemberLookup (rc, false, t, Name, 0, MemberLookupRestrictions.ExactArity, loc);
11674                                 if (member == null) {
11675                                         member = Expression.MemberLookup (rc, true, t, Name, 0, MemberLookupRestrictions.ExactArity, loc);
11676
11677                                         if (member != null) {
11678                                                 // TODO: ec.Report.SymbolRelatedToPreviousError (member);
11679                                                 ErrorIsInaccesible (rc, member.GetSignatureForError (), loc);
11680                                                 return false;
11681                                         }
11682                                 }
11683
11684                                 if (member == null) {
11685                                         Error_TypeDoesNotContainDefinition (rc, loc, t, Name);
11686                                         return false;
11687                                 }
11688
11689                                 var me = member as MemberExpr;
11690                                 if (me is EventExpr) {
11691                                         me = me.ResolveMemberAccess (rc, null, null);
11692                                 } else if (!(member is PropertyExpr || member is FieldExpr)) {
11693                                         rc.Report.Error (1913, loc,
11694                                                 "Member `{0}' cannot be initialized. An object initializer may only be used for fields, or properties",
11695                                                 member.GetSignatureForError ());
11696
11697                                         return false;
11698                                 }
11699
11700                                 if (me.IsStatic) {
11701                                         rc.Report.Error (1914, loc,
11702                                                 "Static field or property `{0}' cannot be assigned in an object initializer",
11703                                                 me.GetSignatureForError ());
11704                                 }
11705
11706                                 target = me;
11707                                 me.InstanceExpression = rc.CurrentInitializerVariable;
11708                         }
11709
11710                         return true;
11711                 }
11712         }
11713         
11714         //
11715         // A collection initializer expression
11716         //
11717         class CollectionElementInitializer : Invocation
11718         {
11719                 public class ElementInitializerArgument : Argument
11720                 {
11721                         public ElementInitializerArgument (Expression e)
11722                                 : base (e)
11723                         {
11724                         }
11725                 }
11726
11727                 sealed class AddMemberAccess : MemberAccess
11728                 {
11729                         public AddMemberAccess (Expression expr, Location loc)
11730                                 : base (expr, "Add", loc)
11731                         {
11732                         }
11733
11734                         public override void Error_TypeDoesNotContainDefinition (ResolveContext ec, TypeSpec type, string name)
11735                         {
11736                                 if (TypeManager.HasElementType (type))
11737                                         return;
11738
11739                                 base.Error_TypeDoesNotContainDefinition (ec, type, name);
11740                         }
11741                 }
11742
11743                 public CollectionElementInitializer (Expression argument)
11744                         : base (null, new Arguments (1))
11745                 {
11746                         base.arguments.Add (new ElementInitializerArgument (argument));
11747                         this.loc = argument.Location;
11748                 }
11749
11750                 public CollectionElementInitializer (List<Expression> arguments, Location loc)
11751                         : base (null, new Arguments (arguments.Count))
11752                 {
11753                         foreach (Expression e in arguments)
11754                                 base.arguments.Add (new ElementInitializerArgument (e));
11755
11756                         this.loc = loc;
11757                 }
11758
11759                 public CollectionElementInitializer (Location loc)
11760                         : base (null, null)
11761                 {
11762                         this.loc = loc;
11763                 }
11764
11765                 public override Expression CreateExpressionTree (ResolveContext ec)
11766                 {
11767                         Arguments args = new Arguments (2);
11768                         args.Add (new Argument (mg.CreateExpressionTree (ec)));
11769
11770                         var expr_initializers = new ArrayInitializer (arguments.Count, loc);
11771                         foreach (Argument a in arguments) {
11772                                 if (a.ArgType == Argument.AType.ExtensionType) {
11773                                         ec.Report.Error (8075, a.Expr.Location, "An expression tree cannot contain a collection initializer with extension method");
11774                                         continue;
11775                                 }
11776                                 expr_initializers.Add (a.CreateExpressionTree (ec));
11777                         }
11778
11779                         args.Add (new Argument (new ArrayCreation (
11780                                 CreateExpressionTypeExpression (ec, loc), expr_initializers, loc)));
11781                         return CreateExpressionFactoryCall (ec, "ElementInit", args);
11782                 }
11783
11784                 protected override void CloneTo (CloneContext clonectx, Expression t)
11785                 {
11786                         CollectionElementInitializer target = (CollectionElementInitializer) t;
11787                         if (arguments != null)
11788                                 target.arguments = arguments.Clone (clonectx);
11789                 }
11790
11791                 protected override Expression DoResolve (ResolveContext ec)
11792                 {
11793                         base.expr = new AddMemberAccess (ec.CurrentInitializerVariable, loc);
11794
11795                         return base.DoResolve (ec);
11796                 }
11797         }
11798
11799         class DictionaryElementInitializer : ElementInitializer
11800         {
11801                 readonly Arguments args;
11802
11803                 public DictionaryElementInitializer (Arguments arguments, Expression initializer, Location loc)
11804                         : base (null, initializer, loc)
11805                 {
11806                         this.args = arguments;
11807                 }
11808
11809                 public override Expression CreateExpressionTree (ResolveContext ec)
11810                 {
11811                         ec.Report.Error (8074, loc, "Expression tree cannot contain a dictionary initializer");
11812                         return null;
11813                 }
11814
11815                 protected override bool ResolveElement (ResolveContext rc)
11816                 {
11817                         var init = rc.CurrentInitializerVariable;
11818                         var type = init.Type;
11819
11820                         if (type.IsArray) {
11821                                 target = new ArrayAccess (new ElementAccess (init, args, loc), loc);
11822                                 return true;
11823                         }
11824
11825                         if (type.IsPointer) {
11826                                 target = init.MakePointerAccess (rc, type, args);
11827                                 return true;
11828                         }
11829
11830                         var indexers = MemberCache.FindMembers (type, MemberCache.IndexerNameAlias, false);
11831                         if (indexers == null && type.BuiltinType != BuiltinTypeSpec.Type.Dynamic) {
11832                                 ElementAccess.Error_CannotApplyIndexing (rc, type, loc);
11833                                 return false;
11834                         }
11835
11836                         target = new IndexerExpr (indexers, type, init, args, loc);
11837                         return true;
11838                 }
11839         }
11840         
11841         //
11842         // A block of object or collection initializers
11843         //
11844         public class CollectionOrObjectInitializers : ExpressionStatement
11845         {
11846                 IList<Expression> initializers;
11847                 bool is_collection_initialization;
11848
11849                 public CollectionOrObjectInitializers (Location loc)
11850                         : this (new Expression[0], loc)
11851                 {
11852                 }
11853
11854                 public CollectionOrObjectInitializers (IList<Expression> initializers, Location loc)
11855                 {
11856                         this.initializers = initializers;
11857                         this.loc = loc;
11858                 }
11859
11860                 public IList<Expression> Initializers {
11861                         get {
11862                                 return initializers;
11863                         }
11864                 }
11865                 
11866                 public bool IsEmpty {
11867                         get {
11868                                 return initializers.Count == 0;
11869                         }
11870                 }
11871
11872                 public bool IsCollectionInitializer {
11873                         get {
11874                                 return is_collection_initialization;
11875                         }
11876                 }
11877
11878                 protected override void CloneTo (CloneContext clonectx, Expression target)
11879                 {
11880                         CollectionOrObjectInitializers t = (CollectionOrObjectInitializers) target;
11881
11882                         t.initializers = new List<Expression> (initializers.Count);
11883                         foreach (var e in initializers)
11884                                 t.initializers.Add (e.Clone (clonectx));
11885                 }
11886
11887                 public override bool ContainsEmitWithAwait ()
11888                 {
11889                         foreach (var e in initializers) {
11890                                 if (e.ContainsEmitWithAwait ())
11891                                         return true;
11892                         }
11893
11894                         return false;
11895                 }
11896
11897                 public override Expression CreateExpressionTree (ResolveContext ec)
11898                 {
11899                         return CreateExpressionTree (ec, false);
11900                 }
11901
11902                 public Expression CreateExpressionTree (ResolveContext ec, bool inferType)
11903                 {
11904                         var expr_initializers = new ArrayInitializer (initializers.Count, loc);
11905                         foreach (Expression e in initializers) {
11906                                 Expression expr = e.CreateExpressionTree (ec);
11907                                 if (expr != null)
11908                                         expr_initializers.Add (expr);
11909                         }
11910
11911                         if (inferType)
11912                                 return new ImplicitlyTypedArrayCreation (expr_initializers, loc);
11913
11914                         return new ArrayCreation (new TypeExpression (ec.Module.PredefinedTypes.MemberBinding.Resolve (), loc), expr_initializers, loc); 
11915                 }
11916                 
11917                 protected override Expression DoResolve (ResolveContext ec)
11918                 {
11919                         List<string> element_names = null;
11920                         for (int i = 0; i < initializers.Count; ++i) {
11921                                 Expression initializer = initializers [i];
11922                                 ElementInitializer element_initializer = initializer as ElementInitializer;
11923
11924                                 if (i == 0) {
11925                                         if (element_initializer != null) {
11926                                                 element_names = new List<string> (initializers.Count);
11927                                                 if (!element_initializer.IsDictionaryInitializer)
11928                                                         element_names.Add (element_initializer.Name);
11929                                         } else if (initializer is CompletingExpression) {
11930                                                 initializer.Resolve (ec);
11931                                                 throw new InternalErrorException ("This line should never be reached");
11932                                         } else {
11933                                                 var t = ec.CurrentInitializerVariable.Type;
11934                                                 // LAMESPEC: The collection must implement IEnumerable only, no dynamic support
11935                                                 if (!t.ImplementsInterface (ec.BuiltinTypes.IEnumerable, false) && t.BuiltinType != BuiltinTypeSpec.Type.Dynamic) {
11936                                                         ec.Report.Error (1922, loc, "A field or property `{0}' cannot be initialized with a collection " +
11937                                                                 "object initializer because type `{1}' does not implement `{2}' interface",
11938                                                                 ec.CurrentInitializerVariable.GetSignatureForError (),
11939                                                                 ec.CurrentInitializerVariable.Type.GetSignatureForError (),
11940                                                                 ec.BuiltinTypes.IEnumerable.GetSignatureForError ());
11941                                                         return null;
11942                                                 }
11943                                                 is_collection_initialization = true;
11944                                         }
11945                                 } else {
11946                                         if (is_collection_initialization != (element_initializer == null)) {
11947                                                 ec.Report.Error (747, initializer.Location, "Inconsistent `{0}' member declaration",
11948                                                         is_collection_initialization ? "collection initializer" : "object initializer");
11949                                                 continue;
11950                                         }
11951
11952                                         if (!is_collection_initialization && !element_initializer.IsDictionaryInitializer) {
11953                                                 if (element_names.Contains (element_initializer.Name)) {
11954                                                         ec.Report.Error (1912, element_initializer.Location,
11955                                                                 "An object initializer includes more than one member `{0}' initialization",
11956                                                                 element_initializer.Name);
11957                                                 } else {
11958                                                         element_names.Add (element_initializer.Name);
11959                                                 }
11960                                         }
11961                                 }
11962
11963                                 Expression e = initializer.Resolve (ec);
11964                                 if (e == EmptyExpressionStatement.Instance)
11965                                         initializers.RemoveAt (i--);
11966                                 else
11967                                         initializers [i] = e;
11968                         }
11969
11970                         type = ec.CurrentInitializerVariable.Type;
11971                         if (is_collection_initialization) {
11972                                 if (TypeManager.HasElementType (type)) {
11973                                         ec.Report.Error (1925, loc, "Cannot initialize object of type `{0}' with a collection initializer",
11974                                                 type.GetSignatureForError ());
11975                                 }
11976                         }
11977
11978                         eclass = ExprClass.Variable;
11979                         return this;
11980                 }
11981
11982                 public override void Emit (EmitContext ec)
11983                 {
11984                         EmitStatement (ec);
11985                 }
11986
11987                 public override void EmitStatement (EmitContext ec)
11988                 {
11989                         foreach (ExpressionStatement e in initializers) {
11990                                 // TODO: need location region
11991                                 ec.Mark (e.Location);
11992                                 e.EmitStatement (ec);
11993                         }
11994                 }
11995
11996                 public override void FlowAnalysis (FlowAnalysisContext fc)
11997                 {
11998                         foreach (var initializer in initializers) {
11999                                 if (initializer != null)
12000                                         initializer.FlowAnalysis (fc);
12001                         }
12002                 }
12003         }
12004         
12005         //
12006         // New expression with element/object initializers
12007         //
12008         public class NewInitialize : New
12009         {
12010                 //
12011                 // This class serves as a proxy for variable initializer target instances.
12012                 // A real variable is assigned later when we resolve left side of an
12013                 // assignment
12014                 //
12015                 sealed class InitializerTargetExpression : Expression, IMemoryLocation
12016                 {
12017                         NewInitialize new_instance;
12018
12019                         public InitializerTargetExpression (NewInitialize newInstance)
12020                         {
12021                                 this.type = newInstance.type;
12022                                 this.loc = newInstance.loc;
12023                                 this.eclass = newInstance.eclass;
12024                                 this.new_instance = newInstance;
12025                         }
12026
12027                         public override bool ContainsEmitWithAwait ()
12028                         {
12029                                 return false;
12030                         }
12031
12032                         public override Expression CreateExpressionTree (ResolveContext ec)
12033                         {
12034                                 // Should not be reached
12035                                 throw new NotSupportedException ("ET");
12036                         }
12037
12038                         protected override Expression DoResolve (ResolveContext ec)
12039                         {
12040                                 return this;
12041                         }
12042
12043                         public override Expression DoResolveLValue (ResolveContext ec, Expression right_side)
12044                         {
12045                                 return this;
12046                         }
12047
12048                         public override void Emit (EmitContext ec)
12049                         {
12050                                 Expression e = (Expression) new_instance.instance;
12051                                 e.Emit (ec);
12052                         }
12053
12054                         public override Expression EmitToField (EmitContext ec)
12055                         {
12056                                 return (Expression) new_instance.instance;
12057                         }
12058
12059                         #region IMemoryLocation Members
12060
12061                         public void AddressOf (EmitContext ec, AddressOp mode)
12062                         {
12063                                 new_instance.instance.AddressOf (ec, mode);
12064                         }
12065
12066                         #endregion
12067                 }
12068
12069                 CollectionOrObjectInitializers initializers;
12070                 IMemoryLocation instance;
12071                 DynamicExpressionStatement dynamic;
12072
12073                 public NewInitialize (FullNamedExpression requested_type, Arguments arguments, CollectionOrObjectInitializers initializers, Location l)
12074                         : base (requested_type, arguments, l)
12075                 {
12076                         this.initializers = initializers;
12077                 }
12078
12079                 public CollectionOrObjectInitializers Initializers {
12080                         get {
12081                                 return initializers;
12082                         }
12083                 }
12084
12085                 protected override void CloneTo (CloneContext clonectx, Expression t)
12086                 {
12087                         base.CloneTo (clonectx, t);
12088
12089                         NewInitialize target = (NewInitialize) t;
12090                         target.initializers = (CollectionOrObjectInitializers) initializers.Clone (clonectx);
12091                 }
12092
12093                 public override bool ContainsEmitWithAwait ()
12094                 {
12095                         return base.ContainsEmitWithAwait () || initializers.ContainsEmitWithAwait ();
12096                 }
12097
12098                 public override Expression CreateExpressionTree (ResolveContext ec)
12099                 {
12100                         Arguments args = new Arguments (2);
12101                         args.Add (new Argument (base.CreateExpressionTree (ec)));
12102                         if (!initializers.IsEmpty)
12103                                 args.Add (new Argument (initializers.CreateExpressionTree (ec, initializers.IsCollectionInitializer)));
12104
12105                         return CreateExpressionFactoryCall (ec,
12106                                 initializers.IsCollectionInitializer ? "ListInit" : "MemberInit",
12107                                 args);
12108                 }
12109
12110                 protected override Expression DoResolve (ResolveContext ec)
12111                 {
12112                         Expression e = base.DoResolve (ec);
12113                         if (type == null)
12114                                 return null;
12115
12116                         if (type.IsDelegate) {
12117                                 ec.Report.Error (1958, Initializers.Location,
12118                                         "Object and collection initializers cannot be used to instantiate a delegate");
12119                         }
12120
12121                         Expression previous = ec.CurrentInitializerVariable;
12122                         ec.CurrentInitializerVariable = new InitializerTargetExpression (this);
12123                         initializers.Resolve (ec);
12124                         ec.CurrentInitializerVariable = previous;
12125
12126                         dynamic = e as DynamicExpressionStatement;
12127                         if (dynamic != null)
12128                                 return this;
12129
12130                         return e;
12131                 }
12132
12133                 public override void Emit (EmitContext ec)
12134                 {
12135                         if (method == null && TypeSpec.IsValueType (type) && initializers.Initializers.Count > 1 && ec.HasSet (BuilderContext.Options.AsyncBody) && initializers.ContainsEmitWithAwait ()) {
12136                                 var fe = ec.GetTemporaryField (type);
12137
12138                                 if (!Emit (ec, fe))
12139                                         fe.Emit (ec);
12140
12141                                 return;
12142                         }
12143
12144                         base.Emit (ec);
12145                 }
12146
12147                 public override bool Emit (EmitContext ec, IMemoryLocation target)
12148                 {
12149                         //
12150                         // Expression is initialized into temporary target then moved
12151                         // to real one for atomicity
12152                         //
12153                         IMemoryLocation temp_target = target;
12154
12155                         LocalTemporary temp = null;
12156                         bool by_ref = false;
12157                         if (!initializers.IsEmpty) {
12158                                 temp_target = target as LocalTemporary;
12159                                 if (temp_target == null)
12160                                         temp_target = target as StackFieldExpr;
12161
12162                                 if (temp_target == null) {
12163                                         var vr = target as VariableReference;
12164                                         if (vr != null && vr.IsRef) {
12165                                                 vr.EmitLoad (ec);
12166                                                 by_ref = true;
12167                                         }
12168                                 }
12169
12170                                 if (temp_target == null)
12171                                         temp_target = temp = new LocalTemporary (type);
12172                         }
12173
12174                         bool left_on_stack;
12175                         if (dynamic != null) {
12176                                 dynamic.Emit (ec);
12177                                 left_on_stack = true;
12178                         } else {
12179                                 left_on_stack = base.Emit (ec, temp_target);
12180                         }
12181
12182                         if (initializers.IsEmpty)
12183                                 return left_on_stack;
12184
12185                         StackFieldExpr sf = null;
12186
12187                         // Move a new instance (reference-type) to local temporary variable
12188                         if (left_on_stack) {
12189                                 if (by_ref) {
12190                                         temp_target = temp = new LocalTemporary (type);
12191                                 }
12192
12193                                 if (temp != null)
12194                                         temp.Store (ec);
12195
12196                                 if (ec.HasSet (BuilderContext.Options.AsyncBody) && initializers.ContainsEmitWithAwait ()) {
12197                                         if (temp == null)
12198                                                 throw new NotImplementedException ();
12199
12200                                         sf = ec.GetTemporaryField (type);
12201                                         sf.EmitAssign (ec, temp, false, false);
12202                                         temp_target = sf;
12203                                         temp.Release (ec);
12204                                         left_on_stack = false;
12205                                 }
12206                         }
12207
12208                         instance = temp_target;
12209
12210                         initializers.Emit (ec);
12211
12212                         ((Expression)temp_target).Emit (ec);
12213
12214                         if (temp != null)
12215                                 temp.Release (ec);
12216
12217                         if (sf != null)
12218                                 sf.IsAvailableForReuse = true;
12219
12220                         return true;
12221                 }
12222
12223                 protected override IMemoryLocation EmitAddressOf (EmitContext ec, AddressOp Mode)
12224                 {
12225                         instance = base.EmitAddressOf (ec, Mode);
12226
12227                         if (!initializers.IsEmpty)
12228                                 initializers.Emit (ec);
12229
12230                         return instance;
12231                 }
12232
12233                 public override void FlowAnalysis (FlowAnalysisContext fc)
12234                 {
12235                         base.FlowAnalysis (fc);
12236                         initializers.FlowAnalysis (fc);
12237                 }
12238
12239                 public override object Accept (StructuralVisitor visitor)
12240                 {
12241                         return visitor.Visit (this);
12242                 }
12243         }
12244
12245         public class NewAnonymousType : New
12246         {
12247                 static readonly AnonymousTypeParameter[] EmptyParameters = new AnonymousTypeParameter[0];
12248
12249                 List<AnonymousTypeParameter> parameters;
12250                 readonly TypeContainer parent;
12251                 AnonymousTypeClass anonymous_type;
12252
12253                 public NewAnonymousType (List<AnonymousTypeParameter> parameters, TypeContainer parent, Location loc)
12254                          : base (null, null, loc)
12255                 {
12256                         this.parameters = parameters;
12257                         this.parent = parent;
12258                 }
12259
12260                 public List<AnonymousTypeParameter> Parameters {
12261                         get {
12262                                 return this.parameters;
12263                         }
12264                 }
12265
12266                 protected override void CloneTo (CloneContext clonectx, Expression target)
12267                 {
12268                         if (parameters == null)
12269                                 return;
12270
12271                         NewAnonymousType t = (NewAnonymousType) target;
12272                         t.parameters = new List<AnonymousTypeParameter> (parameters.Count);
12273                         foreach (AnonymousTypeParameter atp in parameters)
12274                                 t.parameters.Add ((AnonymousTypeParameter) atp.Clone (clonectx));
12275                 }
12276
12277                 AnonymousTypeClass CreateAnonymousType (ResolveContext ec, IList<AnonymousTypeParameter> parameters)
12278                 {
12279                         AnonymousTypeClass type = parent.Module.GetAnonymousType (parameters);
12280                         if (type != null)
12281                                 return type;
12282
12283                         type = AnonymousTypeClass.Create (parent, parameters, loc);
12284                         if (type == null)
12285                                 return null;
12286
12287                         int errors = ec.Report.Errors;
12288                         type.CreateContainer ();
12289                         type.DefineContainer ();
12290                         type.Define ();
12291                         if ((ec.Report.Errors - errors) == 0) {
12292                                 parent.Module.AddAnonymousType (type);
12293                                 type.PrepareEmit ();
12294                         }
12295
12296                         return type;
12297                 }
12298
12299                 public override Expression CreateExpressionTree (ResolveContext ec)
12300                 {
12301                         if (parameters == null)
12302                                 return base.CreateExpressionTree (ec);
12303
12304                         var init = new ArrayInitializer (parameters.Count, loc);
12305                         foreach (var m in anonymous_type.Members) {
12306                                 var p = m as Property;
12307                                 if (p != null)
12308                                         init.Add (new TypeOfMethod (MemberCache.GetMember (type, p.Get.Spec), loc));
12309                         }
12310
12311                         var ctor_args = new ArrayInitializer (arguments.Count, loc);
12312                         foreach (Argument a in arguments)
12313                                 ctor_args.Add (a.CreateExpressionTree (ec));
12314
12315                         Arguments args = new Arguments (3);
12316                         args.Add (new Argument (new TypeOfMethod (method, loc)));
12317                         args.Add (new Argument (new ArrayCreation (CreateExpressionTypeExpression (ec, loc), ctor_args, loc)));
12318                         args.Add (new Argument (new ImplicitlyTypedArrayCreation (init, loc)));
12319
12320                         return CreateExpressionFactoryCall (ec, "New", args);
12321                 }
12322
12323                 protected override Expression DoResolve (ResolveContext ec)
12324                 {
12325                         if (ec.HasSet (ResolveContext.Options.ConstantScope)) {
12326                                 ec.Report.Error (836, loc, "Anonymous types cannot be used in this expression");
12327                                 return null;
12328                         }
12329
12330                         if (parameters == null) {
12331                                 anonymous_type = CreateAnonymousType (ec, EmptyParameters);
12332                                 RequestedType = new TypeExpression (anonymous_type.Definition, loc);
12333                                 return base.DoResolve (ec);
12334                         }
12335
12336                         bool error = false;
12337                         arguments = new Arguments (parameters.Count);
12338                         var t_args = new TypeSpec [parameters.Count];
12339                         for (int i = 0; i < parameters.Count; ++i) {
12340                                 Expression e = parameters [i].Resolve (ec);
12341                                 if (e == null) {
12342                                         error = true;
12343                                         continue;
12344                                 }
12345
12346                                 arguments.Add (new Argument (e));
12347                                 t_args [i] = e.Type;
12348                         }
12349
12350                         if (error)
12351                                 return null;
12352
12353                         anonymous_type = CreateAnonymousType (ec, parameters);
12354                         if (anonymous_type == null)
12355                                 return null;
12356
12357                         type = anonymous_type.Definition.MakeGenericType (ec.Module, t_args);
12358                         method = (MethodSpec) MemberCache.FindMember (type, MemberFilter.Constructor (null), BindingRestriction.DeclaredOnly);
12359                         eclass = ExprClass.Value;
12360                         return this;
12361                 }
12362                 
12363                 public override object Accept (StructuralVisitor visitor)
12364                 {
12365                         return visitor.Visit (this);
12366                 }
12367         }
12368
12369         public class AnonymousTypeParameter : ShimExpression
12370         {
12371                 public readonly string Name;
12372
12373                 public AnonymousTypeParameter (Expression initializer, string name, Location loc)
12374                         : base (initializer)
12375                 {
12376                         this.Name = name;
12377                         this.loc = loc;
12378                 }
12379                 
12380                 public AnonymousTypeParameter (Parameter parameter)
12381                         : base (new SimpleName (parameter.Name, parameter.Location))
12382                 {
12383                         this.Name = parameter.Name;
12384                         this.loc = parameter.Location;
12385                 }               
12386
12387                 public override bool Equals (object o)
12388                 {
12389                         AnonymousTypeParameter other = o as AnonymousTypeParameter;
12390                         return other != null && Name == other.Name;
12391                 }
12392
12393                 public override int GetHashCode ()
12394                 {
12395                         return Name.GetHashCode ();
12396                 }
12397
12398                 protected override Expression DoResolve (ResolveContext ec)
12399                 {
12400                         Expression e = expr.Resolve (ec);
12401                         if (e == null)
12402                                 return null;
12403
12404                         if (e.eclass == ExprClass.MethodGroup) {
12405                                 Error_InvalidInitializer (ec, e.ExprClassName);
12406                                 return null;
12407                         }
12408
12409                         type = e.Type;
12410                         if (type.Kind == MemberKind.Void || type == InternalType.NullLiteral || type == InternalType.AnonymousMethod || type.IsPointer) {
12411                                 Error_InvalidInitializer (ec, type.GetSignatureForError ());
12412                                 return null;
12413                         }
12414
12415                         return e;
12416                 }
12417
12418                 protected virtual void Error_InvalidInitializer (ResolveContext ec, string initializer)
12419                 {
12420                         ec.Report.Error (828, loc, "An anonymous type property `{0}' cannot be initialized with `{1}'",
12421                                 Name, initializer);
12422                 }
12423         }
12424
12425         public class CatchFilterExpression : BooleanExpression
12426         {
12427                 public CatchFilterExpression (Expression expr, Location loc)
12428                         : base (expr)
12429                 {
12430                         this.loc = loc;
12431                 }
12432         }
12433
12434         public class InterpolatedString : Expression
12435         {
12436                 readonly StringLiteral start, end;
12437                 List<Expression> interpolations;
12438                 Arguments arguments;
12439
12440                 public InterpolatedString (StringLiteral start, List<Expression> interpolations, StringLiteral end)
12441                 {
12442                         this.start = start;
12443                         this.end = end;
12444                         this.interpolations = interpolations;
12445                         loc = start.Location;
12446                 }
12447
12448                 protected override void CloneTo (CloneContext clonectx, Expression t)
12449                 {
12450                         InterpolatedString target = (InterpolatedString) t;
12451
12452                         if (interpolations != null) {
12453                                 target.interpolations = new List<Expression> ();
12454                                 foreach (var interpolation in interpolations) {
12455                                         target.interpolations.Add (interpolation.Clone (clonectx));
12456                                 }
12457                         }
12458                 }
12459
12460                 public Expression ConvertTo (ResolveContext rc, TypeSpec type)
12461                 {
12462                         var factory = rc.Module.PredefinedTypes.FormattableStringFactory.Resolve ();
12463                         if (factory == null)
12464                                 return null;
12465
12466                         var ma = new MemberAccess (new TypeExpression (factory, loc), "Create", loc);
12467                         var res = new Invocation (ma, arguments).Resolve (rc);
12468                         if (res != null && res.Type != type)
12469                                 res = Convert.ExplicitConversion (rc, res, type, loc);
12470
12471                         return res;
12472                 }
12473
12474                 public override bool ContainsEmitWithAwait ()
12475                 {
12476                         if (interpolations == null)
12477                                 return false;
12478
12479                         foreach (var expr in interpolations) {
12480                                 if (expr.ContainsEmitWithAwait ())
12481                                         return true;
12482                         }
12483
12484                         return false;
12485                 }
12486
12487                 public override Expression CreateExpressionTree (ResolveContext rc)
12488                 {
12489                         var best = ResolveBestFormatOverload (rc);
12490                         if (best == null)
12491                                 return null;
12492                         
12493                         Expression instance = new NullLiteral (loc);
12494                         var args = Arguments.CreateForExpressionTree (rc, arguments, instance, new TypeOfMethod (best, loc));
12495                         return CreateExpressionFactoryCall (rc, "Call", args);  
12496                 }
12497
12498                 protected override Expression DoResolve (ResolveContext rc)
12499                 {
12500                         string str;
12501
12502                         if (interpolations == null) {
12503                                 str = start.Value;
12504                                 arguments = new Arguments (1);
12505                         } else {
12506                                 for (int i = 0; i < interpolations.Count; i += 2) {
12507                                         var ipi = (InterpolatedStringInsert)interpolations [i];
12508                                         ipi.Resolve (rc);
12509                                 }
12510         
12511                                 arguments = new Arguments (interpolations.Count);
12512
12513                                 var sb = new StringBuilder (start.Value);
12514                                 for (int i = 0; i < interpolations.Count; ++i) {
12515                                         if (i % 2 == 0) {
12516                                                 sb.Append ('{').Append (i / 2);
12517                                                 var isi = (InterpolatedStringInsert)interpolations [i];
12518                                                 if (isi.Alignment != null) {
12519                                                         sb.Append (',');
12520                                                         var value = isi.ResolveAligment (rc);
12521                                                         if (value != null)
12522                                                                 sb.Append (value.Value);
12523                                                 }
12524
12525                                                 if (isi.Format != null) {
12526                                                         sb.Append (':');
12527                                                         sb.Append (isi.Format);
12528                                                 }
12529
12530                                                 sb.Append ('}');
12531                                                 arguments.Add (new Argument (interpolations [i]));
12532                                         } else {
12533                                                 sb.Append (((StringLiteral)interpolations [i]).Value);
12534                                         }
12535                                 }
12536
12537                                 sb.Append (end.Value);
12538                                 str = sb.ToString ();
12539                         }
12540
12541                         arguments.Insert (0, new Argument (new StringLiteral (rc.BuiltinTypes, str, start.Location)));
12542
12543                         eclass = ExprClass.Value;
12544                         type = rc.BuiltinTypes.String;
12545                         return this;
12546                 }
12547
12548                 public override void Emit (EmitContext ec)
12549                 {
12550                         // No interpolation, convert to simple string result (needs to match string.Format unescaping)
12551                         if (interpolations == null) {
12552                                 var str = start.Value.Replace ("{{", "{").Replace ("}}", "}");
12553                                 if (str != start.Value)
12554                                         new StringConstant (ec.BuiltinTypes, str, loc).Emit (ec);
12555                                 else
12556                                         start.Emit (ec);
12557
12558                                 return;
12559                         }
12560
12561                         var best = ResolveBestFormatOverload (new ResolveContext (ec.MemberContext));
12562                         if (best == null)
12563                                 return;
12564
12565                         var ca = new CallEmitter ();
12566                         ca.Emit (ec, best, arguments, loc);
12567                 }
12568
12569                 public override void FlowAnalysis (FlowAnalysisContext fc)
12570                 {
12571                         if (interpolations != null) {
12572                                 foreach (var expr in interpolations) {
12573                                         expr.FlowAnalysis (fc);
12574                                 }
12575                         }
12576                 }
12577
12578                 MethodSpec ResolveBestFormatOverload (ResolveContext rc)
12579                 {
12580                         var members = MemberCache.FindMembers (rc.BuiltinTypes.String, "Format", true);
12581                         var res = new OverloadResolver (members, OverloadResolver.Restrictions.NoBaseMembers, loc);
12582                         return res.ResolveMember<MethodSpec> (rc, ref arguments);
12583                 }
12584         }
12585
12586         public class InterpolatedStringInsert : CompositeExpression
12587         {
12588                 public InterpolatedStringInsert (Expression expr)
12589                         : base (expr)
12590                 {
12591                 }
12592
12593                 public Expression Alignment { get; set; }
12594                 public string Format { get; set; }
12595
12596                 protected override void CloneTo (CloneContext clonectx, Expression t)
12597                 {
12598                         var target = (InterpolatedStringInsert)t;
12599                         target.expr = expr.Clone (clonectx);
12600                         if (Alignment != null)
12601                                 target.Alignment = Alignment.Clone (clonectx);
12602                 }
12603
12604                 protected override Expression DoResolve (ResolveContext rc)
12605                 {
12606                         var expr = base.DoResolve (rc);
12607                         if (expr == null)
12608                                 return null;
12609
12610                         //
12611                         // For better error reporting, assumes the built-in implementation uses object
12612                         // as argument(s)
12613                         //
12614                         return Convert.ImplicitConversionRequired (rc, expr, rc.BuiltinTypes.Object, expr.Location);
12615                 }
12616
12617                 public override void FlowAnalysis (FlowAnalysisContext fc)
12618                 {
12619                         Child.FlowAnalysis (fc);
12620                 }
12621
12622                 public int? ResolveAligment (ResolveContext rc)
12623                 {
12624                         var c = Alignment.ResolveLabelConstant (rc);
12625                         if (c == null)
12626                                 return null;
12627                         
12628                         c = c.ImplicitConversionRequired (rc, rc.BuiltinTypes.Int);
12629                         if (c == null)
12630                                 return null;
12631                         
12632                         var value = (int) c.GetValueAsLong ();
12633                         if (value > 32767 || value < -32767) {
12634                                 rc.Report.Warning (8094, 1, Alignment.Location, 
12635                                         "Alignment value has a magnitude greater than 32767 and may result in a large formatted string");
12636                         }
12637
12638                         return value;
12639                 }
12640         }
12641 }