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