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