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