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