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