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