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