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