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