2001-11-22 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 Ximian, Inc.
8 //
9 //
10
11 namespace Mono.CSharp {
12         using System;
13         using System.Collections;
14         using System.Diagnostics;
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                 StaticCallExpr (MethodInfo m, ArrayList a)
29                 {
30                         mi = m;
31                         args = a;
32
33                         type = m.ReturnType;
34                         eclass = ExprClass.Value;
35                 }
36
37                 public override Expression DoResolve (EmitContext ec)
38                 {
39                         //
40                         // We are born fully resolved
41                         //
42                         return this;
43                 }
44
45                 public override void Emit (EmitContext ec)
46                 {
47                         if (args != null) 
48                                 Invocation.EmitArguments (ec, mi, args);
49
50                         ec.ig.Emit (OpCodes.Call, mi);
51                         return;
52                 }
53                 
54                 static public Expression MakeSimpleCall (EmitContext ec, MethodGroupExpr mg,
55                                                          Expression e, Location loc)
56                 {
57                         ArrayList args;
58                         MethodBase method;
59                         
60                         args = new ArrayList (1);
61                         args.Add (new Argument (e, Argument.AType.Expression));
62                         method = Invocation.OverloadResolve (ec, (MethodGroupExpr) mg, args, loc);
63
64                         if (method == null)
65                                 return null;
66
67                         return new StaticCallExpr ((MethodInfo) method, args);
68                 }
69
70                 public override void EmitStatement (EmitContext ec)
71                 {
72                         Emit (ec);
73                         if (type != TypeManager.void_type)
74                                 ec.ig.Emit (OpCodes.Pop);
75                 }
76         }
77         
78         /// <summary>
79         ///   Unary expressions.  
80         /// </summary>
81         ///
82         /// <remarks>
83         ///   Unary implements unary expressions.   It derives from
84         ///   ExpressionStatement becuase the pre/post increment/decrement
85         ///   operators can be used in a statement context.
86         /// </remarks>
87         public class Unary : Expression {
88                 public enum Operator : byte {
89                         UnaryPlus, UnaryNegation, LogicalNot, OnesComplement,
90                         Indirection, AddressOf, 
91                 }
92
93                 Operator   oper;
94                 Expression expr;
95                 Location   loc;
96                 
97                 public Unary (Operator op, Expression expr, Location loc)
98                 {
99                         this.oper = op;
100                         this.expr = expr;
101                         this.loc = loc;
102                 }
103
104                 public Expression Expr {
105                         get {
106                                 return expr;
107                         }
108
109                         set {
110                                 expr = value;
111                         }
112                 }
113
114                 public Operator Oper {
115                         get {
116                                 return oper;
117                         }
118
119                         set {
120                                 oper = value;
121                         }
122                 }
123
124                 /// <summary>
125                 ///   Returns a stringified representation of the Operator
126                 /// </summary>
127                 string OperName ()
128                 {
129                         switch (oper){
130                         case Operator.UnaryPlus:
131                                 return "+";
132                         case Operator.UnaryNegation:
133                                 return "-";
134                         case Operator.LogicalNot:
135                                 return "!";
136                         case Operator.OnesComplement:
137                                 return "~";
138                         case Operator.AddressOf:
139                                 return "&";
140                         case Operator.Indirection:
141                                 return "*";
142                         }
143
144                         return oper.ToString ();
145                 }
146
147                 void error23 (Type t)
148                 {
149                         Report.Error (
150                                 23, loc, "Operator " + OperName () +
151                                 " cannot be applied to operand of type `" +
152                                 TypeManager.CSharpName (t) + "'");
153                 }
154
155                 static Expression TryReduceNegative (Expression expr)
156                 {
157                         Expression e = null;
158                         
159                         if (expr is IntLiteral)
160                                 e = new IntLiteral (-((IntLiteral) expr).Value);
161                         else if (expr is UIntLiteral)
162                                 e = new LongLiteral (-((UIntLiteral) expr).Value);
163                         else if (expr is LongLiteral)
164                                 e = new LongLiteral (-((LongLiteral) expr).Value);
165                         else if (expr is FloatLiteral)
166                                 e = new FloatLiteral (-((FloatLiteral) expr).Value);
167                         else if (expr is DoubleLiteral)
168                                 e = new DoubleLiteral (-((DoubleLiteral) expr).Value);
169                         else if (expr is DecimalLiteral)
170                                 e = new DecimalLiteral (-((DecimalLiteral) expr).Value);
171
172                         return e;
173                 }
174                 
175                 Expression ResolveOperator (EmitContext ec)
176                 {
177                         Type expr_type = expr.Type;
178
179                         //
180                         // Step 1: Perform Operator Overload location
181                         //
182                         Expression mg;
183                         string op_name;
184                         
185                         op_name = "op_" + oper;
186
187                         mg = MemberLookup (ec, expr_type, op_name, false, loc);
188                         
189                         if (mg == null && expr_type.BaseType != null)
190                                 mg = MemberLookup (ec, expr_type.BaseType, op_name, false, loc);
191                         
192                         if (mg != null) {
193                                 Expression e = StaticCallExpr.MakeSimpleCall (
194                                         ec, (MethodGroupExpr) mg, expr, loc);
195
196                                 if (e == null){
197                                         error23 (expr_type);
198                                         return null;
199                                 }
200                                 
201                                 return e;
202                         }
203
204                         //
205                         // Step 2: Default operations on CLI native types.
206                         //
207
208                         // Only perform numeric promotions on:
209                         // +, - 
210
211                         if (expr_type == null)
212                                 return null;
213                         
214                         if (oper == Operator.LogicalNot){
215                                 if (expr_type != TypeManager.bool_type) {
216                                         error23 (expr.Type);
217                                         return null;
218                                 }
219                                 
220                                 type = TypeManager.bool_type;
221                                 return this;
222                         }
223
224                         if (oper == Operator.OnesComplement) {
225                                 if (!((expr_type == TypeManager.int32_type) ||
226                                       (expr_type == TypeManager.uint32_type) ||
227                                       (expr_type == TypeManager.int64_type) ||
228                                       (expr_type == TypeManager.uint64_type) ||
229                                       (expr_type.IsSubclassOf (TypeManager.enum_type)))){
230                                         error23 (expr.Type);
231                                         return null;
232                                 }
233                                 type = expr_type;
234                                 return this;
235                         }
236
237                         if (oper == Operator.UnaryPlus) {
238                                 //
239                                 // A plus in front of something is just a no-op, so return the child.
240                                 //
241                                 return expr;
242                         }
243
244                         //
245                         // Deals with -literals
246                         // int     operator- (int x)
247                         // long    operator- (long x)
248                         // float   operator- (float f)
249                         // double  operator- (double d)
250                         // decimal operator- (decimal d)
251                         //
252                         if (oper == Operator.UnaryNegation){
253                                 //
254                                 // Fold a "- Constant" into a negative constant
255                                 //
256                         
257                                 Expression e = null;
258
259                                 //
260                                 // Is this a constant? 
261                                 //
262                                 e = TryReduceNegative (expr);
263                                 
264                                 if (e != null){
265                                         e = e.Resolve (ec);
266                                         return e;
267                                 }
268
269                                 //
270                                 // Not a constant we can optimize, perform numeric 
271                                 // promotions to int, long, double.
272                                 //
273                                 //
274                                 // The following is inneficient, because we call
275                                 // ConvertImplicit too many times.
276                                 //
277                                 // It is also not clear if we should convert to Float
278                                 // or Double initially.
279                                 //
280                                 if (expr_type == TypeManager.uint32_type){
281                                         //
282                                         // FIXME: handle exception to this rule that
283                                         // permits the int value -2147483648 (-2^31) to
284                                         // bt written as a decimal interger literal
285                                         //
286                                         type = TypeManager.int64_type;
287                                         expr = ConvertImplicit (ec, expr, type, loc);
288                                         return this;
289                                 }
290
291                                 if (expr_type == TypeManager.uint64_type){
292                                         //
293                                         // FIXME: Handle exception of `long value'
294                                         // -92233720368547758087 (-2^63) to be written as
295                                         // decimal integer literal.
296                                         //
297                                         error23 (expr_type);
298                                         return null;
299                                 }
300
301                                 e = ConvertImplicit (ec, expr, TypeManager.int32_type, loc);
302                                 if (e != null){
303                                         expr = e;
304                                         type = e.Type;
305                                         return this;
306                                 } 
307
308                                 e = ConvertImplicit (ec, expr, TypeManager.int64_type, loc);
309                                 if (e != null){
310                                         expr = e;
311                                         type = e.Type;
312                                         return this;
313                                 }
314
315                                 e = ConvertImplicit (ec, expr, TypeManager.double_type, loc);
316                                 if (e != null){
317                                         expr = e;
318                                         type = e.Type;
319                                         return this;
320                                 }
321
322                                 error23 (expr_type);
323                                 return null;
324                         }
325
326                         if (oper == Operator.AddressOf){
327                                 if (expr.ExprClass != ExprClass.Variable){
328                                         Error (211, loc, "Cannot take the address of non-variables");
329                                         return null;
330                                 }
331                                 type = Type.GetType (expr.Type.ToString () + "*");
332
333                                 return this;
334                         }
335                         
336                         Error (187, loc, "No such operator '" + OperName () + "' defined for type '" +
337                                TypeManager.CSharpName (expr_type) + "'");
338                         return null;
339                 }
340
341                 public override Expression DoResolve (EmitContext ec)
342                 {
343                         expr = expr.Resolve (ec);
344                         
345                         if (expr == null)
346                                 return null;
347
348                         eclass = ExprClass.Value;
349                         return ResolveOperator (ec);
350                 }
351
352                 public override void Emit (EmitContext ec)
353                 {
354                         ILGenerator ig = ec.ig;
355                         Type expr_type = expr.Type;
356                         
357                         switch (oper) {
358                         case Operator.UnaryPlus:
359                                 throw new Exception ("This should be caught by Resolve");
360                                 
361                         case Operator.UnaryNegation:
362                                 expr.Emit (ec);
363                                 ig.Emit (OpCodes.Neg);
364                                 break;
365                                 
366                         case Operator.LogicalNot:
367                                 expr.Emit (ec);
368                                 ig.Emit (OpCodes.Ldc_I4_0);
369                                 ig.Emit (OpCodes.Ceq);
370                                 break;
371                                 
372                         case Operator.OnesComplement:
373                                 expr.Emit (ec);
374                                 ig.Emit (OpCodes.Not);
375                                 break;
376                                 
377                         case Operator.AddressOf:
378                                 ((IMemoryLocation)expr).AddressOf (ec);
379                                 break;
380                                 
381                         case Operator.Indirection:
382                                 throw new Exception ("Not implemented yet");
383                                 
384                         default:
385                                 throw new Exception ("This should not happen: Operator = "
386                                                      + oper.ToString ());
387                         }
388                 }
389
390                 /// <summary>
391                 ///   This will emit the child expression for `ec' avoiding the logical
392                 ///   not.  The parent will take care of changing brfalse/brtrue
393                 /// </summary>
394                 public void EmitLogicalNot (EmitContext ec)
395                 {
396                         if (oper != Operator.LogicalNot)
397                                 throw new Exception ("EmitLogicalNot can only be called with !expr");
398
399                         expr.Emit (ec);
400                 }
401                 
402                 public override Expression Reduce (EmitContext ec)
403                 {
404                         Expression e;
405                         
406                         //
407                         // First, reduce our child.  Note that although we handle 
408                         //
409                         expr = expr.Reduce (ec);
410                         if (!(expr is Literal))
411                                 return expr;
412                         
413                         switch (oper){
414                         case Operator.UnaryPlus:
415                                 return expr;
416                                 
417                         case Operator.UnaryNegation:
418                                 e = TryReduceNegative (expr);
419                                 if (e == null)
420                                         break;
421                                 return e;
422                                 
423                         case Operator.LogicalNot:
424                                 BoolLiteral b = (BoolLiteral) expr;
425
426                                 return new BoolLiteral (!(b.Value));
427                                 
428                         case Operator.OnesComplement:
429                                 Type et = expr.Type;
430                                 
431                                 if (et == TypeManager.int32_type)
432                                         return new IntLiteral (~ ((IntLiteral) expr).Value);
433                                 if (et == TypeManager.uint32_type)
434                                         return new UIntLiteral (~ ((UIntLiteral) expr).Value);
435                                 if (et == TypeManager.int64_type)
436                                         return new LongLiteral (~ ((LongLiteral) expr).Value);
437                                 if (et == TypeManager.uint64_type)
438                                         return new ULongLiteral (~ ((ULongLiteral) expr).Value);
439                                 break;
440                         }
441                         return this;
442                 }
443         }
444
445         /// <summary>
446         ///   Unary Mutator expressions (pre and post ++ and --)
447         /// </summary>
448         ///
449         /// <remarks>
450         ///   UnaryMutator implements ++ and -- expressions.   It derives from
451         ///   ExpressionStatement becuase the pre/post increment/decrement
452         ///   operators can be used in a statement context.
453         ///
454         /// FIXME: Idea, we could split this up in two classes, one simpler
455         /// for the common case, and one with the extra fields for more complex
456         /// classes (indexers require temporary access;  overloaded require method)
457         ///
458         /// Maybe we should have classes PreIncrement, PostIncrement, PreDecrement,
459         /// PostDecrement, that way we could save the `Mode' byte as well.  
460         /// </remarks>
461         public class UnaryMutator : ExpressionStatement {
462                 public enum Mode : byte {
463                         PreIncrement, PreDecrement, PostIncrement, PostDecrement
464                 }
465                 
466                 Mode mode;
467                 Location loc;
468                 Expression expr;
469                 LocalTemporary temp_storage;
470
471                 //
472                 // This is expensive for the simplest case.
473                 //
474                 Expression method;
475                         
476                 public UnaryMutator (Mode m, Expression e, Location l)
477                 {
478                         mode = m;
479                         loc = l;
480                         expr = e;
481                 }
482
483                 string OperName ()
484                 {
485                         return (mode == Mode.PreIncrement || mode == Mode.PostIncrement) ?
486                                 "++" : "--";
487                 }
488                 
489                 void error23 (Type t)
490                 {
491                         Report.Error (
492                                 23, loc, "Operator " + OperName () + 
493                                 " cannot be applied to operand of type `" +
494                                 TypeManager.CSharpName (t) + "'");
495                 }
496
497                 /// <summary>
498                 ///   Returns whether an object of type `t' can be incremented
499                 ///   or decremented with add/sub (ie, basically whether we can
500                 ///   use pre-post incr-decr operations on it, but it is not a
501                 ///   System.Decimal, which we require operator overloading to catch)
502                 /// </summary>
503                 static bool IsIncrementableNumber (Type t)
504                 {
505                         return (t == TypeManager.sbyte_type) ||
506                                 (t == TypeManager.byte_type) ||
507                                 (t == TypeManager.short_type) ||
508                                 (t == TypeManager.ushort_type) ||
509                                 (t == TypeManager.int32_type) ||
510                                 (t == TypeManager.uint32_type) ||
511                                 (t == TypeManager.int64_type) ||
512                                 (t == TypeManager.uint64_type) ||
513                                 (t == TypeManager.char_type) ||
514                                 (t.IsSubclassOf (TypeManager.enum_type)) ||
515                                 (t == TypeManager.float_type) ||
516                                 (t == TypeManager.double_type);
517                 }
518
519                 Expression ResolveOperator (EmitContext ec)
520                 {
521                         Type expr_type = expr.Type;
522
523                         //
524                         // Step 1: Perform Operator Overload location
525                         //
526                         Expression mg;
527                         string op_name;
528                         
529                         if (mode == Mode.PreIncrement || mode == Mode.PostIncrement)
530                                 op_name = "op_Increment";
531                         else 
532                                 op_name = "op_Decrement";
533
534                         mg = MemberLookup (ec, expr_type, op_name, false, loc);
535
536                         if (mg == null && expr_type.BaseType != null)
537                                 mg = MemberLookup (ec, expr_type.BaseType, op_name, false, loc);
538                         
539                         if (mg != null) {
540                                 method = StaticCallExpr.MakeSimpleCall (
541                                         ec, (MethodGroupExpr) mg, expr, loc);
542
543                                 type = method.Type;
544                                 return this;
545                         }
546
547                         //
548                         // The operand of the prefix/postfix increment decrement operators
549                         // should be an expression that is classified as a variable,
550                         // a property access or an indexer access
551                         //
552                         type = expr_type;
553                         if (expr.ExprClass == ExprClass.Variable){
554                                 if (IsIncrementableNumber (expr_type) ||
555                                     expr_type == TypeManager.decimal_type){
556                                         return this;
557                                 }
558                         } else if (expr.ExprClass == ExprClass.IndexerAccess){
559                                 IndexerAccess ia = (IndexerAccess) expr;
560                                 
561                                 temp_storage = new LocalTemporary (ec, expr.Type);
562                                 
563                                 expr = ia.ResolveLValue (ec, temp_storage);
564                                 if (expr == null)
565                                         return null;
566
567                                 return this;
568                         } else if (expr.ExprClass == ExprClass.PropertyAccess){
569                                 PropertyExpr pe = (PropertyExpr) expr;
570
571                                 if (pe.VerifyAssignable ())
572                                         return this;
573
574                                 return null;
575                         } else {
576                                 report118 (loc, expr, "variable, indexer or property access");
577                                 return null;
578                         }
579
580                         Error (187, loc, "No such operator '" + OperName () + "' defined for type '" +
581                                TypeManager.CSharpName (expr_type) + "'");
582                         return null;
583                 }
584
585                 public override Expression DoResolve (EmitContext ec)
586                 {
587                         expr = expr.Resolve (ec);
588                         
589                         if (expr == null)
590                                 return null;
591
592                         eclass = ExprClass.Value;
593                         return ResolveOperator (ec);
594                 }
595                 
596
597                 //
598                 // FIXME: We need some way of avoiding the use of temp_storage
599                 // for some types of storage (parameters, local variables,
600                 // static fields) and single-dimension array access.
601                 //
602                 void EmitCode (EmitContext ec, bool is_expr)
603                 {
604                         ILGenerator ig = ec.ig;
605                         IAssignMethod ia = (IAssignMethod) expr;
606
607                         if (temp_storage == null)
608                                 temp_storage = new LocalTemporary (ec, expr.Type);
609                         
610                         switch (mode){
611                         case Mode.PreIncrement:
612                         case Mode.PreDecrement:
613                                 if (method == null){
614                                         expr.Emit (ec);
615
616                                         ig.Emit (OpCodes.Ldc_I4_1);
617                                 
618                                         if (mode == Mode.PreDecrement)
619                                                 ig.Emit (OpCodes.Sub);
620                                         else
621                                                 ig.Emit (OpCodes.Add);
622                                 } else
623                                         method.Emit (ec);
624                                 
625                                 temp_storage.Store (ec);
626                                 ia.EmitAssign (ec, temp_storage);
627                                 if (is_expr)
628                                         temp_storage.Emit (ec);
629                                 break;
630                                 
631                         case Mode.PostIncrement:
632                         case Mode.PostDecrement:
633                                 if (is_expr)
634                                         expr.Emit (ec);
635                                 
636                                 if (method == null){
637                                         if (!is_expr)
638                                                 expr.Emit (ec);
639                                         else
640                                                 ig.Emit (OpCodes.Dup);
641
642                                         ig.Emit (OpCodes.Ldc_I4_1);
643                                 
644                                         if (mode == Mode.PostDecrement)
645                                                 ig.Emit (OpCodes.Sub);
646                                         else
647                                                 ig.Emit (OpCodes.Add);
648                                 } else {
649                                         method.Emit (ec);
650                                 }
651                                 
652                                 temp_storage.Store (ec);
653                                 ia.EmitAssign (ec, temp_storage);
654                                 break;
655                         }
656                 }
657
658                 public override void Emit (EmitContext ec)
659                 {
660                         EmitCode (ec, true);
661                         
662                 }
663                 
664                 public override void EmitStatement (EmitContext ec)
665                 {
666                         EmitCode (ec, false);
667                 }
668
669         }
670
671         /// <summary>
672         ///   Implements the `is' and `as' tests.
673         /// </summary>
674         ///
675         /// <remarks>
676         ///   FIXME: Split this in two, and we get to save the `Operator' Oper
677         ///   size. 
678         /// </remarks>
679         public class Probe : Expression {
680                 public readonly string ProbeType;
681                 public readonly Operator Oper;
682                 Expression expr;
683                 Type probe_type;
684                 
685                 public enum Operator : byte {
686                         Is, As
687                 }
688                 
689                 public Probe (Operator oper, Expression expr, string probe_type)
690                 {
691                         Oper = oper;
692                         ProbeType = probe_type;
693                         this.expr = expr;
694                 }
695
696                 public Expression Expr {
697                         get {
698                                 return expr;
699                         }
700                 }
701                 
702                 public override Expression DoResolve (EmitContext ec)
703                 {
704                         probe_type = ec.TypeContainer.LookupType (ProbeType, false);
705
706                         if (probe_type == null)
707                                 return null;
708
709                         expr = expr.Resolve (ec);
710                         
711                         type = TypeManager.bool_type;
712                         eclass = ExprClass.Value;
713
714                         return this;
715                 }
716
717                 public override void Emit (EmitContext ec)
718                 {
719                         ILGenerator ig = ec.ig;
720                         
721                         expr.Emit (ec);
722                         
723                         if (Oper == Operator.Is){
724                                 ig.Emit (OpCodes.Isinst, probe_type);
725                                 ig.Emit (OpCodes.Ldnull);
726                                 ig.Emit (OpCodes.Cgt_Un);
727                         } else {
728                                 ig.Emit (OpCodes.Isinst, probe_type);
729                         }
730                 }
731         }
732
733         /// <summary>
734         ///   This represents a typecast in the source language.
735         ///
736         ///   FIXME: Cast expressions have an unusual set of parsing
737         ///   rules, we need to figure those out.
738         /// </summary>
739         public class Cast : Expression {
740                 string target_type;
741                 Expression expr;
742                 Location   loc;
743                         
744                 public Cast (string cast_type, Expression expr, Location loc)
745                 {
746                         this.target_type = cast_type;
747                         this.expr = expr;
748                         this.loc = loc;
749                 }
750
751                 public string TargetType {
752                         get {
753                                 return target_type;
754                         }
755                 }
756
757                 public Expression Expr {
758                         get {
759                                 return expr;
760                         }
761                         set {
762                                 expr = value;
763                         }
764                 }
765                 
766                 public override Expression DoResolve (EmitContext ec)
767                 {
768                         expr = expr.Resolve (ec);
769                         if (expr == null)
770                                 return null;
771                         
772                         type = ec.TypeContainer.LookupType (target_type, false);
773                         eclass = ExprClass.Value;
774                         
775                         if (type == null)
776                                 return null;
777
778                         expr = ConvertExplicit (ec, expr, type, loc);
779                         return expr;
780                 }
781
782                 public override void Emit (EmitContext ec)
783                 {
784                         //
785                         // This one will never happen
786                         //
787                         throw new Exception ("Should not happen");
788                 }
789         }
790
791         /// <summary>
792         ///   Binary operators
793         /// </summary>
794         public class Binary : Expression {
795                 public enum Operator : byte {
796                         Multiply, Division, Modulus,
797                         Addition, Subtraction,
798                         LeftShift, RightShift,
799                         LessThan, GreaterThan, LessThanOrEqual, GreaterThanOrEqual, 
800                         Equality, Inequality,
801                         BitwiseAnd,
802                         ExclusiveOr,
803                         BitwiseOr,
804                         LogicalAnd,
805                         LogicalOr
806                 }
807
808                 Operator oper;
809                 Expression left, right;
810                 MethodBase method;
811                 ArrayList  Arguments;
812                 Location   loc;
813                 
814
815                 public Binary (Operator oper, Expression left, Expression right, Location loc)
816                 {
817                         this.oper = oper;
818                         this.left = left;
819                         this.right = right;
820                         this.loc = loc;
821                 }
822
823                 public Operator Oper {
824                         get {
825                                 return oper;
826                         }
827                         set {
828                                 oper = value;
829                         }
830                 }
831                 
832                 public Expression Left {
833                         get {
834                                 return left;
835                         }
836                         set {
837                                 left = value;
838                         }
839                 }
840
841                 public Expression Right {
842                         get {
843                                 return right;
844                         }
845                         set {
846                                 right = value;
847                         }
848                 }
849
850
851                 /// <summary>
852                 ///   Returns a stringified representation of the Operator
853                 /// </summary>
854                 string OperName ()
855                 {
856                         switch (oper){
857                         case Operator.Multiply:
858                                 return "*";
859                         case Operator.Division:
860                                 return "/";
861                         case Operator.Modulus:
862                                 return "%";
863                         case Operator.Addition:
864                                 return "+";
865                         case Operator.Subtraction:
866                                 return "-";
867                         case Operator.LeftShift:
868                                 return "<<";
869                         case Operator.RightShift:
870                                 return ">>";
871                         case Operator.LessThan:
872                                 return "<";
873                         case Operator.GreaterThan:
874                                 return ">";
875                         case Operator.LessThanOrEqual:
876                                 return "<=";
877                         case Operator.GreaterThanOrEqual:
878                                 return ">=";
879                         case Operator.Equality:
880                                 return "==";
881                         case Operator.Inequality:
882                                 return "!=";
883                         case Operator.BitwiseAnd:
884                                 return "&";
885                         case Operator.BitwiseOr:
886                                 return "|";
887                         case Operator.ExclusiveOr:
888                                 return "^";
889                         case Operator.LogicalOr:
890                                 return "||";
891                         case Operator.LogicalAnd:
892                                 return "&&";
893                         }
894
895                         return oper.ToString ();
896                 }
897
898                 Expression ForceConversion (EmitContext ec, Expression expr, Type target_type)
899                 {
900                         if (expr.Type == target_type)
901                                 return expr;
902
903                         return ConvertImplicit (ec, expr, target_type, new Location (-1));
904                 }
905                 
906                 //
907                 // Note that handling the case l == Decimal || r == Decimal
908                 // is taken care of by the Step 1 Operator Overload resolution.
909                 //
910                 bool DoNumericPromotions (EmitContext ec, Type l, Type r)
911                 {
912                         if (l == TypeManager.double_type || r == TypeManager.double_type){
913                                 //
914                                 // If either operand is of type double, the other operand is
915                                 // conveted to type double.
916                                 //
917                                 if (r != TypeManager.double_type)
918                                         right = ConvertImplicit (ec, right, TypeManager.double_type, loc);
919                                 if (l != TypeManager.double_type)
920                                         left = ConvertImplicit (ec, left, TypeManager.double_type, loc);
921                                 
922                                 type = TypeManager.double_type;
923                         } else if (l == TypeManager.float_type || r == TypeManager.float_type){
924                                 //
925                                 // if either operand is of type float, th eother operand is
926                                 // converd to type float.
927                                 //
928                                 if (r != TypeManager.double_type)
929                                         right = ConvertImplicit (ec, right, TypeManager.float_type, loc);
930                                 if (l != TypeManager.double_type)
931                                         left = ConvertImplicit (ec, left, TypeManager.float_type, loc);
932                                 type = TypeManager.float_type;
933                         } else if (l == TypeManager.uint64_type || r == TypeManager.uint64_type){
934                                 Expression e;
935                                 Type other;
936                                 //
937                                 // If either operand is of type ulong, the other operand is
938                                 // converted to type ulong.  or an error ocurrs if the other
939                                 // operand is of type sbyte, short, int or long
940                                 //
941                                 
942                                 if (l == TypeManager.uint64_type){
943                                         if (r != TypeManager.uint64_type && right is IntLiteral){
944                                                 e = TryImplicitIntConversion (l, (IntLiteral) right);
945                                                 if (e != null)
946                                                         right = e;
947                                         }
948                                         other = right.Type;
949                                 } else {
950                                         if (left is IntLiteral){
951                                                 e = TryImplicitIntConversion (r, (IntLiteral) left);
952                                                 if (e != null)
953                                                         left = e;
954                                         }
955                                         other = left.Type;
956                                 }
957
958                                 if ((other == TypeManager.sbyte_type) ||
959                                     (other == TypeManager.short_type) ||
960                                     (other == TypeManager.int32_type) ||
961                                     (other == TypeManager.int64_type)){
962                                         string oper = OperName ();
963                                         
964                                         Error (34, loc, "Operator `" + OperName ()
965                                                + "' is ambiguous on operands of type `"
966                                                + TypeManager.CSharpName (l) + "' "
967                                                + "and `" + TypeManager.CSharpName (r)
968                                                + "'");
969                                 }
970                                 type = TypeManager.uint64_type;
971                         } else if (l == TypeManager.int64_type || r == TypeManager.int64_type){
972                                 //
973                                 // If either operand is of type long, the other operand is converted
974                                 // to type long.
975                                 //
976                                 if (l != TypeManager.int64_type)
977                                         left = ConvertImplicit (ec, left, TypeManager.int64_type, loc);
978                                 if (r != TypeManager.int64_type)
979                                         right = ConvertImplicit (ec, right, TypeManager.int64_type, loc);
980
981                                 type = TypeManager.int64_type;
982                         } else if (l == TypeManager.uint32_type || r == TypeManager.uint32_type){
983                                 //
984                                 // If either operand is of type uint, and the other
985                                 // operand is of type sbyte, short or int, othe operands are
986                                 // converted to type long.
987                                 //
988                                 Type other = null;
989                                 
990                                 if (l == TypeManager.uint32_type)
991                                         other = r;
992                                 else if (r == TypeManager.uint32_type)
993                                         other = l;
994
995                                 if ((other == TypeManager.sbyte_type) ||
996                                     (other == TypeManager.short_type) ||
997                                     (other == TypeManager.int32_type)){
998                                         left = ForceConversion (ec, left, TypeManager.int64_type);
999                                         right = ForceConversion (ec, right, TypeManager.int64_type);
1000                                         type = TypeManager.int64_type;
1001                                 } else {
1002                                         //
1003                                         // if either operand is of type uint, the other
1004                                         // operand is converd to type uint
1005                                         //
1006                                         left = ForceConversion (ec, left, TypeManager.uint32_type);
1007                                         right = ForceConversion (ec, right, TypeManager.uint32_type);
1008                                         type = TypeManager.uint32_type;
1009                                 } 
1010                         } else if (l == TypeManager.decimal_type || r == TypeManager.decimal_type){
1011                                 if (l != TypeManager.decimal_type)
1012                                         left = ConvertImplicit (ec, left, TypeManager.decimal_type, loc);
1013                                 if (r != TypeManager.decimal_type)
1014                                         right = ConvertImplicit (ec, right, TypeManager.decimal_type, loc);
1015
1016                                 type = TypeManager.decimal_type;
1017                         } else {
1018                                 Expression l_tmp, r_tmp;
1019
1020                                 l_tmp = ForceConversion (ec, left, TypeManager.int32_type);
1021                                 if (l_tmp == null)
1022                                         return false;
1023                                 
1024                                 r_tmp = ForceConversion (ec, right, TypeManager.int32_type);
1025                                 if (r_tmp == null)
1026                                         return false;
1027
1028                                 left = l_tmp;
1029                                 right = r_tmp;
1030                                 
1031                                 type = TypeManager.int32_type;
1032                         }
1033
1034                         return true;
1035                 }
1036
1037                 void error19 ()
1038                 {
1039                         Error (19, loc,
1040                                "Operator " + OperName () + " cannot be applied to operands of type `" +
1041                                TypeManager.CSharpName (left.Type) + "' and `" +
1042                                TypeManager.CSharpName (right.Type) + "'");
1043                                                      
1044                 }
1045                 
1046                 Expression CheckShiftArguments (EmitContext ec)
1047                 {
1048                         Expression e;
1049                         Type l = left.Type;
1050                         Type r = right.Type;
1051
1052                         e = ForceConversion (ec, right, TypeManager.int32_type);
1053                         if (e == null){
1054                                 error19 ();
1055                                 return null;
1056                         }
1057                         right = e;
1058
1059                         if (((e = ConvertImplicit (ec, left, TypeManager.int32_type, loc)) != null) ||
1060                             ((e = ConvertImplicit (ec, left, TypeManager.uint32_type, loc)) != null) ||
1061                             ((e = ConvertImplicit (ec, left, TypeManager.int64_type, loc)) != null) ||
1062                             ((e = ConvertImplicit (ec, left, TypeManager.uint64_type, loc)) != null)){
1063                                 left = e;
1064                                 type = e.Type;
1065
1066                                 return this;
1067                         }
1068                         error19 ();
1069                         return null;
1070                 }
1071                 
1072                 Expression ResolveOperator (EmitContext ec)
1073                 {
1074                         Type l = left.Type;
1075                         Type r = right.Type;
1076
1077                         //
1078                         // Step 1: Perform Operator Overload location
1079                         //
1080                         Expression left_expr, right_expr;
1081                         
1082                         string op = "op_" + oper;
1083
1084                         left_expr = MemberLookup (ec, l, op, false, loc);
1085                         if (left_expr == null && l.BaseType != null)
1086                                 left_expr = MemberLookup (ec, l.BaseType, op, false, loc);
1087                         
1088                         right_expr = MemberLookup (ec, r, op, false, loc);
1089                         if (right_expr == null && r.BaseType != null)
1090                                 right_expr = MemberLookup (ec, r.BaseType, op, false, loc);
1091                         
1092                         MethodGroupExpr union = Invocation.MakeUnionSet (left_expr, right_expr);
1093                         
1094                         if (union != null) {
1095                                 Arguments = new ArrayList ();
1096                                 Arguments.Add (new Argument (left, Argument.AType.Expression));
1097                                 Arguments.Add (new Argument (right, Argument.AType.Expression));
1098
1099                                 method = Invocation.OverloadResolve (ec, union, Arguments, loc);
1100                                 if (method != null) {
1101                                         MethodInfo mi = (MethodInfo) method;
1102                                         type = mi.ReturnType;
1103                                         return this;
1104                                 } else {
1105                                         error19 ();
1106                                         return null;
1107                                 }
1108                         }       
1109
1110                         //
1111                         // Step 2: Default operations on CLI native types.
1112                         //
1113                         
1114                         // Only perform numeric promotions on:
1115                         // +, -, *, /, %, &, |, ^, ==, !=, <, >, <=, >=
1116                         //
1117                         if (oper == Operator.Addition){
1118                                 //
1119                                 // If any of the arguments is a string, cast to string
1120                                 //
1121                                 if (l == TypeManager.string_type){
1122                                         if (r == TypeManager.string_type){
1123                                                 if (left is Literal && right is Literal){
1124                                                         StringLiteral ls = (StringLiteral) left;
1125                                                         StringLiteral rs = (StringLiteral) right;
1126                                                         
1127                                                         return new StringLiteral (ls.Value + rs.Value);
1128                                                 }
1129                                                 
1130                                                 // string + string
1131                                                 method = TypeManager.string_concat_string_string;
1132                                         } else {
1133                                                 // string + object
1134                                                 method = TypeManager.string_concat_object_object;
1135                                                 right = ConvertImplicit (ec, right,
1136                                                                          TypeManager.object_type, loc);
1137                                         }
1138                                         type = TypeManager.string_type;
1139
1140                                         Arguments = new ArrayList ();
1141                                         Arguments.Add (new Argument (left, Argument.AType.Expression));
1142                                         Arguments.Add (new Argument (right, Argument.AType.Expression));
1143
1144                                         return this;
1145                                         
1146                                 } else if (r == TypeManager.string_type){
1147                                         // object + string
1148                                         method = TypeManager.string_concat_object_object;
1149                                         Arguments = new ArrayList ();
1150                                         Arguments.Add (new Argument (left, Argument.AType.Expression));
1151                                         Arguments.Add (new Argument (right, Argument.AType.Expression));
1152
1153                                         left = ConvertImplicit (ec, left, TypeManager.object_type, loc);
1154                                         type = TypeManager.string_type;
1155
1156                                         return this;
1157                                 }
1158
1159                                 //
1160                                 // FIXME: is Delegate operator + (D x, D y) handled?
1161                                 //
1162                         }
1163                         
1164                         if (oper == Operator.LeftShift || oper == Operator.RightShift)
1165                                 return CheckShiftArguments (ec);
1166
1167                         if (oper == Operator.LogicalOr || oper == Operator.LogicalAnd){
1168                                 if (l != TypeManager.bool_type || r != TypeManager.bool_type){
1169                                         error19 ();
1170                                         return null;
1171                                 }
1172
1173                                 type = TypeManager.bool_type;
1174                                 return this;
1175                         } 
1176
1177                         if (oper == Operator.Equality || oper == Operator.Inequality){
1178                                 if (l == TypeManager.bool_type || r == TypeManager.bool_type){
1179                                         if (r != TypeManager.bool_type || l != TypeManager.bool_type){
1180                                                 error19 ();
1181                                                 return null;
1182                                         }
1183                                         
1184                                         type = TypeManager.bool_type;
1185                                         return this;
1186                                 }
1187
1188                         }
1189
1190                         //
1191                         // We are dealing with numbers
1192                         //
1193
1194                         if (!DoNumericPromotions (ec, l, r)){
1195                                 // Attempt:
1196                                 //
1197                                 // operator != (object a, object b)
1198                                 // operator == (object a, object b)
1199                                 //
1200
1201                                 if (oper == Operator.Equality || oper == Operator.Inequality){
1202                                         Expression li, ri;
1203                                         li = ConvertImplicit (ec, left, TypeManager.object_type, loc);
1204                                         if (li != null){
1205                                                 ri = ConvertImplicit (ec, right, TypeManager.object_type,
1206                                                                       loc);
1207                                                 if (ri != null){
1208                                                         left = li;
1209                                                         right = ri;
1210                                                         
1211                                                         type = TypeManager.bool_type;
1212                                                         return this;
1213                                                 }
1214                                         }
1215                                 }
1216
1217                                 error19 ();
1218                                 return null;
1219                         }
1220
1221                         if (left == null || right == null)
1222                                 return null;
1223
1224                         
1225                         if (oper == Operator.BitwiseAnd ||
1226                             oper == Operator.BitwiseOr ||
1227                             oper == Operator.ExclusiveOr){
1228                                 if (!((l == TypeManager.int32_type) ||
1229                                       (l == TypeManager.uint32_type) ||
1230                                       (l == TypeManager.int64_type) ||
1231                                       (l == TypeManager.uint64_type))){
1232                                         error19 ();
1233                                         return null;
1234                                 }
1235                                 type = l;
1236                         }
1237
1238                         if (oper == Operator.Equality ||
1239                             oper == Operator.Inequality ||
1240                             oper == Operator.LessThanOrEqual ||
1241                             oper == Operator.LessThan ||
1242                             oper == Operator.GreaterThanOrEqual ||
1243                             oper == Operator.GreaterThan){
1244                                 type = TypeManager.bool_type;
1245                         }
1246
1247                         return this;
1248                 }
1249                 
1250                 public override Expression DoResolve (EmitContext ec)
1251                 {
1252                         left = left.Resolve (ec);
1253                         right = right.Resolve (ec);
1254
1255                         if (left == null || right == null)
1256                                 return null;
1257
1258                         if (left.Type == null)
1259                                 throw new Exception (
1260                                         "Resolve returned non null, but did not set the type! (" +
1261                                         left + ") at Line: " + loc.Row);
1262                         if (right.Type == null)
1263                                 throw new Exception (
1264                                         "Resolve returned non null, but did not set the type! (" +
1265                                         right + ") at Line: "+ loc.Row);
1266
1267                         eclass = ExprClass.Value;
1268
1269                         return ResolveOperator (ec);
1270                 }
1271
1272                 public bool IsBranchable ()
1273                 {
1274                         if (oper == Operator.Equality ||
1275                             oper == Operator.Inequality ||
1276                             oper == Operator.LessThan ||
1277                             oper == Operator.GreaterThan ||
1278                             oper == Operator.LessThanOrEqual ||
1279                             oper == Operator.GreaterThanOrEqual){
1280                                 return true;
1281                         } else
1282                                 return false;
1283                 }
1284
1285                 /// <summary>
1286                 ///   This entry point is used by routines that might want
1287                 ///   to emit a brfalse/brtrue after an expression, and instead
1288                 ///   they could use a more compact notation.
1289                 ///
1290                 ///   Typically the code would generate l.emit/r.emit, followed
1291                 ///   by the comparission and then a brtrue/brfalse.  The comparissions
1292                 ///   are sometimes inneficient (there are not as complete as the branches
1293                 ///   look for the hacks in Emit using double ceqs).
1294                 ///
1295                 ///   So for those cases we provide EmitBranchable that can emit the
1296                 ///   branch with the test
1297                 /// </summary>
1298                 public void EmitBranchable (EmitContext ec, int target)
1299                 {
1300                         OpCode opcode;
1301                         bool close_target = false;
1302                         
1303                         left.Emit (ec);
1304                         right.Emit (ec);
1305                         
1306                         switch (oper){
1307                         case Operator.Equality:
1308                                 if (close_target)
1309                                         opcode = OpCodes.Beq_S;
1310                                 else
1311                                         opcode = OpCodes.Beq;
1312                                 break;
1313
1314                         case Operator.Inequality:
1315                                 if (close_target)
1316                                         opcode = OpCodes.Bne_Un_S;
1317                                 else
1318                                         opcode = OpCodes.Bne_Un;
1319                                 break;
1320
1321                         case Operator.LessThan:
1322                                 if (close_target)
1323                                         opcode = OpCodes.Blt_S;
1324                                 else
1325                                         opcode = OpCodes.Blt;
1326                                 break;
1327
1328                         case Operator.GreaterThan:
1329                                 if (close_target)
1330                                         opcode = OpCodes.Bgt_S;
1331                                 else
1332                                         opcode = OpCodes.Bgt;
1333                                 break;
1334
1335                         case Operator.LessThanOrEqual:
1336                                 if (close_target)
1337                                         opcode = OpCodes.Ble_S;
1338                                 else
1339                                         opcode = OpCodes.Ble;
1340                                 break;
1341
1342                         case Operator.GreaterThanOrEqual:
1343                                 if (close_target)
1344                                         opcode = OpCodes.Bge_S;
1345                                 else
1346                                         opcode = OpCodes.Ble;
1347                                 break;
1348
1349                         default:
1350                                 throw new Exception ("EmitBranchable called on non-EmitBranchable operator: "
1351                                                      + oper.ToString ());
1352                         }
1353
1354                         ec.ig.Emit (opcode, target);
1355                 }
1356                 
1357                 public override void Emit (EmitContext ec)
1358                 {
1359                         ILGenerator ig = ec.ig;
1360                         Type l = left.Type;
1361                         Type r = right.Type;
1362                         OpCode opcode;
1363
1364                         if (method != null) {
1365
1366                                 // Note that operators are static anyway
1367                                 
1368                                 if (Arguments != null) 
1369                                         Invocation.EmitArguments (ec, method, Arguments);
1370                                 
1371                                 if (method is MethodInfo)
1372                                         ig.Emit (OpCodes.Call, (MethodInfo) method);
1373                                 else
1374                                         ig.Emit (OpCodes.Call, (ConstructorInfo) method);
1375
1376                                 return;
1377                         }
1378                         
1379                         left.Emit (ec);
1380                         right.Emit (ec);
1381
1382                         switch (oper){
1383                         case Operator.Multiply:
1384                                 if (ec.CheckState){
1385                                         if (l == TypeManager.int32_type || l == TypeManager.int64_type)
1386                                                 opcode = OpCodes.Mul_Ovf;
1387                                         else if (l==TypeManager.uint32_type || l==TypeManager.uint64_type)
1388                                                 opcode = OpCodes.Mul_Ovf_Un;
1389                                         else
1390                                                 opcode = OpCodes.Mul;
1391                                 } else
1392                                         opcode = OpCodes.Mul;
1393
1394                                 break;
1395
1396                         case Operator.Division:
1397                                 if (l == TypeManager.uint32_type || l == TypeManager.uint64_type)
1398                                         opcode = OpCodes.Div_Un;
1399                                 else
1400                                         opcode = OpCodes.Div;
1401                                 break;
1402
1403                         case Operator.Modulus:
1404                                 if (l == TypeManager.uint32_type || l == TypeManager.uint64_type)
1405                                         opcode = OpCodes.Rem_Un;
1406                                 else
1407                                         opcode = OpCodes.Rem;
1408                                 break;
1409
1410                         case Operator.Addition:
1411                                 if (ec.CheckState){
1412                                         if (l == TypeManager.int32_type || l == TypeManager.int64_type)
1413                                                 opcode = OpCodes.Add_Ovf;
1414                                         else if (l==TypeManager.uint32_type || l==TypeManager.uint64_type)
1415                                                 opcode = OpCodes.Add_Ovf_Un;
1416                                         else
1417                                                 opcode = OpCodes.Mul;
1418                                 } else
1419                                         opcode = OpCodes.Add;
1420                                 break;
1421
1422                         case Operator.Subtraction:
1423                                 if (ec.CheckState){
1424                                         if (l == TypeManager.int32_type || l == TypeManager.int64_type)
1425                                                 opcode = OpCodes.Sub_Ovf;
1426                                         else if (l==TypeManager.uint32_type || l==TypeManager.uint64_type)
1427                                                 opcode = OpCodes.Sub_Ovf_Un;
1428                                         else
1429                                                 opcode = OpCodes.Sub;
1430                                 } else
1431                                         opcode = OpCodes.Sub;
1432                                 break;
1433
1434                         case Operator.RightShift:
1435                                 opcode = OpCodes.Shr;
1436                                 break;
1437                                 
1438                         case Operator.LeftShift:
1439                                 opcode = OpCodes.Shl;
1440                                 break;
1441
1442                         case Operator.Equality:
1443                                 opcode = OpCodes.Ceq;
1444                                 break;
1445
1446                         case Operator.Inequality:
1447                                 ec.ig.Emit (OpCodes.Ceq);
1448                                 ec.ig.Emit (OpCodes.Ldc_I4_0);
1449                                 
1450                                 opcode = OpCodes.Ceq;
1451                                 break;
1452
1453                         case Operator.LessThan:
1454                                 opcode = OpCodes.Clt;
1455                                 break;
1456
1457                         case Operator.GreaterThan:
1458                                 opcode = OpCodes.Cgt;
1459                                 break;
1460
1461                         case Operator.LessThanOrEqual:
1462                                 ec.ig.Emit (OpCodes.Cgt);
1463                                 ec.ig.Emit (OpCodes.Ldc_I4_0);
1464                                 
1465                                 opcode = OpCodes.Ceq;
1466                                 break;
1467
1468                         case Operator.GreaterThanOrEqual:
1469                                 ec.ig.Emit (OpCodes.Clt);
1470                                 ec.ig.Emit (OpCodes.Ldc_I4_1);
1471                                 
1472                                 opcode = OpCodes.Sub;
1473                                 break;
1474
1475                         case Operator.LogicalOr:
1476                         case Operator.BitwiseOr:
1477                                 opcode = OpCodes.Or;
1478                                 break;
1479
1480                         case Operator.LogicalAnd:
1481                         case Operator.BitwiseAnd:
1482                                 opcode = OpCodes.And;
1483                                 break;
1484
1485                         case Operator.ExclusiveOr:
1486                                 opcode = OpCodes.Xor;
1487                                 break;
1488
1489                         default:
1490                                 throw new Exception ("This should not happen: Operator = "
1491                                                      + oper.ToString ());
1492                         }
1493
1494                         ig.Emit (opcode);
1495                 }
1496
1497                 /// <summary>
1498                 ///   Constant expression reducer for binary operations
1499                 /// </summary>
1500                 public override Expression Reduce (EmitContext ec)
1501                 {
1502                         
1503                         left = left.Reduce (ec);
1504                         right = right.Reduce (ec);
1505
1506                         if (!(left is Literal && right is Literal))
1507                                 return this;
1508
1509                         if (method == TypeManager.string_concat_string_string){
1510                                 StringLiteral ls = (StringLiteral) left;
1511                                 StringLiteral rs = (StringLiteral) right;
1512                                 
1513                                 return new StringLiteral (ls.Value + rs.Value);
1514                         }
1515
1516                         // FINISH ME.
1517                         
1518                         return this;
1519                 }
1520         }
1521
1522         public class Conditional : Expression {
1523                 Expression expr, trueExpr, falseExpr;
1524                 Location loc;
1525                 
1526                 public Conditional (Expression expr, Expression trueExpr, Expression falseExpr, Location l)
1527                 {
1528                         this.expr = expr;
1529                         this.trueExpr = trueExpr;
1530                         this.falseExpr = falseExpr;
1531                         this.loc = l;
1532                 }
1533
1534                 public Expression Expr {
1535                         get {
1536                                 return expr;
1537                         }
1538                 }
1539
1540                 public Expression TrueExpr {
1541                         get {
1542                                 return trueExpr;
1543                         }
1544                 }
1545
1546                 public Expression FalseExpr {
1547                         get {
1548                                 return falseExpr;
1549                         }
1550                 }
1551
1552                 public override Expression DoResolve (EmitContext ec)
1553                 {
1554                         expr = expr.Resolve (ec);
1555
1556                         if (expr.Type != TypeManager.bool_type)
1557                                 expr = Expression.ConvertImplicitRequired (
1558                                         ec, expr, TypeManager.bool_type, loc);
1559                         
1560                         trueExpr = trueExpr.Resolve (ec);
1561                         falseExpr = falseExpr.Resolve (ec);
1562
1563                         if (expr == null || trueExpr == null || falseExpr == null)
1564                                 return null;
1565
1566                         if (trueExpr.Type == falseExpr.Type)
1567                                 type = trueExpr.Type;
1568                         else {
1569                                 Expression conv;
1570
1571                                 //
1572                                 // First, if an implicit conversion exists from trueExpr
1573                                 // to falseExpr, then the result type is of type falseExpr.Type
1574                                 //
1575                                 conv = ConvertImplicit (ec, trueExpr, falseExpr.Type, loc);
1576                                 if (conv != null){
1577                                         type = falseExpr.Type;
1578                                         trueExpr = conv;
1579                                 } else if ((conv = ConvertImplicit(ec, falseExpr,trueExpr.Type,loc))!= null){
1580                                         type = trueExpr.Type;
1581                                         falseExpr = conv;
1582                                 } else {
1583                                         Error (173, loc, "The type of the conditional expression can " +
1584                                                "not be computed because there is no implicit conversion" +
1585                                                " from `" + TypeManager.CSharpName (trueExpr.Type) + "'" +
1586                                                " and `" + TypeManager.CSharpName (falseExpr.Type) + "'");
1587                                         return null;
1588                                 }
1589                         }
1590
1591                         if (expr is BoolLiteral){
1592                                 BoolLiteral bl = (BoolLiteral) expr;
1593
1594                                 if (bl.Value)
1595                                         return trueExpr;
1596                                 else
1597                                         return falseExpr;
1598                         }
1599                         
1600                         eclass = ExprClass.Value;
1601                         return this;
1602                 }
1603
1604                 public override void Emit (EmitContext ec)
1605                 {
1606                         ILGenerator ig = ec.ig;
1607                         Label false_target = ig.DefineLabel ();
1608                         Label end_target = ig.DefineLabel ();
1609
1610                         expr.Emit (ec);
1611                         ig.Emit (OpCodes.Brfalse, false_target);
1612                         trueExpr.Emit (ec);
1613                         ig.Emit (OpCodes.Br, end_target);
1614                         ig.MarkLabel (false_target);
1615                         falseExpr.Emit (ec);
1616                         ig.MarkLabel (end_target);
1617                 }
1618
1619                 public override Expression Reduce (EmitContext ec)
1620                 {
1621                         expr = expr.Reduce (ec);
1622                         trueExpr = trueExpr.Reduce (ec);
1623                         falseExpr = falseExpr.Reduce (ec);
1624
1625                         if (!(expr is Literal && trueExpr is Literal && falseExpr is Literal))
1626                                 return this;
1627
1628                         BoolLiteral bl = (BoolLiteral) expr;
1629
1630                         if (bl.Value)
1631                                 return trueExpr;
1632                         else
1633                                 return falseExpr;
1634                 }
1635         }
1636
1637         public class LocalVariableReference : Expression, IAssignMethod, IMemoryLocation {
1638                 public readonly string Name;
1639                 public readonly Block Block;
1640
1641                 VariableInfo variable_info;
1642                 
1643                 public LocalVariableReference (Block block, string name)
1644                 {
1645                         Block = block;
1646                         Name = name;
1647                         eclass = ExprClass.Variable;
1648                 }
1649
1650                 public VariableInfo VariableInfo {
1651                         get {
1652                                 if (variable_info == null)
1653                                         variable_info = Block.GetVariableInfo (Name);
1654                                 return variable_info;
1655                         }
1656                 }
1657                 
1658                 public override Expression DoResolve (EmitContext ec)
1659                 {
1660                         VariableInfo vi = VariableInfo;
1661
1662                         type = vi.VariableType;
1663                         return this;
1664                 }
1665
1666                 public override void Emit (EmitContext ec)
1667                 {
1668                         VariableInfo vi = VariableInfo;
1669                         ILGenerator ig = ec.ig;
1670                         int idx = vi.Idx;
1671
1672                         vi.Used = true;
1673
1674                         switch (idx){
1675                         case 0:
1676                                 ig.Emit (OpCodes.Ldloc_0);
1677                                 break;
1678                                 
1679                         case 1:
1680                                 ig.Emit (OpCodes.Ldloc_1);
1681                                 break;
1682                                 
1683                         case 2:
1684                                 ig.Emit (OpCodes.Ldloc_2);
1685                                 break;
1686                                 
1687                         case 3:
1688                                 ig.Emit (OpCodes.Ldloc_3);
1689                                 break;
1690                                 
1691                         default:
1692                                 if (idx <= 255)
1693                                         ig.Emit (OpCodes.Ldloc_S, (byte) idx);
1694                                 else
1695                                         ig.Emit (OpCodes.Ldloc, idx);
1696                                 break;
1697                         }
1698                 }
1699                 
1700                 public static void Store (ILGenerator ig, int idx)
1701                 {
1702                         switch (idx){
1703                         case 0:
1704                                 ig.Emit (OpCodes.Stloc_0);
1705                                 break;
1706                                 
1707                         case 1:
1708                                 ig.Emit (OpCodes.Stloc_1);
1709                                 break;
1710                                 
1711                         case 2:
1712                                 ig.Emit (OpCodes.Stloc_2);
1713                                 break;
1714                                 
1715                         case 3:
1716                                 ig.Emit (OpCodes.Stloc_3);
1717                                 break;
1718                                 
1719                         default:
1720                                 if (idx <= 255)
1721                                         ig.Emit (OpCodes.Stloc_S, (byte) idx);
1722                                 else
1723                                         ig.Emit (OpCodes.Stloc, idx);
1724                                 break;
1725                         }
1726                 }
1727
1728                 public void EmitAssign (EmitContext ec, Expression source)
1729                 {
1730                         ILGenerator ig = ec.ig;
1731                         VariableInfo vi = VariableInfo;
1732
1733                         vi.Assigned = true;
1734
1735                         source.Emit (ec);
1736                         
1737                         // Funny seems the code below generates optimal code for us, but
1738                         // seems to take too long to generate what we need.
1739                         // ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
1740
1741                         Store (ig, vi.Idx);
1742                 }
1743                 
1744                 public void AddressOf (EmitContext ec)
1745                 {
1746                         VariableInfo vi = VariableInfo;
1747                         int idx = vi.Idx;
1748
1749                         vi.Used = true;
1750                         vi.Assigned = true;
1751                         
1752                         if (idx <= 255)
1753                                 ec.ig.Emit (OpCodes.Ldloca_S, (byte) idx);
1754                         else
1755                                 ec.ig.Emit (OpCodes.Ldloca, idx);
1756                 }
1757         }
1758
1759         /// <summary>
1760         ///   This represents a reference to a parameter in the intermediate
1761         ///   representation.
1762         /// </summary>
1763         public class ParameterReference : Expression, IAssignMethod, IMemoryLocation {
1764                 public readonly Parameters Pars;
1765                 public readonly String Name;
1766                 public readonly int Idx;
1767                 int arg_idx;
1768                 
1769                 public ParameterReference (Parameters pars, int idx, string name)
1770                 {
1771                         Pars = pars;
1772                         Idx  = idx;
1773                         Name = name;
1774                         eclass = ExprClass.Variable;
1775                 }
1776
1777                 public override Expression DoResolve (EmitContext ec)
1778                 {
1779                         Type [] types = Pars.GetParameterInfo (ec.TypeContainer);
1780
1781                         type = types [Idx];
1782
1783                         arg_idx = Idx;
1784                         if (!ec.IsStatic)
1785                                 arg_idx++;
1786                         
1787                         return this;
1788                 }
1789
1790                 public override void Emit (EmitContext ec)
1791                 {
1792                         if (arg_idx <= 255)
1793                                 ec.ig.Emit (OpCodes.Ldarg_S, (byte) arg_idx);
1794                         else
1795                                 ec.ig.Emit (OpCodes.Ldarg, arg_idx);
1796                 }
1797
1798                 public void EmitAssign (EmitContext ec, Expression source)
1799                 {
1800                         source.Emit (ec);
1801                         
1802                         if (arg_idx <= 255)
1803                                 ec.ig.Emit (OpCodes.Starg_S, (byte) arg_idx);
1804                         else
1805                                 ec.ig.Emit (OpCodes.Starg, arg_idx);
1806                         
1807                 }
1808
1809                 public void AddressOf (EmitContext ec)
1810                 {
1811                         if (arg_idx <= 255)
1812                                 ec.ig.Emit (OpCodes.Ldarga_S, (byte) arg_idx);
1813                         else
1814                                 ec.ig.Emit (OpCodes.Ldarga, arg_idx);
1815                 }
1816         }
1817         
1818         /// <summary>
1819         ///   Used for arguments to New(), Invocation()
1820         /// </summary>
1821         public class Argument {
1822                 public enum AType : byte {
1823                         Expression,
1824                         Ref,
1825                         Out
1826                 };
1827
1828                 public readonly AType ArgType;
1829                 public Expression expr;
1830                 
1831                 public Argument (Expression expr, AType type)
1832                 {
1833                         this.expr = expr;
1834                         this.ArgType = type;
1835                 }
1836
1837                 public Expression Expr {
1838                         get {
1839                                 return expr;
1840                         }
1841
1842                         set {
1843                                 expr = value;
1844                         }
1845                 }
1846
1847                 public Type Type {
1848                         get {
1849                                 return expr.Type;
1850                         }
1851                 }
1852
1853                 public Parameter.Modifier GetParameterModifier ()
1854                 {
1855                         if (ArgType == AType.Ref)
1856                                 return Parameter.Modifier.REF;
1857
1858                         if (ArgType == AType.Out)
1859                                 return Parameter.Modifier.OUT;
1860
1861                         return Parameter.Modifier.NONE;
1862                 }
1863
1864                 public static string FullDesc (Argument a)
1865                 {
1866                         return (a.ArgType == AType.Ref ? "ref " :
1867                                 (a.ArgType == AType.Out ? "out " : "")) +
1868                                 TypeManager.CSharpName (a.Expr.Type);
1869                 }
1870                 
1871                 public bool Resolve (EmitContext ec, Location loc)
1872                 {
1873                         expr = expr.Resolve (ec);
1874
1875                         if (ArgType == AType.Expression)
1876                                 return expr != null;
1877
1878                         if (expr.ExprClass != ExprClass.Variable){
1879                                 Report.Error (206, loc,
1880                                               "A property or indexer can not be passed as an out or ref " +
1881                                               "parameter");
1882                                 return false;
1883                         }
1884                                 
1885                         return expr != null;
1886                 }
1887
1888                 public void Emit (EmitContext ec)
1889                 {
1890                         if (ArgType == AType.Ref || ArgType == AType.Out)
1891                                 ((IMemoryLocation)expr).AddressOf (ec);
1892                         else
1893                                 expr.Emit (ec);
1894                 }
1895         }
1896
1897         /// <summary>
1898         ///   Invocation of methods or delegates.
1899         /// </summary>
1900         public class Invocation : ExpressionStatement {
1901                 public readonly ArrayList Arguments;
1902                 Location loc;
1903
1904                 Expression expr;
1905                 MethodBase method = null;
1906                         
1907                 static Hashtable method_parameter_cache;
1908
1909                 static Invocation ()
1910                 {
1911                         method_parameter_cache = new Hashtable ();
1912                 }
1913                         
1914                 //
1915                 // arguments is an ArrayList, but we do not want to typecast,
1916                 // as it might be null.
1917                 //
1918                 // FIXME: only allow expr to be a method invocation or a
1919                 // delegate invocation (7.5.5)
1920                 //
1921                 public Invocation (Expression expr, ArrayList arguments, Location l)
1922                 {
1923                         this.expr = expr;
1924                         Arguments = arguments;
1925                         loc = l;
1926                 }
1927
1928                 public Expression Expr {
1929                         get {
1930                                 return expr;
1931                         }
1932                 }
1933
1934                 /// <summary>
1935                 ///   Returns the Parameters (a ParameterData interface) for the
1936                 ///   Method `mb'
1937                 /// </summary>
1938                 public static ParameterData GetParameterData (MethodBase mb)
1939                 {
1940                         object pd = method_parameter_cache [mb];
1941                         object ip;
1942                         
1943                         if (pd != null)
1944                                 return (ParameterData) pd;
1945
1946                         
1947                         ip = TypeContainer.LookupParametersByBuilder (mb);
1948                         if (ip != null){
1949                                 method_parameter_cache [mb] = ip;
1950
1951                                 return (ParameterData) ip;
1952                         } else {
1953                                 ParameterInfo [] pi = mb.GetParameters ();
1954                                 ReflectionParameters rp = new ReflectionParameters (pi);
1955                                 method_parameter_cache [mb] = rp;
1956
1957                                 return (ParameterData) rp;
1958                         }
1959                 }
1960
1961                 /// <summary>
1962                 ///   Tells whether a user defined conversion from Type `from' to
1963                 ///   Type `to' exists.
1964                 ///
1965                 ///   FIXME: we could implement a cache here. 
1966                 /// </summary>
1967                 static bool ConversionExists (EmitContext ec, Type from, Type to, Location loc)
1968                 {
1969                         // Locate user-defined implicit operators
1970
1971                         Expression mg;
1972                         
1973                         mg = MemberLookup (ec, to, "op_Implicit", false, loc);
1974
1975                         if (mg != null) {
1976                                 MethodGroupExpr me = (MethodGroupExpr) mg;
1977                                 
1978                                 for (int i = me.Methods.Length; i > 0;) {
1979                                         i--;
1980                                         MethodBase mb = me.Methods [i];
1981                                         ParameterData pd = GetParameterData (mb);
1982                                         
1983                                         if (from == pd.ParameterType (0))
1984                                                 return true;
1985                                 }
1986                         }
1987
1988                         mg = MemberLookup (ec, from, "op_Implicit", false, loc);
1989
1990                         if (mg != null) {
1991                                 MethodGroupExpr me = (MethodGroupExpr) mg;
1992
1993                                 for (int i = me.Methods.Length; i > 0;) {
1994                                         i--;
1995                                         MethodBase mb = me.Methods [i];
1996                                         MethodInfo mi = (MethodInfo) mb;
1997                                         
1998                                         if (mi.ReturnType == to)
1999                                                 return true;
2000                                 }
2001                         }
2002                         
2003                         return false;
2004                 }
2005                 
2006                 /// <summary>
2007                 ///  Determines "better conversion" as specified in 7.4.2.3
2008                 ///  Returns : 1 if a->p is better
2009                 ///            0 if a->q or neither is better 
2010                 /// </summary>
2011                 static int BetterConversion (EmitContext ec, Argument a, Type p, Type q, bool use_standard,
2012                                              Location loc)
2013                 {
2014                         Type argument_type = a.Type;
2015                         Expression argument_expr = a.Expr;
2016
2017                         if (argument_type == null)
2018                                 throw new Exception ("Expression of type " + a.Expr + " does not resolve its type");
2019
2020                         if (p == q)
2021                                 return 0;
2022                         
2023                         if (argument_type == p)
2024                                 return 1;
2025
2026                         if (argument_type == q)
2027                                 return 0;
2028
2029                         //
2030                         // Now probe whether an implicit constant expression conversion
2031                         // can be used.
2032                         //
2033                         // An implicit constant expression conversion permits the following
2034                         // conversions:
2035                         //
2036                         //    * A constant-expression of type `int' can be converted to type
2037                         //      sbyte, byute, short, ushort, uint, ulong provided the value of
2038                         //      of the expression is withing the range of the destination type.
2039                         //
2040                         //    * A constant-expression of type long can be converted to type
2041                         //      ulong, provided the value of the constant expression is not negative
2042                         //
2043                         // FIXME: Note that this assumes that constant folding has
2044                         // taken place.  We dont do constant folding yet.
2045                         //
2046
2047                         if (argument_expr is IntLiteral){
2048                                 IntLiteral ei = (IntLiteral) argument_expr;
2049                                 int value = ei.Value;
2050                                 
2051                                 if (p == TypeManager.sbyte_type){
2052                                         if (value >= SByte.MinValue && value <= SByte.MaxValue)
2053                                                 return 1;
2054                                 } else if (p == TypeManager.byte_type){
2055                                         if (Byte.MinValue >= 0 && value <= Byte.MaxValue)
2056                                                 return 1;
2057                                 } else if (p == TypeManager.short_type){
2058                                         if (value >= Int16.MinValue && value <= Int16.MaxValue)
2059                                                 return 1;
2060                                 } else if (p == TypeManager.ushort_type){
2061                                         if (value >= UInt16.MinValue && value <= UInt16.MaxValue)
2062                                                 return 1;
2063                                 } else if (p == TypeManager.uint32_type){
2064                                         //
2065                                         // we can optimize this case: a positive int32
2066                                         // always fits on a uint32
2067                                         //
2068                                         if (value >= 0)
2069                                                 return 1;
2070                                 } else if (p == TypeManager.uint64_type){
2071                                         //
2072                                         // we can optimize this case: a positive int32
2073                                         // always fits on a uint64
2074                                         //
2075                                         if (value >= 0)
2076                                                 return 1;
2077                                 }
2078                         } else if (argument_type == TypeManager.int64_type && argument_expr is LongLiteral){
2079                                 LongLiteral ll = (LongLiteral) argument_expr;
2080                                 
2081                                 if (p == TypeManager.uint64_type){
2082                                         if (ll.Value > 0)
2083                                                 return 1;
2084                                 }
2085                         }
2086
2087                         if (q == null) {
2088
2089                                 Expression tmp;
2090
2091                                 if (use_standard)
2092                                         tmp = ConvertImplicitStandard (ec, argument_expr, p, loc);
2093                                 else
2094                                         tmp = ConvertImplicit (ec, argument_expr, p, loc);
2095
2096                                 if (tmp != null)
2097                                         return 1;
2098                                 else
2099                                         return 0;
2100
2101                         }
2102
2103                         if (ConversionExists (ec, p, q, loc) == true &&
2104                             ConversionExists (ec, q, p, loc) == false)
2105                                 return 1;
2106
2107                         if (p == TypeManager.sbyte_type)
2108                                 if (q == TypeManager.byte_type || q == TypeManager.ushort_type ||
2109                                     q == TypeManager.uint32_type || q == TypeManager.uint64_type)
2110                                         return 1;
2111
2112                         if (p == TypeManager.short_type)
2113                                 if (q == TypeManager.ushort_type || q == TypeManager.uint32_type ||
2114                                     q == TypeManager.uint64_type)
2115                                         return 1;
2116
2117                         if (p == TypeManager.int32_type)
2118                                 if (q == TypeManager.uint32_type || q == TypeManager.uint64_type)
2119                                         return 1;
2120
2121                         if (p == TypeManager.int64_type)
2122                                 if (q == TypeManager.uint64_type)
2123                                         return 1;
2124
2125                         return 0;
2126                 }
2127                 
2128                 /// <summary>
2129                 ///  Determines "Better function"
2130                 /// </summary>
2131                 /// <remarks>
2132                 ///    and returns an integer indicating :
2133                 ///    0 if candidate ain't better
2134                 ///    1 if candidate is better than the current best match
2135                 /// </remarks>
2136                 static int BetterFunction (EmitContext ec, ArrayList args,
2137                                            MethodBase candidate, MethodBase best,
2138                                            bool use_standard, Location loc)
2139                 {
2140                         ParameterData candidate_pd = GetParameterData (candidate);
2141                         ParameterData best_pd;
2142                         int argument_count;
2143
2144                         if (args == null)
2145                                 argument_count = 0;
2146                         else
2147                                 argument_count = args.Count;
2148
2149                         if (candidate_pd.Count == 0 && argument_count == 0)
2150                                 return 1;
2151
2152                         if (best == null) {
2153                                 if (candidate_pd.Count == argument_count) {
2154                                         int x = 0;
2155                                         for (int j = argument_count; j > 0;) {
2156                                                 j--;
2157                                                 
2158                                                 Argument a = (Argument) args [j];
2159                                                 
2160                                                 x = BetterConversion (
2161                                                         ec, a, candidate_pd.ParameterType (j), null,
2162                                                         use_standard, loc);
2163                                                 
2164                                                 if (x <= 0)
2165                                                         break;
2166                                         }
2167                                         
2168                                         if (x > 0)
2169                                                 return 1;
2170                                         else
2171                                                 return 0;
2172                                         
2173                                 } else
2174                                         return 0;
2175                         }
2176
2177                         best_pd = GetParameterData (best);
2178
2179                         if (candidate_pd.Count == argument_count && best_pd.Count == argument_count) {
2180                                 int rating1 = 0, rating2 = 0;
2181                                 
2182                                 for (int j = argument_count; j > 0;) {
2183                                         j--;
2184                                         int x, y;
2185                                         
2186                                         Argument a = (Argument) args [j];
2187
2188                                         x = BetterConversion (ec, a, candidate_pd.ParameterType (j),
2189                                                               best_pd.ParameterType (j), use_standard, loc);
2190                                         y = BetterConversion (ec, a, best_pd.ParameterType (j),
2191                                                               candidate_pd.ParameterType (j), use_standard,
2192                                                               loc);
2193                                         
2194                                         rating1 += x;
2195                                         rating2 += y;
2196                                 }
2197
2198                                 if (rating1 > rating2)
2199                                         return 1;
2200                                 else
2201                                         return 0;
2202                         } else
2203                                 return 0;
2204                         
2205                 }
2206
2207                 public static string FullMethodDesc (MethodBase mb)
2208                 {
2209                         StringBuilder sb = new StringBuilder (mb.Name);
2210                         ParameterData pd = GetParameterData (mb);
2211
2212                         int count = pd.Count;
2213                         sb.Append (" (");
2214                         
2215                         for (int i = count; i > 0; ) {
2216                                 i--;
2217                                 
2218                                 sb.Append (pd.ParameterDesc (count - i - 1));
2219                                 if (i != 0)
2220                                         sb.Append (", ");
2221                         }
2222                         
2223                         sb.Append (")");
2224                         return sb.ToString ();
2225                 }
2226
2227                 public static MethodGroupExpr MakeUnionSet (Expression mg1, Expression mg2)
2228                 {
2229                         MemberInfo [] miset;
2230                         MethodGroupExpr union;
2231                         
2232                         if (mg1 != null && mg2 != null) {
2233                                 
2234                                 MethodGroupExpr left_set = null, right_set = null;
2235                                 int length1 = 0, length2 = 0;
2236                                 
2237                                 left_set = (MethodGroupExpr) mg1;
2238                                 length1 = left_set.Methods.Length;
2239                                 
2240                                 right_set = (MethodGroupExpr) mg2;
2241                                 length2 = right_set.Methods.Length;
2242
2243                                 ArrayList common = new ArrayList ();
2244                                 
2245                                 for (int i = 0; i < left_set.Methods.Length; i++) {
2246                                         for (int j = 0; j < right_set.Methods.Length; j++) {
2247                                                 if (left_set.Methods [i] == right_set.Methods [j]) 
2248                                                         common.Add (left_set.Methods [i]);
2249                                         }
2250                                 }
2251                                 
2252                                 miset = new MemberInfo [length1 + length2 - common.Count];
2253
2254                                 left_set.Methods.CopyTo (miset, 0);
2255
2256                                 int k = 0;
2257                                 
2258                                 for (int j = 0; j < right_set.Methods.Length; j++)
2259                                         if (!common.Contains (right_set.Methods [j]))
2260                                                 miset [length1 + k++] = right_set.Methods [j];
2261                                 
2262                                 union = new MethodGroupExpr (miset);
2263
2264                                 return union;
2265
2266                         } else if (mg1 == null && mg2 != null) {
2267                                 
2268                                 MethodGroupExpr me = (MethodGroupExpr) mg2; 
2269                                 
2270                                 miset = new MemberInfo [me.Methods.Length];
2271                                 me.Methods.CopyTo (miset, 0);
2272
2273                                 union = new MethodGroupExpr (miset);
2274                                 
2275                                 return union;
2276
2277                         } else if (mg2 == null && mg1 != null) {
2278                                 
2279                                 MethodGroupExpr me = (MethodGroupExpr) mg1; 
2280                                 
2281                                 miset = new MemberInfo [me.Methods.Length];
2282                                 me.Methods.CopyTo (miset, 0);
2283
2284                                 union = new MethodGroupExpr (miset);
2285                                 
2286                                 return union;
2287                         }
2288                         
2289                         return null;
2290                 }
2291
2292                 /// <summary>
2293                 ///  Determines is the candidate method, if a params method, is applicable
2294                 ///  in its expanded form to the given set of arguments
2295                 /// </summary>
2296                 static bool IsParamsMethodApplicable (ArrayList arguments, MethodBase candidate)
2297                 {
2298                         int arg_count;
2299                         
2300                         if (arguments == null)
2301                                 arg_count = 0;
2302                         else
2303                                 arg_count = arguments.Count;
2304                         
2305                         ParameterData pd = GetParameterData (candidate);
2306                         
2307                         int pd_count = pd.Count;
2308
2309                         if (pd.ParameterModifier (pd_count - 1) != Parameter.Modifier.PARAMS)
2310                                 return false;
2311
2312                         if (pd_count - 1 > arg_count)
2313                                 return false;
2314
2315                         // If we have come this far, the case which remains is when the number of parameters
2316                         // is less than or equal to the argument count. So, we now check if the element type
2317                         // of the params array is compatible with each argument type
2318                         //
2319
2320                         Type element_type = pd.ParameterType (pd_count - 1).GetElementType ();
2321
2322                         for (int i = pd_count - 1; i < arg_count - 1; i++) {
2323                                 Argument a = (Argument) arguments [i];
2324                                 if (!StandardConversionExists (a.Type, element_type))
2325                                         return false;
2326                         }
2327                         
2328                         return true;
2329                 }
2330
2331                 /// <summary>
2332                 ///  Determines if the candidate method is applicable (section 14.4.2.1)
2333                 ///  to the given set of arguments
2334                 /// </summary>
2335                 static bool IsApplicable (ArrayList arguments, MethodBase candidate)
2336                 {
2337                         int arg_count;
2338
2339                         if (arguments == null)
2340                                 arg_count = 0;
2341                         else
2342                                 arg_count = arguments.Count;
2343
2344                         ParameterData pd = GetParameterData (candidate);
2345
2346                         int pd_count = pd.Count;
2347
2348                         if (arg_count != pd.Count)
2349                                 return false;
2350
2351                         for (int i = arg_count; i > 0; ) {
2352                                 i--;
2353
2354                                 Argument a = (Argument) arguments [i];
2355
2356                                 Parameter.Modifier a_mod = a.GetParameterModifier ();
2357                                 Parameter.Modifier p_mod = pd.ParameterModifier (i);
2358
2359                                 if (a_mod == p_mod) {
2360                                         
2361                                         if (a_mod == Parameter.Modifier.NONE)
2362                                                 if (!StandardConversionExists (a.Type, pd.ParameterType (i)))
2363                                                         return false;
2364                                         
2365                                         if (a_mod == Parameter.Modifier.REF ||
2366                                             a_mod == Parameter.Modifier.OUT)
2367                                                 if (pd.ParameterType (i) != a.Type)
2368                                                         return false;
2369                                 } else
2370                                         return false;
2371                         }
2372
2373                         return true;
2374                 }
2375                 
2376                 
2377
2378                 /// <summary>
2379                 ///   Find the Applicable Function Members (7.4.2.1)
2380                 ///
2381                 ///   me: Method Group expression with the members to select.
2382                 ///       it might contain constructors or methods (or anything
2383                 ///       that maps to a method).
2384                 ///
2385                 ///   Arguments: ArrayList containing resolved Argument objects.
2386                 ///
2387                 ///   loc: The location if we want an error to be reported, or a Null
2388                 ///        location for "probing" purposes.
2389                 ///
2390                 ///   use_standard: controls whether OverloadResolve should use the 
2391                 ///   ConvertImplicit or ConvertImplicitStandard during overload resolution.
2392                 ///
2393                 ///   Returns: The MethodBase (either a ConstructorInfo or a MethodInfo)
2394                 ///            that is the best match of me on Arguments.
2395                 ///
2396                 /// </summary>
2397                 public static MethodBase OverloadResolve (EmitContext ec, MethodGroupExpr me,
2398                                                           ArrayList Arguments, Location loc,
2399                                                           bool use_standard)
2400                 {
2401                         ArrayList afm = new ArrayList ();
2402                         int best_match_idx = -1;
2403                         MethodBase method = null;
2404                         int argument_count;
2405                         
2406                         for (int i = me.Methods.Length; i > 0; ){
2407                                 i--;
2408                                 MethodBase candidate  = me.Methods [i];
2409                                 int x;
2410
2411                                 // Check if candidate is applicable (section 14.4.2.1)
2412                                 if (!IsApplicable (Arguments, candidate))
2413                                         continue;
2414
2415                                 x = BetterFunction (ec, Arguments, candidate, method, use_standard, loc);
2416                                 
2417                                 if (x == 0)
2418                                         continue;
2419                                 else {
2420                                         best_match_idx = i;
2421                                         method = me.Methods [best_match_idx];
2422                                 }
2423                         }
2424
2425                         if (Arguments == null)
2426                                 argument_count = 0;
2427                         else
2428                                 argument_count = Arguments.Count;
2429                         
2430                         //
2431                         // Now we see if we can find params functions, applicable in their expanded form
2432                         // since if they were applicable in their normal form, they would have been selected
2433                         // above anyways
2434                         //
2435                         if (best_match_idx == -1) {
2436
2437                                 for (int i = me.Methods.Length; i > 0; ) {
2438                                         i--;
2439                                         MethodBase candidate = me.Methods [i];
2440
2441                                         if (IsParamsMethodApplicable (Arguments, candidate)) {
2442                                                 best_match_idx = i;
2443                                                 method = me.Methods [best_match_idx];
2444                                                 break;
2445                                         }
2446                                 }
2447                         }
2448
2449                         //
2450                         // Now we see if we can at least find a method with the same number of arguments
2451                         //
2452                         ParameterData pd;
2453                         
2454                         if (best_match_idx == -1) {
2455                                 
2456                                 for (int i = me.Methods.Length; i > 0;) {
2457                                         i--;
2458                                         MethodBase mb = me.Methods [i];
2459                                         pd = GetParameterData (mb);
2460                                         
2461                                         if (pd.Count == argument_count) {
2462                                                 best_match_idx = i;
2463                                                 method = me.Methods [best_match_idx];
2464                                                 break;
2465                                         } else
2466                                                 continue;
2467                                 }
2468                         }
2469
2470                         if (method == null)
2471                                 return null;
2472                         
2473                         // And now convert implicitly, each argument to the required type
2474                         
2475                         pd = GetParameterData (method);
2476                         int pd_count = pd.Count;
2477
2478                         for (int j = 0; j < argument_count; j++) {
2479
2480                                 Argument a = (Argument) Arguments [j];
2481                                 Expression a_expr = a.Expr;
2482                                 Type parameter_type = pd.ParameterType (j);
2483
2484                                 //
2485                                 // Note that we need to compare against the element type
2486                                 // when we have a params method
2487                                 //
2488                                 if (pd.ParameterModifier (pd_count - 1) == Parameter.Modifier.PARAMS) {
2489                                         if (j >= pd_count - 1) 
2490                                                 parameter_type = pd.ParameterType (pd_count - 1).GetElementType ();
2491                                 }
2492
2493                                 if (a.Type != parameter_type){
2494                                         Expression conv;
2495                                         
2496                                         if (use_standard)
2497                                                 conv = ConvertImplicitStandard (ec, a_expr, parameter_type, Location.Null);
2498                                         else
2499                                                 conv = ConvertImplicit (ec, a_expr, parameter_type, Location.Null);
2500
2501                                         if (conv == null) {
2502                                                 if (!Location.IsNull (loc)) {
2503                                                         Error (1502, loc,
2504                                                         "The best overloaded match for method '" + FullMethodDesc (method)+
2505                                                                "' has some invalid arguments");
2506                                                         Error (1503, loc,
2507                                                          "Argument " + (j+1) +
2508                                                          ": Cannot convert from '" + Argument.FullDesc (a) 
2509                                                          + "' to '" + pd.ParameterDesc (j) + "'");
2510                                                 }
2511                                                 return null;
2512                                         }
2513                                         
2514                         
2515                                         
2516                                         //
2517                                         // Update the argument with the implicit conversion
2518                                         //
2519                                         if (a_expr != conv)
2520                                                 a.Expr = conv;
2521
2522                                         // FIXME : For the case of params methods, we need to actually instantiate
2523                                         // an array and initialize it with the argument values etc etc.
2524
2525                                 }
2526                                 
2527                                 if (a.GetParameterModifier () != pd.ParameterModifier (j) &&
2528                                     pd.ParameterModifier (j) != Parameter.Modifier.PARAMS) {
2529                                         if (!Location.IsNull (loc)) {
2530                                                 Error (1502, loc,
2531                                                        "The best overloaded match for method '" + FullMethodDesc (method)+
2532                                                        "' has some invalid arguments");
2533                                                 Error (1503, loc,
2534                                                        "Argument " + (j+1) +
2535                                                        ": Cannot convert from '" + Argument.FullDesc (a) 
2536                                                        + "' to '" + pd.ParameterDesc (j) + "'");
2537                                         }
2538                                         return null;
2539                                 }
2540                                 
2541                                 
2542                         }
2543                         
2544                         return method;
2545                 }
2546                 
2547                 public static MethodBase OverloadResolve (EmitContext ec, MethodGroupExpr me,
2548                                                           ArrayList Arguments, Location loc)
2549                 {
2550                         return OverloadResolve (ec, me, Arguments, loc, false);
2551                 }
2552                         
2553                 public override Expression DoResolve (EmitContext ec)
2554                 {
2555                         //
2556                         // First, resolve the expression that is used to
2557                         // trigger the invocation
2558                         //
2559                         expr = expr.Resolve (ec);
2560                         if (expr == null)
2561                                 return null;
2562
2563                         if (!(expr is MethodGroupExpr)) {
2564                                 Type expr_type = expr.Type;
2565
2566                                 if (expr_type != null){
2567                                         bool IsDelegate = TypeManager.IsDelegateType (expr_type);
2568                                         if (IsDelegate)
2569                                                 return (new DelegateInvocation (
2570                                                         this.expr, Arguments, loc)).Resolve (ec);
2571                                 }
2572                         }
2573
2574                         if (!(expr is MethodGroupExpr)){
2575                                 report118 (loc, this.expr, "method group");
2576                                 return null;
2577                         }
2578
2579                         //
2580                         // Next, evaluate all the expressions in the argument list
2581                         //
2582                         if (Arguments != null){
2583                                 for (int i = Arguments.Count; i > 0;){
2584                                         --i;
2585                                         Argument a = (Argument) Arguments [i];
2586
2587                                         if (!a.Resolve (ec, loc))
2588                                                 return null;
2589                                 }
2590                         }
2591
2592                         method = OverloadResolve (ec, (MethodGroupExpr) this.expr, Arguments, loc);
2593
2594                         if (method == null){
2595                                 Error (-6, loc,
2596                                        "Could not find any applicable function for this argument list");
2597                                 return null;
2598                         }
2599
2600                         if (method is MethodInfo)
2601                                 type = ((MethodInfo)method).ReturnType;
2602
2603                         eclass = ExprClass.Value;
2604                         return this;
2605                 }
2606
2607                 // <summary>
2608                 //   Emits the list of arguments as an array
2609                 // </summary>
2610                 static void EmitParams (EmitContext ec, int idx, ArrayList arguments)
2611                 {
2612                         ILGenerator ig = ec.ig;
2613                         int count = arguments.Count - idx;
2614                         Argument a = (Argument) arguments [idx];
2615                         Type t = a.expr.Type;
2616                         string array_type = t.FullName + "[]";
2617                         LocalBuilder array;
2618                         
2619                         array = ig.DeclareLocal (Type.GetType (array_type));
2620                         IntLiteral.EmitInt (ig, count);
2621                         ig.Emit (OpCodes.Newarr, t);
2622                         ig.Emit (OpCodes.Stloc, array);
2623
2624                         int top = arguments.Count;
2625                         for (int j = idx; j < top; j++){
2626                                 a = (Argument) arguments [j];
2627                                 
2628                                 ig.Emit (OpCodes.Ldloc, array);
2629                                 IntLiteral.EmitInt (ig, j - idx);
2630                                 a.Emit (ec);
2631                                 
2632                                 ArrayAccess.EmitStoreOpcode (ig, t);
2633                         }
2634                         ig.Emit (OpCodes.Ldloc, array);
2635                 }
2636                 
2637                 /// <summary>
2638                 ///   Emits a list of resolved Arguments that are in the arguments
2639                 ///   ArrayList.
2640                 /// 
2641                 ///   The MethodBase argument might be null if the
2642                 ///   emission of the arguments is known not to contain
2643                 ///   a `params' field (for example in constructors or other routines
2644                 ///   that keep their arguments in this structure
2645                 /// </summary>
2646                 public static void EmitArguments (EmitContext ec, MethodBase mb, ArrayList arguments)
2647                 {
2648                         ParameterData pd = null;
2649                         int top;
2650
2651                         if (arguments != null)
2652                                 top = arguments.Count;
2653                         else
2654                                 top = 0;
2655
2656                         if (mb != null)
2657                                  pd = GetParameterData (mb);
2658
2659                         for (int i = 0; i < top; i++){
2660                                 Argument a = (Argument) arguments [i];
2661
2662                                 if (pd != null){
2663                                         if (pd.ParameterModifier (i) == Parameter.Modifier.PARAMS){
2664                                                 EmitParams (ec, i, arguments);
2665                                                 return;
2666                                         }
2667                                 }
2668                                             
2669                                 a.Emit (ec);
2670                         }
2671                 }
2672
2673                 public static void EmitCall (EmitContext ec,
2674                                              bool is_static, Expression instance_expr,
2675                                              MethodBase method, ArrayList Arguments)
2676                 {
2677                         ILGenerator ig = ec.ig;
2678                         bool struct_call = false;
2679                                 
2680                         if (!is_static){
2681                                 //
2682                                 // If this is ourselves, push "this"
2683                                 //
2684                                 if (instance_expr == null){
2685                                         ig.Emit (OpCodes.Ldarg_0);
2686                                 } else {
2687                                         //
2688                                         // Push the instance expression
2689                                         //
2690                                         if (instance_expr.Type.IsSubclassOf (TypeManager.value_type)){
2691
2692                                                 struct_call = true;
2693
2694                                                 //
2695                                                 // If the expression implements IMemoryLocation, then
2696                                                 // we can optimize and use AddressOf on the
2697                                                 // return.
2698                                                 //
2699                                                 // If not we have to use some temporary storage for
2700                                                 // it.
2701                                                 if (instance_expr is IMemoryLocation)
2702                                                         ((IMemoryLocation) instance_expr).AddressOf (ec);
2703                                                 else {
2704                                                         Type t = instance_expr.Type;
2705                                                         
2706                                                         instance_expr.Emit (ec);
2707                                                         LocalBuilder temp = ig.DeclareLocal (t);
2708                                                         ig.Emit (OpCodes.Stloc, temp);
2709                                                         ig.Emit (OpCodes.Ldloca, temp);
2710                                                 }
2711                                         } else 
2712                                                 instance_expr.Emit (ec);
2713                                 }
2714                         }
2715
2716                         if (Arguments != null)
2717                                 EmitArguments (ec, method, Arguments);
2718
2719                         if (is_static || struct_call){
2720                                 if (method is MethodInfo)
2721                                         ig.Emit (OpCodes.Call, (MethodInfo) method);
2722                                 else
2723                                         ig.Emit (OpCodes.Call, (ConstructorInfo) method);
2724                         } else {
2725                                 if (method is MethodInfo)
2726                                         ig.Emit (OpCodes.Callvirt, (MethodInfo) method);
2727                                 else
2728                                         ig.Emit (OpCodes.Callvirt, (ConstructorInfo) method);
2729                         }
2730                 }
2731                 
2732                 public override void Emit (EmitContext ec)
2733                 {
2734                         MethodGroupExpr mg = (MethodGroupExpr) this.expr;
2735                         EmitCall (ec, method.IsStatic, mg.InstanceExpression, method, Arguments);
2736                 }
2737                 
2738                 public override void EmitStatement (EmitContext ec)
2739                 {
2740                         Emit (ec);
2741
2742                         // 
2743                         // Pop the return value if there is one
2744                         //
2745                         if (method is MethodInfo){
2746                                 if (((MethodInfo)method).ReturnType != TypeManager.void_type)
2747                                         ec.ig.Emit (OpCodes.Pop);
2748                         }
2749                 }
2750         }
2751
2752         /// <summary>
2753         ///    Implements the new expression 
2754         /// </summary>
2755         public class New : ExpressionStatement {
2756                 public readonly ArrayList Arguments;
2757                 public readonly string    RequestedType;
2758
2759                 Location loc;
2760                 MethodBase method = null;
2761
2762                 //
2763                 // If set, the new expression is for a value_target, and
2764                 // we will not leave anything on the stack.
2765                 //
2766                 Expression value_target;
2767                 
2768                 public New (string requested_type, ArrayList arguments, Location l)
2769                 {
2770                         RequestedType = requested_type;
2771                         Arguments = arguments;
2772                         loc = l;
2773                 }
2774
2775                 public Expression ValueTypeVariable {
2776                         get {
2777                                 return value_target;
2778                         }
2779
2780                         set {
2781                                 value_target = value;
2782                         }
2783                 }
2784
2785                 public override Expression DoResolve (EmitContext ec)
2786                 {
2787                         type = ec.TypeContainer.LookupType (RequestedType, false);
2788                         
2789                         if (type == null)
2790                                 return null;
2791                         
2792                         bool IsDelegate = TypeManager.IsDelegateType (type);
2793                         
2794                         if (IsDelegate)
2795                                 return (new NewDelegate (type, Arguments, loc)).Resolve (ec);
2796                         
2797                         Expression ml;
2798                         
2799                         ml = MemberLookup (ec, type, ".ctor", false,
2800                                            MemberTypes.Constructor, AllBindingsFlags, loc);
2801                         
2802                         bool is_struct = false;
2803                         is_struct = type.IsSubclassOf (TypeManager.value_type);
2804                         
2805                         if (! (ml is MethodGroupExpr)){
2806                                 if (!is_struct){
2807                                         report118 (loc, ml, "method group");
2808                                         return null;
2809                                 }
2810                         }
2811                         
2812                         if (ml != null) {
2813                                 if (Arguments != null){
2814                                         for (int i = Arguments.Count; i > 0;){
2815                                                 --i;
2816                                                 Argument a = (Argument) Arguments [i];
2817                                                 
2818                                                 if (!a.Resolve (ec, loc))
2819                                                         return null;
2820                                         }
2821                                 }
2822
2823                                 method = Invocation.OverloadResolve (ec, (MethodGroupExpr) ml,
2824                                                                      Arguments, loc);
2825                         }
2826                         
2827                         if (method == null && !is_struct) {
2828                                 Error (-6, loc,
2829                                        "New invocation: Can not find a constructor for " +
2830                                        "this argument list");
2831                                 return null;
2832                         }
2833                         
2834                         eclass = ExprClass.Value;
2835                         return this;
2836                 }
2837
2838                 //
2839                 // This DoEmit can be invoked in two contexts:
2840                 //    * As a mechanism that will leave a value on the stack (new object)
2841                 //    * As one that wont (init struct)
2842                 //
2843                 // You can control whether a value is required on the stack by passing
2844                 // need_value_on_stack.  The code *might* leave a value on the stack
2845                 // so it must be popped manually
2846                 //
2847                 // Returns whether a value is left on the stack
2848                 //
2849                 bool DoEmit (EmitContext ec, bool need_value_on_stack)
2850                 {
2851                         if (method == null){
2852                                 IMemoryLocation ml = (IMemoryLocation) value_target;
2853
2854                                 ml.AddressOf (ec);
2855                         } else {
2856                                 Invocation.EmitArguments (ec, method, Arguments);
2857                                 ec.ig.Emit (OpCodes.Newobj, (ConstructorInfo) method);
2858                                 return true;
2859                         }
2860
2861                         //
2862                         // It must be a value type, sanity check
2863                         //
2864                         if (value_target != null){
2865                                 ec.ig.Emit (OpCodes.Initobj, type);
2866
2867                                 if (need_value_on_stack){
2868                                         value_target.Emit (ec);
2869                                         return true;
2870                                 }
2871                                 return false;
2872                         }
2873
2874                         throw new Exception ("No method and no value type");
2875                 }
2876
2877                 public override void Emit (EmitContext ec)
2878                 {
2879                         DoEmit (ec, true);
2880                 }
2881                 
2882                 public override void EmitStatement (EmitContext ec)
2883                 {
2884                         if (DoEmit (ec, false))
2885                                 ec.ig.Emit (OpCodes.Pop);
2886                 }
2887         }
2888
2889         /// <summary>
2890         ///   Represents an array creation expression.
2891         /// </summary>
2892         ///
2893         /// <remarks>
2894         ///   There are two possible scenarios here: one is an array creation
2895         ///   expression that specifies the dimensions and optionally the
2896         ///   initialization data
2897         /// </remarks>
2898         public class ArrayCreation : ExpressionStatement {
2899
2900                 string RequestedType;
2901                 string Rank;
2902                 ArrayList Initializers;
2903                 Location  loc;
2904                 ArrayList Arguments;
2905
2906                 MethodBase method = null;
2907                 Type array_element_type;
2908                 bool IsOneDimensional = false;
2909                 
2910                 bool IsBuiltinType = false;
2911
2912                 int dimensions = 0;
2913                 Type underlying_type;
2914
2915                 ArrayList ArrayData;
2916
2917                 public ArrayCreation (string requested_type, ArrayList exprs,
2918                                       string rank, ArrayList initializers, Location l)
2919                 {
2920                         RequestedType = requested_type;
2921                         Rank          = rank;
2922                         Initializers  = initializers;
2923                         loc = l;
2924
2925                         Arguments = new ArrayList ();
2926
2927                         foreach (Expression e in exprs)
2928                                 Arguments.Add (new Argument (e, Argument.AType.Expression));
2929                         
2930                 }
2931
2932                 public ArrayCreation (string requested_type, string rank, ArrayList initializers, Location l)
2933                 {
2934                         RequestedType = requested_type;
2935                         Initializers = initializers;
2936                         loc = l;
2937
2938                         Rank = rank.Substring (0, rank.LastIndexOf ("["));
2939
2940                         string tmp = rank.Substring (rank.LastIndexOf ("["));
2941
2942                         dimensions = tmp.Length - 1;
2943                 }
2944
2945                 public static string FormArrayType (string base_type, int idx_count, string rank)
2946                 {
2947                         StringBuilder sb = new StringBuilder (base_type);
2948
2949                         sb.Append (rank);
2950                         
2951                         sb.Append ("[");
2952                         for (int i = 1; i < idx_count; i++)
2953                                 sb.Append (",");
2954                         sb.Append ("]");
2955                         
2956                         return sb.ToString ();
2957                 }
2958
2959                 public static string FormElementType (string base_type, int idx_count, string rank)
2960                 {
2961                         StringBuilder sb = new StringBuilder (base_type);
2962                         
2963                         sb.Append ("[");
2964                         for (int i = 1; i < idx_count; i++)
2965                                 sb.Append (",");
2966                         sb.Append ("]");
2967
2968                         sb.Append (rank);
2969
2970                         string val = sb.ToString ();
2971
2972                         return val.Substring (0, val.LastIndexOf ("["));
2973                 }
2974
2975                 void error178 ()
2976                 {
2977                         Report.Error (178, loc, "Incorrectly structured array initializer");
2978                 }
2979
2980                 public bool CheckIndices (EmitContext ec, ArrayList probe, int idx,
2981                                           bool require_constant, bool unspecified_dims)
2982                 {
2983                         foreach (object o in probe) {
2984                                 
2985                                 if (o is ArrayList) {
2986
2987                                         if (!unspecified_dims) { 
2988                                                 Argument a = (Argument) Arguments [idx];
2989                                                 
2990                                                 if (!a.Resolve (ec, loc))
2991                                                         return false;
2992                                                 
2993                                                 Expression e = Expression.Reduce (ec, a.Expr);
2994                                                 
2995                                                 if (!(e is Literal) && require_constant) {
2996                                                         Report.Error (150, loc, "A constant value is expected");
2997                                                         return false;
2998                                                 }
2999                                                 
3000                                                 int value = (int) ((Literal) e).GetValue ();
3001                                                 
3002                                                 if (value != probe.Count) {
3003                                                         error178 ();
3004                                                         return false;
3005                                                 }
3006                                         }
3007
3008                                         bool ret = CheckIndices (ec, (ArrayList) o, ++idx,
3009                                                                  require_constant, unspecified_dims);
3010                                         if (!ret)
3011                                                 return false;
3012                                         
3013                                 } else {
3014                                         
3015                                         Expression tmp = (Expression) o;
3016                                         tmp = tmp.Resolve (ec);
3017                                         tmp = Expression.Reduce (ec, tmp);
3018                                         
3019                                         if (!(tmp is Literal) && require_constant) {
3020                                                 Report.Error (150, loc, "A constant value is expected");
3021                                                 return false;
3022                                         }
3023                                         
3024                                         Expression conv = ConvertImplicitRequired (ec, tmp,
3025                                                                                    underlying_type, loc);
3026                                         
3027                                         if (conv == null)
3028                                                 return false;
3029
3030                                         ArrayData.Add (((Literal) tmp).GetValue ());
3031                                 }
3032                         }
3033
3034                         return true;
3035                 }
3036                 
3037                 public void UpdateIndices (EmitContext ec)
3038                 {                       
3039                         for (ArrayList probe = Initializers; probe != null;) {
3040
3041                                 if (probe [0] is ArrayList) {
3042                                         Expression e = new IntLiteral (probe.Count);
3043                                         Arguments.Add (new Argument (e, Argument.AType.Expression));
3044
3045                                         probe = (ArrayList) probe [0];
3046                                         
3047                                 } else {
3048                                         Expression e = new IntLiteral (probe.Count);
3049                                         Arguments.Add (new Argument (e, Argument.AType.Expression));
3050                                         
3051                                         probe = null;
3052                                 }
3053                         }
3054
3055                 }
3056                 
3057                 public bool ValidateInitializers (EmitContext ec)
3058                 {
3059                         if (Initializers == null)
3060                                 return true;
3061                         
3062                         underlying_type = ec.TypeContainer.LookupType (RequestedType, false);
3063
3064                         //
3065                         // We use this to store all the date values in the order in which we
3066                         // will need to store them in the byte blob later
3067                         //
3068                         ArrayData = new ArrayList ();
3069                         
3070                         bool ret;
3071                         
3072                         if (Arguments != null) {
3073                                 ret = CheckIndices (ec, Initializers, 0, true, false);
3074                                 return ret;
3075                                 
3076                         } else {
3077                                 Arguments = new ArrayList ();
3078
3079                                 ret = CheckIndices (ec, Initializers, 0, true, true);
3080                                 if (!ret)
3081                                         return false;
3082                                 
3083                                 UpdateIndices (ec);
3084                                 
3085                                 if (Arguments.Count != dimensions) {
3086                                         error178 ();
3087                                         return false;
3088                                 }
3089                                 
3090                                 return ret;
3091                         }
3092                 }
3093                 
3094                 public override Expression DoResolve (EmitContext ec)
3095                 {
3096                         int arg_count;
3097
3098                         if (!ValidateInitializers (ec))
3099                                 return null;
3100
3101                         if (Arguments == null)
3102                                 arg_count = 0;
3103                         else
3104                                 arg_count = Arguments.Count;
3105                         
3106                         string array_type = FormArrayType (RequestedType, arg_count, Rank);
3107
3108                         string element_type = FormElementType (RequestedType, arg_count, Rank);
3109
3110                         type = ec.TypeContainer.LookupType (array_type, false);
3111                         
3112                         array_element_type = ec.TypeContainer.LookupType (element_type, false);
3113                         
3114                         if (type == null)
3115                                 return null;
3116                         
3117                         if (arg_count == 1) {
3118                                 IsOneDimensional = true;
3119                                 eclass = ExprClass.Value;
3120                                 return this;
3121                         }
3122
3123                         IsBuiltinType = TypeManager.IsBuiltinType (type);
3124                         
3125                         if (IsBuiltinType) {
3126                                 
3127                                 Expression ml;
3128                                 
3129                                 ml = MemberLookup (ec, type, ".ctor", false, MemberTypes.Constructor,
3130                                                    AllBindingsFlags, loc);
3131                                 
3132                                 if (!(ml is MethodGroupExpr)){
3133                                         report118 (loc, ml, "method group");
3134                                         return null;
3135                                 }
3136                                 
3137                                 if (ml == null) {
3138                                         Report.Error (-6, loc, "New invocation: Can not find a constructor for " +
3139                                                       "this argument list");
3140                                         return null;
3141                                 }
3142                                 
3143                                 if (Arguments != null) {
3144                                         for (int i = arg_count; i > 0;){
3145                                                 --i;
3146                                                 Argument a = (Argument) Arguments [i];
3147                                                 
3148                                                 if (!a.Resolve (ec, loc))
3149                                                         return null;
3150                                         }
3151                                 }
3152                                 
3153                                 method = Invocation.OverloadResolve (ec, (MethodGroupExpr) ml, Arguments, loc);
3154                                 
3155                                 if (method == null) {
3156                                         Report.Error (-6, loc, "New invocation: Can not find a constructor for " +
3157                                                       "this argument list");
3158                                         return null;
3159                                 }
3160                                 
3161                                 eclass = ExprClass.Value;
3162                                 return this;
3163                                 
3164                         } else {
3165
3166                                 ModuleBuilder mb = ec.TypeContainer.RootContext.ModuleBuilder;
3167
3168                                 ArrayList args = new ArrayList ();
3169                                 if (Arguments != null){
3170                                         for (int i = arg_count; i > 0;){
3171                                                 --i;
3172                                                 Argument a = (Argument) Arguments [i];
3173                                                 
3174                                                 if (!a.Resolve (ec, loc))
3175                                                         return null;
3176                                                 
3177                                                 args.Add (a.Type);
3178                                         }
3179                                 }
3180                                 
3181                                 Type [] arg_types = null;
3182                                 
3183                                 if (args.Count > 0)
3184                                         arg_types = new Type [args.Count];
3185                                 
3186                                 args.CopyTo (arg_types, 0);
3187                                 
3188                                 method = mb.GetArrayMethod (type, ".ctor", CallingConventions.HasThis, null,
3189                                                             arg_types);
3190                                 
3191                                 if (method == null) {
3192                                         Report.Error (-6, loc, "New invocation: Can not find a constructor for " +
3193                                                       "this argument list");
3194                                         return null;
3195                                 }
3196                                 
3197                                 eclass = ExprClass.Value;
3198                                 return this;
3199                                 
3200                         }
3201                 }
3202
3203                 public byte [] MakeByteBlob ()
3204                 {
3205                         int factor;
3206                         byte [] data;
3207
3208                         int count = ArrayData.Count;
3209
3210                         if (underlying_type == TypeManager.int32_type ||
3211                             underlying_type == TypeManager.uint32_type ||
3212                             underlying_type == TypeManager.float_type)
3213                                 factor = 4;
3214                         else if (underlying_type == TypeManager.int64_type ||
3215                                  underlying_type == TypeManager.uint64_type ||
3216                                  underlying_type == TypeManager.double_type)
3217                                 factor = 8;
3218                         else if (underlying_type == TypeManager.byte_type ||
3219                                  underlying_type == TypeManager.sbyte_type ||
3220                                  underlying_type == TypeManager.char_type ||
3221                                  underlying_type == TypeManager.bool_type)      
3222                                 factor = 1;
3223                         else if (underlying_type == TypeManager.short_type ||
3224                                  underlying_type == TypeManager.ushort_type)
3225                                 factor = 2;
3226                         else {  
3227                                 Report.Error (-100, loc, "Unhandled type in MakeByteBlob!!");
3228                                 return null;
3229                         }
3230
3231                         data = new byte [count * factor];
3232                         
3233                         for (int i = 0; i < count; ++i) {
3234                                 int val = (int) ArrayData [i];
3235                                 for (int j = 0; j < factor; ++j) {
3236                                         data [(i * factor) + j] = (byte) (val & 0xFF);
3237                                         val = val >> 8;
3238                                 }
3239                         }
3240                         
3241                         return data;
3242                 }
3243                 
3244                 public override void Emit (EmitContext ec)
3245                 {
3246                         ILGenerator ig = ec.ig;
3247                         
3248                         if (IsOneDimensional) {
3249                                 Invocation.EmitArguments (ec, null, Arguments);
3250                                 ig.Emit (OpCodes.Newarr, array_element_type);
3251                                 
3252                         } else {
3253                                 Invocation.EmitArguments (ec, null, Arguments);
3254
3255                                 if (IsBuiltinType)
3256                                         ig.Emit (OpCodes.Newobj, (ConstructorInfo) method);
3257                                 else
3258                                         ig.Emit (OpCodes.Newobj, (MethodInfo) method);
3259                         }
3260
3261                         if (Initializers != null) {
3262                                 FieldBuilder fb;
3263
3264                                 byte [] data = MakeByteBlob ();
3265
3266                                 if (data != null) {
3267                                         fb = ec.TypeContainer.RootContext.MakeStaticData (data);
3268                                         
3269                                         ig.Emit (OpCodes.Dup);
3270                                         ig.Emit (OpCodes.Ldtoken, fb);
3271                                         ig.Emit (OpCodes.Call, TypeManager.void_initializearray_array_fieldhandle);
3272                                 }
3273                         }
3274                 }
3275                 
3276                 public override void EmitStatement (EmitContext ec)
3277                 {
3278                         Emit (ec);
3279                         ec.ig.Emit (OpCodes.Pop);
3280                 }
3281                 
3282         }
3283         
3284         /// <summary>
3285         ///   Represents the `this' construct
3286         /// </summary>
3287         public class This : Expression, IAssignMethod, IMemoryLocation {
3288                 Location loc;
3289                 
3290                 public This (Location loc)
3291                 {
3292                         this.loc = loc;
3293                 }
3294
3295                 public override Expression DoResolve (EmitContext ec)
3296                 {
3297                         eclass = ExprClass.Variable;
3298                         type = ec.TypeContainer.TypeBuilder;
3299
3300                         if (ec.IsStatic){
3301                                 Report.Error (26, loc,
3302                                               "Keyword this not valid in static code");
3303                                 return null;
3304                         }
3305                         
3306                         return this;
3307                 }
3308
3309                 public Expression DoResolveLValue (EmitContext ec)
3310                 {
3311                         DoResolve (ec);
3312                         
3313                         if (ec.TypeContainer is Class){
3314                                 Report.Error (1604, loc, "Cannot assign to `this'");
3315                                 return null;
3316                         }
3317
3318                         return this;
3319                 }
3320
3321                 public override void Emit (EmitContext ec)
3322                 {
3323                         ec.ig.Emit (OpCodes.Ldarg_0);
3324                 }
3325
3326                 public void EmitAssign (EmitContext ec, Expression source)
3327                 {
3328                         source.Emit (ec);
3329                         ec.ig.Emit (OpCodes.Starg, 0);
3330                 }
3331
3332                 public void AddressOf (EmitContext ec)
3333                 {
3334                         ec.ig.Emit (OpCodes.Ldarga_S, (byte) 0);
3335                 }
3336         }
3337
3338         /// <summary>
3339         ///   Implements the typeof operator
3340         /// </summary>
3341         public class TypeOf : Expression {
3342                 public readonly string QueriedType;
3343                 Type typearg;
3344                 
3345                 public TypeOf (string queried_type)
3346                 {
3347                         QueriedType = queried_type;
3348                 }
3349
3350                 public override Expression DoResolve (EmitContext ec)
3351                 {
3352                         typearg = ec.TypeContainer.LookupType (QueriedType, false);
3353
3354                         if (typearg == null)
3355                                 return null;
3356
3357                         type = TypeManager.type_type;
3358                         eclass = ExprClass.Type;
3359                         return this;
3360                 }
3361
3362                 public override void Emit (EmitContext ec)
3363                 {
3364                         ec.ig.Emit (OpCodes.Ldtoken, typearg);
3365                         ec.ig.Emit (OpCodes.Call, TypeManager.system_type_get_type_from_handle);
3366                 }
3367         }
3368
3369         /// <summary>
3370         ///   Implements the sizeof expression
3371         /// </summary>
3372         public class SizeOf : Expression {
3373                 public readonly string QueriedType;
3374                 
3375                 public SizeOf (string queried_type)
3376                 {
3377                         this.QueriedType = queried_type;
3378                 }
3379
3380                 public override Expression DoResolve (EmitContext ec)
3381                 {
3382                         // FIXME: Implement;
3383                         throw new Exception ("Unimplemented");
3384                         // return this;
3385                 }
3386
3387                 public override void Emit (EmitContext ec)
3388                 {
3389                         throw new Exception ("Implement me");
3390                 }
3391         }
3392
3393         /// <summary>
3394         ///   Implements the member access expression
3395         /// </summary>
3396         public class MemberAccess : Expression {
3397                 public readonly string Identifier;
3398                 Expression expr;
3399                 Expression member_lookup;
3400                 Location loc;
3401                 
3402                 public MemberAccess (Expression expr, string id, Location l)
3403                 {
3404                         this.expr = expr;
3405                         Identifier = id;
3406                         loc = l;
3407                 }
3408
3409                 public Expression Expr {
3410                         get {
3411                                 return expr;
3412                         }
3413                 }
3414
3415                 void error176 (Location loc, string name)
3416                 {
3417                         Report.Error (176, loc, "Static member `" +
3418                                       name + "' cannot be accessed " +
3419                                       "with an instance reference, qualify with a " +
3420                                       "type name instead");
3421                 }
3422                 
3423                 public override Expression DoResolve (EmitContext ec)
3424                 {
3425                         //
3426                         // We are the sole users of ResolveWithSimpleName (ie, the only
3427                         // ones that can cope with it
3428                         //
3429                         expr = expr.ResolveWithSimpleName (ec);
3430
3431                         if (expr == null)
3432                                 return null;
3433
3434                         if (expr is SimpleName){
3435                                 SimpleName child_expr = (SimpleName) expr;
3436
3437                                 expr = new SimpleName (child_expr.Name + "." + Identifier, loc);
3438
3439                                 return expr.Resolve (ec);
3440                         }
3441                                         
3442                         member_lookup = MemberLookup (ec, expr.Type, Identifier, false, loc);
3443
3444                         if (member_lookup == null)
3445                                 return null;
3446                         
3447                         //
3448                         // Method Groups
3449                         //
3450                         if (member_lookup is MethodGroupExpr){
3451                                 MethodGroupExpr mg = (MethodGroupExpr) member_lookup;
3452                                 
3453                                 //
3454                                 // Type.MethodGroup
3455                                 //
3456                                 if (expr is TypeExpr){
3457                                         if (!mg.RemoveInstanceMethods ()){
3458                                                 SimpleName.Error120 (loc, mg.Methods [0].Name); 
3459                                                 return null;
3460                                         }
3461
3462                                         return member_lookup;
3463                                 }
3464
3465                                 //
3466                                 // Instance.MethodGroup
3467                                 //
3468                                 if (!mg.RemoveStaticMethods ()){
3469                                         error176 (loc, mg.Methods [0].Name);
3470                                         return null;
3471                                 }
3472                                 
3473                                 mg.InstanceExpression = expr;
3474                                         
3475                                 return member_lookup;
3476                         }
3477
3478                         if (member_lookup is FieldExpr){
3479                                 FieldExpr fe = (FieldExpr) member_lookup;
3480                                 FieldInfo fi = fe.FieldInfo;
3481
3482                                 if (fi.IsLiteral) {
3483                                         Type t = fi.FieldType;
3484                                         object o;
3485
3486                                         if (fi is FieldBuilder)
3487                                                 o = TypeManager.GetValue ((FieldBuilder) fi);
3488                                         else
3489                                                 o = fi.GetValue (fi);
3490                                         
3491                                         if (t.IsSubclassOf (TypeManager.enum_type)) {
3492                                                 Expression enum_member = MemberLookup (ec, t, "value__", false, loc); 
3493                                                 Type underlying_type = enum_member.Type;
3494                                                 
3495                                                 Expression e = Literalize (o, underlying_type);
3496                                                 e.Resolve (ec);
3497                                         
3498                                                 return new EnumLiteral (e, t);
3499                                         }
3500
3501                                         Expression exp = Literalize (o, t);
3502                                         exp.Resolve (ec);
3503                                         
3504                                         return exp;
3505                                 }
3506                                 
3507                                 if (expr is TypeExpr){
3508                                         if (!fe.FieldInfo.IsStatic){
3509                                                 error176 (loc, fe.FieldInfo.Name);
3510                                                 return null;
3511                                         }
3512                                         return member_lookup;
3513                                 } else {
3514                                         if (fe.FieldInfo.IsStatic){
3515                                                 error176 (loc, fe.FieldInfo.Name);
3516                                                 return null;
3517                                         }
3518                                         fe.InstanceExpression = expr;
3519
3520                                         return fe;
3521                                 }
3522                         }
3523
3524                         if (member_lookup is PropertyExpr){
3525                                 PropertyExpr pe = (PropertyExpr) member_lookup;
3526
3527                                 if (expr is TypeExpr){
3528                                         if (!pe.IsStatic){
3529                                                 SimpleName.Error120 (loc, pe.PropertyInfo.Name);
3530                                                 return null;
3531                                         }
3532                                         return pe;
3533                                 } else {
3534                                         if (pe.IsStatic){
3535                                                 error176 (loc, pe.PropertyInfo.Name);
3536                                                 return null;
3537                                         }
3538                                         pe.InstanceExpression = expr;
3539
3540                                         return pe;
3541                                 }
3542                         }
3543                         
3544                         Console.WriteLine ("Support for [" + member_lookup + "] is not present yet");
3545                         Environment.Exit (0);
3546                         return null;
3547                 }
3548
3549                 public override void Emit (EmitContext ec)
3550                 {
3551                         throw new Exception ("Should not happen I think");
3552                 }
3553         }
3554
3555         /// <summary>
3556         ///   Implements checked expressions
3557         /// </summary>
3558         public class CheckedExpr : Expression {
3559
3560                 public Expression Expr;
3561
3562                 public CheckedExpr (Expression e)
3563                 {
3564                         Expr = e;
3565                 }
3566
3567                 public override Expression DoResolve (EmitContext ec)
3568                 {
3569                         Expr = Expr.Resolve (ec);
3570
3571                         if (Expr == null)
3572                                 return null;
3573
3574                         eclass = Expr.ExprClass;
3575                         type = Expr.Type;
3576                         return this;
3577                 }
3578
3579                 public override void Emit (EmitContext ec)
3580                 {
3581                         bool last_check = ec.CheckState;
3582                         
3583                         ec.CheckState = true;
3584                         Expr.Emit (ec);
3585                         ec.CheckState = last_check;
3586                 }
3587                 
3588         }
3589
3590         /// <summary>
3591         ///   Implements the unchecked expression
3592         /// </summary>
3593         public class UnCheckedExpr : Expression {
3594
3595                 public Expression Expr;
3596
3597                 public UnCheckedExpr (Expression e)
3598                 {
3599                         Expr = e;
3600                 }
3601
3602                 public override Expression DoResolve (EmitContext ec)
3603                 {
3604                         Expr = Expr.Resolve (ec);
3605
3606                         if (Expr == null)
3607                                 return null;
3608
3609                         eclass = Expr.ExprClass;
3610                         type = Expr.Type;
3611                         return this;
3612                 }
3613
3614                 public override void Emit (EmitContext ec)
3615                 {
3616                         bool last_check = ec.CheckState;
3617                         
3618                         ec.CheckState = false;
3619                         Expr.Emit (ec);
3620                         ec.CheckState = last_check;
3621                 }
3622                 
3623         }
3624
3625         /// <summary>
3626         ///   An Element Access expression.  During semantic
3627         ///   analysis these are transformed into IndexerAccess or
3628         ///   ArrayAccess expressions
3629         /// </summary>
3630         public class ElementAccess : Expression {
3631                 public ArrayList  Arguments;
3632                 public Expression Expr;
3633                 public Location   loc;
3634                 
3635                 public ElementAccess (Expression e, ArrayList e_list, Location l)
3636                 {
3637                         Expr = e;
3638
3639                         Arguments = new ArrayList ();
3640                         foreach (Expression tmp in e_list)
3641                                 Arguments.Add (new Argument (tmp, Argument.AType.Expression));
3642                         
3643                         loc  = l;
3644                 }
3645
3646                 bool CommonResolve (EmitContext ec)
3647                 {
3648                         Expr = Expr.Resolve (ec);
3649
3650                         if (Expr == null) 
3651                                 return false;
3652
3653                         if (Arguments == null)
3654                                 return false;
3655
3656                         for (int i = Arguments.Count; i > 0;){
3657                                 --i;
3658                                 Argument a = (Argument) Arguments [i];
3659                                 
3660                                 if (!a.Resolve (ec, loc))
3661                                         return false;
3662                         }
3663
3664                         return true;
3665                 }
3666                                 
3667                 public override Expression DoResolve (EmitContext ec)
3668                 {
3669                         if (!CommonResolve (ec))
3670                                 return null;
3671
3672                         //
3673                         // We perform some simple tests, and then to "split" the emit and store
3674                         // code we create an instance of a different class, and return that.
3675                         //
3676                         // I am experimenting with this pattern.
3677                         //
3678                         if (Expr.Type.IsSubclassOf (TypeManager.array_type))
3679                                 return (new ArrayAccess (this)).Resolve (ec);
3680                         else
3681                                 return (new IndexerAccess (this)).Resolve (ec);
3682                 }
3683
3684                 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
3685                 {
3686                         if (!CommonResolve (ec))
3687                                 return null;
3688
3689                         if (Expr.Type.IsSubclassOf (TypeManager.array_type))
3690                                 return (new ArrayAccess (this)).ResolveLValue (ec, right_side);
3691                         else
3692                                 return (new IndexerAccess (this)).ResolveLValue (ec, right_side);
3693                 }
3694                 
3695                 public override void Emit (EmitContext ec)
3696                 {
3697                         throw new Exception ("Should never be reached");
3698                 }
3699         }
3700
3701         /// <summary>
3702         ///   Implements array access 
3703         /// </summary>
3704         public class ArrayAccess : Expression, IAssignMethod {
3705                 //
3706                 // Points to our "data" repository
3707                 //
3708                 ElementAccess ea;
3709                 
3710                 public ArrayAccess (ElementAccess ea_data)
3711                 {
3712                         ea = ea_data;
3713                         eclass = ExprClass.Variable;
3714                 }
3715
3716                 public override Expression DoResolve (EmitContext ec)
3717                 {
3718                         if (ea.Expr.ExprClass != ExprClass.Variable) {
3719                                 report118 (ea.loc, ea.Expr, "variable");
3720                                 return null;
3721                         }
3722
3723                         Type t = ea.Expr.Type;
3724
3725                         if (t.GetArrayRank () != ea.Arguments.Count){
3726                                 Report.Error (22, ea.loc,
3727                                               "Incorrect number of indexes for array " +
3728                                               " expected: " + t.GetArrayRank () + " got: " +
3729                                               ea.Arguments.Count);
3730                                 return null;
3731                         }
3732                         type = t.GetElementType ();
3733                         eclass = ExprClass.Variable;
3734
3735                         return this;
3736                 }
3737
3738                 /// <summary>
3739                 ///    Emits the right opcode to load an object of Type `t'
3740                 ///    from an array of T
3741                 /// </summary>
3742                 static public void EmitLoadOpcode (ILGenerator ig, Type type)
3743                 {
3744                         if (type == TypeManager.byte_type)
3745                                 ig.Emit (OpCodes.Ldelem_I1);
3746                         else if (type == TypeManager.sbyte_type)
3747                                 ig.Emit (OpCodes.Ldelem_U1);
3748                         else if (type == TypeManager.short_type)
3749                                 ig.Emit (OpCodes.Ldelem_I2);
3750                         else if (type == TypeManager.ushort_type)
3751                                 ig.Emit (OpCodes.Ldelem_U2);
3752                         else if (type == TypeManager.int32_type)
3753                                 ig.Emit (OpCodes.Ldelem_I4);
3754                         else if (type == TypeManager.uint32_type)
3755                                 ig.Emit (OpCodes.Ldelem_U4);
3756                         else if (type == TypeManager.uint64_type)
3757                                 ig.Emit (OpCodes.Ldelem_I8);
3758                         else if (type == TypeManager.int64_type)
3759                                 ig.Emit (OpCodes.Ldelem_I8);
3760                         else if (type == TypeManager.float_type)
3761                                 ig.Emit (OpCodes.Ldelem_R4);
3762                         else if (type == TypeManager.double_type)
3763                                 ig.Emit (OpCodes.Ldelem_R8);
3764                         else if (type == TypeManager.intptr_type)
3765                                 ig.Emit (OpCodes.Ldelem_I);
3766                         else
3767                                 ig.Emit (OpCodes.Ldelem_Ref);
3768                 }
3769
3770                 /// <summary>
3771                 ///    Emits the right opcode to store an object of Type `t'
3772                 ///    from an array of T.  
3773                 /// </summary>
3774                 static public void EmitStoreOpcode (ILGenerator ig, Type t)
3775                 {
3776                         if (t == TypeManager.byte_type || t == TypeManager.sbyte_type)
3777                                 ig.Emit (OpCodes.Stelem_I1);
3778                         else if (t == TypeManager.short_type || t == TypeManager.ushort_type)
3779                                 ig.Emit (OpCodes.Stelem_I2);
3780                         else if (t == TypeManager.int32_type || t == TypeManager.uint32_type)
3781                                 ig.Emit (OpCodes.Stelem_I4);
3782                         else if (t == TypeManager.int64_type || t == TypeManager.uint64_type)
3783                                 ig.Emit (OpCodes.Stelem_I8);
3784                         else if (t == TypeManager.float_type)
3785                                 ig.Emit (OpCodes.Stelem_R4);
3786                         else if (t == TypeManager.double_type)
3787                                 ig.Emit (OpCodes.Stelem_R8);
3788                         else if (t == TypeManager.intptr_type)
3789                                 ig.Emit (OpCodes.Stelem_I);
3790                         else
3791                                 ig.Emit (OpCodes.Stelem_Ref);
3792                 }
3793                 
3794                 public override void Emit (EmitContext ec)
3795                 {
3796                         int rank = ea.Expr.Type.GetArrayRank ();
3797                         ILGenerator ig = ec.ig;
3798
3799                         ea.Expr.Emit (ec);
3800
3801                         foreach (Argument a in ea.Arguments)
3802                                 a.Expr.Emit (ec);
3803
3804                         if (rank == 1)
3805                                 EmitLoadOpcode (ig, type);
3806                         else {
3807                                 ModuleBuilder mb = ec.TypeContainer.RootContext.ModuleBuilder;
3808                                 Type [] args = new Type [ea.Arguments.Count];
3809                                 MethodInfo get;
3810                                 
3811                                 int i = 0;
3812                                 
3813                                 foreach (Argument a in ea.Arguments)
3814                                         args [i++] = a.Type;
3815                                 
3816                                 get = mb.GetArrayMethod (
3817                                         ea.Expr.Type, "Get",
3818                                         CallingConventions.HasThis |
3819                                         CallingConventions.Standard,
3820                                         type, args);
3821                                 
3822                                 ig.Emit (OpCodes.Call, get);
3823                         }
3824                 }
3825
3826                 public void EmitAssign (EmitContext ec, Expression source)
3827                 {
3828                         int rank = ea.Expr.Type.GetArrayRank ();
3829                         ILGenerator ig = ec.ig;
3830
3831                         ea.Expr.Emit (ec);
3832
3833                         foreach (Argument a in ea.Arguments)
3834                                 a.Expr.Emit (ec);
3835
3836                         source.Emit (ec);
3837
3838                         Type t = source.Type;
3839                         if (rank == 1)
3840                                 EmitStoreOpcode (ig, t);
3841                         else {
3842                                 ModuleBuilder mb = ec.TypeContainer.RootContext.ModuleBuilder;
3843                                 Type [] args = new Type [ea.Arguments.Count + 1];
3844                                 MethodInfo set;
3845                                 
3846                                 int i = 0;
3847                                 
3848                                 foreach (Argument a in ea.Arguments)
3849                                         args [i++] = a.Type;
3850
3851                                 args [i] = type;
3852                                 
3853                                 set = mb.GetArrayMethod (
3854                                         ea.Expr.Type, "Set",
3855                                         CallingConventions.HasThis |
3856                                         CallingConventions.Standard,
3857                                         TypeManager.void_type, args);
3858                                 
3859                                 ig.Emit (OpCodes.Call, set);
3860                         }
3861                 }
3862         }
3863
3864         
3865         class Indexers {
3866                 public ArrayList getters, setters;
3867                 static Hashtable map;
3868
3869                 static Indexers ()
3870                 {
3871                         map = new Hashtable ();
3872                 }
3873
3874                 Indexers (MemberInfo [] mi)
3875                 {
3876                         foreach (PropertyInfo property in mi){
3877                                 MethodInfo get, set;
3878                                 
3879                                 get = property.GetGetMethod (true);
3880                                 if (get != null){
3881                                         if (getters == null)
3882                                                 getters = new ArrayList ();
3883
3884                                         getters.Add (get);
3885                                 }
3886                                 
3887                                 set = property.GetSetMethod (true);
3888                                 if (set != null){
3889                                         if (setters == null)
3890                                                 setters = new ArrayList ();
3891                                         setters.Add (set);
3892                                 }
3893                         }
3894                 }
3895                 
3896                 static public Indexers GetIndexersForType (Type t, TypeManager tm, Location loc) 
3897                 {
3898                         Indexers ix = (Indexers) map [t];
3899                         string p_name = TypeManager.IndexerPropertyName (t);
3900                         
3901                         if (ix != null)
3902                                 return ix;
3903
3904                         MemberInfo [] mi = tm.FindMembers (
3905                                 t, MemberTypes.Property,
3906                                 BindingFlags.Public | BindingFlags.Instance,
3907                                 Type.FilterName, p_name);
3908
3909                         if (mi == null || mi.Length == 0){
3910                                 Report.Error (21, loc,
3911                                               "Type `" + TypeManager.CSharpName (t) + "' does not have " +
3912                                               "any indexers defined");
3913                                 return null;
3914                         }
3915                         
3916                         ix = new Indexers (mi);
3917                         map [t] = ix;
3918
3919                         return ix;
3920                 }
3921         }
3922
3923         /// <summary>
3924         ///   Expressions that represent an indexer call.
3925         /// </summary>
3926         public class IndexerAccess : Expression, IAssignMethod {
3927                 //
3928                 // Points to our "data" repository
3929                 //
3930                 ElementAccess ea;
3931                 MethodInfo get, set;
3932                 Indexers ilist;
3933                 ArrayList set_arguments;
3934                 
3935                 public IndexerAccess (ElementAccess ea_data)
3936                 {
3937                         ea = ea_data;
3938                         eclass = ExprClass.Value;
3939                 }
3940
3941                 public override Expression DoResolve (EmitContext ec)
3942                 {
3943                         Type indexer_type = ea.Expr.Type;
3944                         
3945                         //
3946                         // Step 1: Query for all `Item' *properties*.  Notice
3947                         // that the actual methods are pointed from here.
3948                         //
3949                         // This is a group of properties, piles of them.  
3950
3951                         if (ilist == null)
3952                                 ilist = Indexers.GetIndexersForType (
3953                                         indexer_type, ec.TypeContainer.RootContext.TypeManager, ea.loc);
3954
3955
3956                         //
3957                         // Step 2: find the proper match
3958                         //
3959                         if (ilist != null && ilist.getters != null && ilist.getters.Count > 0)
3960                                 get = (MethodInfo) Invocation.OverloadResolve (
3961                                         ec, new MethodGroupExpr (ilist.getters), ea.Arguments, ea.loc);
3962
3963                         if (get == null){
3964                                 Report.Error (154, ea.loc,
3965                                               "indexer can not be used in this context, because " +
3966                                               "it lacks a `get' accessor");
3967                                 return null;
3968                         }
3969
3970                         type = get.ReturnType;
3971                         eclass = ExprClass.IndexerAccess;
3972                         return this;
3973                 }
3974
3975                 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
3976                 {
3977                         Type indexer_type = ea.Expr.Type;
3978                         Type right_type = right_side.Type;
3979
3980                         if (ilist == null)
3981                                 ilist = Indexers.GetIndexersForType (
3982                                         indexer_type, ec.TypeContainer.RootContext.TypeManager, ea.loc);
3983
3984                         if (ilist != null && ilist.setters != null && ilist.setters.Count > 0){
3985                                 set_arguments = (ArrayList) ea.Arguments.Clone ();
3986                                 set_arguments.Add (new Argument (right_side, Argument.AType.Expression));
3987
3988                                 set = (MethodInfo) Invocation.OverloadResolve (
3989                                         ec, new MethodGroupExpr (ilist.setters), set_arguments, ea.loc);
3990                         }
3991                         
3992                         if (set == null){
3993                                 Report.Error (200, ea.loc,
3994                                               "indexer X.this [" + TypeManager.CSharpName (right_type) +
3995                                               "] lacks a `set' accessor");
3996                                         return null;
3997                         }
3998
3999                         type = TypeManager.void_type;
4000                         eclass = ExprClass.IndexerAccess;
4001                         return this;
4002                 }
4003                 
4004                 public override void Emit (EmitContext ec)
4005                 {
4006                         Invocation.EmitCall (ec, false, ea.Expr, get, ea.Arguments);
4007                 }
4008
4009                 //
4010                 // source is ignored, because we already have a copy of it from the
4011                 // LValue resolution and we have already constructed a pre-cached
4012                 // version of the arguments (ea.set_arguments);
4013                 //
4014                 public void EmitAssign (EmitContext ec, Expression source)
4015                 {
4016                         Invocation.EmitCall (ec, false, ea.Expr, set, set_arguments);
4017                 }
4018         }
4019         
4020         public class BaseAccess : Expression {
4021
4022                 public enum BaseAccessType : byte {
4023                         Member,
4024                         Indexer
4025                 };
4026                 
4027                 public readonly BaseAccessType BAType;
4028                 public readonly string         Member;
4029                 public readonly ArrayList      Arguments;
4030
4031                 public BaseAccess (BaseAccessType t, string member, ArrayList args)
4032                 {
4033                         BAType = t;
4034                         Member = member;
4035                         Arguments = args;
4036                         
4037                 }
4038
4039                 public override Expression DoResolve (EmitContext ec)
4040                 {
4041                         // FIXME: Implement;
4042                         throw new Exception ("Unimplemented");
4043                         // return this;
4044                 }
4045
4046                 public override void Emit (EmitContext ec)
4047                 {
4048                         throw new Exception ("Unimplemented");
4049                 }
4050         }
4051
4052         /// <summary>
4053         ///   This class exists solely to pass the Type around and to be a dummy
4054         ///   that can be passed to the conversion functions (this is used by
4055         ///   foreach implementation to typecast the object return value from
4056         ///   get_Current into the proper type.  All code has been generated and
4057         ///   we only care about the side effect conversions to be performed
4058         /// </summary>
4059         public class EmptyExpression : Expression {
4060                 public EmptyExpression ()
4061                 {
4062                         type = TypeManager.object_type;
4063                         eclass = ExprClass.Value;
4064                 }
4065
4066                 public EmptyExpression (Type t)
4067                 {
4068                         type = t;
4069                         eclass = ExprClass.Value;
4070                 }
4071                 
4072                 public override Expression DoResolve (EmitContext ec)
4073                 {
4074                         return this;
4075                 }
4076
4077                 public override void Emit (EmitContext ec)
4078                 {
4079                         // nothing, as we only exist to not do anything.
4080                 }
4081         }
4082
4083         public class UserCast : Expression {
4084                 MethodBase method;
4085                 Expression source;
4086                 
4087                 public UserCast (MethodInfo method, Expression source)
4088                 {
4089                         this.method = method;
4090                         this.source = source;
4091                         type = method.ReturnType;
4092                         eclass = ExprClass.Value;
4093                 }
4094
4095                 public override Expression DoResolve (EmitContext ec)
4096                 {
4097                         //
4098                         // We are born fully resolved
4099                         //
4100                         return this;
4101                 }
4102
4103                 public override void Emit (EmitContext ec)
4104                 {
4105                         ILGenerator ig = ec.ig;
4106
4107                         source.Emit (ec);
4108                         
4109                         if (method is MethodInfo)
4110                                 ig.Emit (OpCodes.Call, (MethodInfo) method);
4111                         else
4112                                 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
4113
4114                 }
4115
4116         }
4117 }