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