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