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