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