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