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