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