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