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