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