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