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