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