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