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