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