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