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