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