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