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