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