0f46a9f25c078617980b410e81264525817f1ac2
[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                         // reload our cached types if required
1226                         //
1227                         l = left.Type;
1228                         r = right.Type;
1229                         
1230                         if (oper == Operator.BitwiseAnd ||
1231                             oper == Operator.BitwiseOr ||
1232                             oper == Operator.ExclusiveOr){
1233                                 if (l == r){
1234                                         if (l.IsSubclassOf (TypeManager.enum_type) ||
1235                                             !((l == TypeManager.int32_type) ||
1236                                               (l == TypeManager.uint32_type) ||
1237                                               (l == TypeManager.int64_type) ||
1238                                               (l == TypeManager.uint64_type)))
1239                                                 type = l;
1240                                 } else {
1241                                         error19 ();
1242                                         return null;
1243                                 }
1244                         }
1245
1246                         if (oper == Operator.Equality ||
1247                             oper == Operator.Inequality ||
1248                             oper == Operator.LessThanOrEqual ||
1249                             oper == Operator.LessThan ||
1250                             oper == Operator.GreaterThanOrEqual ||
1251                             oper == Operator.GreaterThan){
1252                                 type = TypeManager.bool_type;
1253                         }
1254
1255                         return this;
1256                 }
1257                 
1258                 public override Expression DoResolve (EmitContext ec)
1259                 {
1260                         left = left.Resolve (ec);
1261                         right = right.Resolve (ec);
1262
1263                         if (left == null || right == null)
1264                                 return null;
1265
1266                         if (left.Type == null)
1267                                 throw new Exception (
1268                                         "Resolve returned non null, but did not set the type! (" +
1269                                         left + ") at Line: " + loc.Row);
1270                         if (right.Type == null)
1271                                 throw new Exception (
1272                                         "Resolve returned non null, but did not set the type! (" +
1273                                         right + ") at Line: "+ loc.Row);
1274
1275                         eclass = ExprClass.Value;
1276
1277                         return ResolveOperator (ec);
1278                 }
1279
1280                 public bool IsBranchable ()
1281                 {
1282                         if (oper == Operator.Equality ||
1283                             oper == Operator.Inequality ||
1284                             oper == Operator.LessThan ||
1285                             oper == Operator.GreaterThan ||
1286                             oper == Operator.LessThanOrEqual ||
1287                             oper == Operator.GreaterThanOrEqual){
1288                                 return true;
1289                         } else
1290                                 return false;
1291                 }
1292
1293                 /// <summary>
1294                 ///   This entry point is used by routines that might want
1295                 ///   to emit a brfalse/brtrue after an expression, and instead
1296                 ///   they could use a more compact notation.
1297                 ///
1298                 ///   Typically the code would generate l.emit/r.emit, followed
1299                 ///   by the comparission and then a brtrue/brfalse.  The comparissions
1300                 ///   are sometimes inneficient (there are not as complete as the branches
1301                 ///   look for the hacks in Emit using double ceqs).
1302                 ///
1303                 ///   So for those cases we provide EmitBranchable that can emit the
1304                 ///   branch with the test
1305                 /// </summary>
1306                 public void EmitBranchable (EmitContext ec, int target)
1307                 {
1308                         OpCode opcode;
1309                         bool close_target = false;
1310                         
1311                         left.Emit (ec);
1312                         right.Emit (ec);
1313                         
1314                         switch (oper){
1315                         case Operator.Equality:
1316                                 if (close_target)
1317                                         opcode = OpCodes.Beq_S;
1318                                 else
1319                                         opcode = OpCodes.Beq;
1320                                 break;
1321
1322                         case Operator.Inequality:
1323                                 if (close_target)
1324                                         opcode = OpCodes.Bne_Un_S;
1325                                 else
1326                                         opcode = OpCodes.Bne_Un;
1327                                 break;
1328
1329                         case Operator.LessThan:
1330                                 if (close_target)
1331                                         opcode = OpCodes.Blt_S;
1332                                 else
1333                                         opcode = OpCodes.Blt;
1334                                 break;
1335
1336                         case Operator.GreaterThan:
1337                                 if (close_target)
1338                                         opcode = OpCodes.Bgt_S;
1339                                 else
1340                                         opcode = OpCodes.Bgt;
1341                                 break;
1342
1343                         case Operator.LessThanOrEqual:
1344                                 if (close_target)
1345                                         opcode = OpCodes.Ble_S;
1346                                 else
1347                                         opcode = OpCodes.Ble;
1348                                 break;
1349
1350                         case Operator.GreaterThanOrEqual:
1351                                 if (close_target)
1352                                         opcode = OpCodes.Bge_S;
1353                                 else
1354                                         opcode = OpCodes.Ble;
1355                                 break;
1356
1357                         default:
1358                                 throw new Exception ("EmitBranchable called on non-EmitBranchable operator: "
1359                                                      + oper.ToString ());
1360                         }
1361
1362                         ec.ig.Emit (opcode, target);
1363                 }
1364                 
1365                 public override void Emit (EmitContext ec)
1366                 {
1367                         ILGenerator ig = ec.ig;
1368                         Type l = left.Type;
1369                         Type r = right.Type;
1370                         OpCode opcode;
1371
1372                         if (method != null) {
1373
1374                                 // Note that operators are static anyway
1375                                 
1376                                 if (Arguments != null) 
1377                                         Invocation.EmitArguments (ec, method, Arguments);
1378                                 
1379                                 if (method is MethodInfo)
1380                                         ig.Emit (OpCodes.Call, (MethodInfo) method);
1381                                 else
1382                                         ig.Emit (OpCodes.Call, (ConstructorInfo) method);
1383
1384                                 return;
1385                         }
1386                         
1387                         left.Emit (ec);
1388                         right.Emit (ec);
1389
1390                         switch (oper){
1391                         case Operator.Multiply:
1392                                 if (ec.CheckState){
1393                                         if (l == TypeManager.int32_type || l == TypeManager.int64_type)
1394                                                 opcode = OpCodes.Mul_Ovf;
1395                                         else if (l==TypeManager.uint32_type || l==TypeManager.uint64_type)
1396                                                 opcode = OpCodes.Mul_Ovf_Un;
1397                                         else
1398                                                 opcode = OpCodes.Mul;
1399                                 } else
1400                                         opcode = OpCodes.Mul;
1401
1402                                 break;
1403
1404                         case Operator.Division:
1405                                 if (l == TypeManager.uint32_type || l == TypeManager.uint64_type)
1406                                         opcode = OpCodes.Div_Un;
1407                                 else
1408                                         opcode = OpCodes.Div;
1409                                 break;
1410
1411                         case Operator.Modulus:
1412                                 if (l == TypeManager.uint32_type || l == TypeManager.uint64_type)
1413                                         opcode = OpCodes.Rem_Un;
1414                                 else
1415                                         opcode = OpCodes.Rem;
1416                                 break;
1417
1418                         case Operator.Addition:
1419                                 if (ec.CheckState){
1420                                         if (l == TypeManager.int32_type || l == TypeManager.int64_type)
1421                                                 opcode = OpCodes.Add_Ovf;
1422                                         else if (l==TypeManager.uint32_type || l==TypeManager.uint64_type)
1423                                                 opcode = OpCodes.Add_Ovf_Un;
1424                                         else
1425                                                 opcode = OpCodes.Mul;
1426                                 } else
1427                                         opcode = OpCodes.Add;
1428                                 break;
1429
1430                         case Operator.Subtraction:
1431                                 if (ec.CheckState){
1432                                         if (l == TypeManager.int32_type || l == TypeManager.int64_type)
1433                                                 opcode = OpCodes.Sub_Ovf;
1434                                         else if (l==TypeManager.uint32_type || l==TypeManager.uint64_type)
1435                                                 opcode = OpCodes.Sub_Ovf_Un;
1436                                         else
1437                                                 opcode = OpCodes.Sub;
1438                                 } else
1439                                         opcode = OpCodes.Sub;
1440                                 break;
1441
1442                         case Operator.RightShift:
1443                                 opcode = OpCodes.Shr;
1444                                 break;
1445                                 
1446                         case Operator.LeftShift:
1447                                 opcode = OpCodes.Shl;
1448                                 break;
1449
1450                         case Operator.Equality:
1451                                 opcode = OpCodes.Ceq;
1452                                 break;
1453
1454                         case Operator.Inequality:
1455                                 ec.ig.Emit (OpCodes.Ceq);
1456                                 ec.ig.Emit (OpCodes.Ldc_I4_0);
1457                                 
1458                                 opcode = OpCodes.Ceq;
1459                                 break;
1460
1461                         case Operator.LessThan:
1462                                 opcode = OpCodes.Clt;
1463                                 break;
1464
1465                         case Operator.GreaterThan:
1466                                 opcode = OpCodes.Cgt;
1467                                 break;
1468
1469                         case Operator.LessThanOrEqual:
1470                                 ec.ig.Emit (OpCodes.Cgt);
1471                                 ec.ig.Emit (OpCodes.Ldc_I4_0);
1472                                 
1473                                 opcode = OpCodes.Ceq;
1474                                 break;
1475
1476                         case Operator.GreaterThanOrEqual:
1477                                 ec.ig.Emit (OpCodes.Clt);
1478                                 ec.ig.Emit (OpCodes.Ldc_I4_1);
1479                                 
1480                                 opcode = OpCodes.Sub;
1481                                 break;
1482
1483                         case Operator.LogicalOr:
1484                         case Operator.BitwiseOr:
1485                                 opcode = OpCodes.Or;
1486                                 break;
1487
1488                         case Operator.LogicalAnd:
1489                         case Operator.BitwiseAnd:
1490                                 opcode = OpCodes.And;
1491                                 break;
1492
1493                         case Operator.ExclusiveOr:
1494                                 opcode = OpCodes.Xor;
1495                                 break;
1496
1497                         default:
1498                                 throw new Exception ("This should not happen: Operator = "
1499                                                      + oper.ToString ());
1500                         }
1501
1502                         ig.Emit (opcode);
1503                 }
1504
1505                 /// <summary>
1506                 ///   Constant expression reducer for binary operations
1507                 /// </summary>
1508                 public override Expression Reduce (EmitContext ec)
1509                 {
1510                         
1511                         left = left.Reduce (ec);
1512                         right = right.Reduce (ec);
1513
1514                         if (!(left is Literal && right is Literal))
1515                                 return this;
1516
1517                         if (method == TypeManager.string_concat_string_string){
1518                                 StringLiteral ls = (StringLiteral) left;
1519                                 StringLiteral rs = (StringLiteral) right;
1520                                 
1521                                 return new StringLiteral (ls.Value + rs.Value);
1522                         }
1523
1524                         // FINISH ME.
1525                         
1526                         return this;
1527                 }
1528         }
1529
1530         public class Conditional : Expression {
1531                 Expression expr, trueExpr, falseExpr;
1532                 Location loc;
1533                 
1534                 public Conditional (Expression expr, Expression trueExpr, Expression falseExpr, Location l)
1535                 {
1536                         this.expr = expr;
1537                         this.trueExpr = trueExpr;
1538                         this.falseExpr = falseExpr;
1539                         this.loc = l;
1540                 }
1541
1542                 public Expression Expr {
1543                         get {
1544                                 return expr;
1545                         }
1546                 }
1547
1548                 public Expression TrueExpr {
1549                         get {
1550                                 return trueExpr;
1551                         }
1552                 }
1553
1554                 public Expression FalseExpr {
1555                         get {
1556                                 return falseExpr;
1557                         }
1558                 }
1559
1560                 public override Expression DoResolve (EmitContext ec)
1561                 {
1562                         expr = expr.Resolve (ec);
1563
1564                         if (expr.Type != TypeManager.bool_type)
1565                                 expr = Expression.ConvertImplicitRequired (
1566                                         ec, expr, TypeManager.bool_type, loc);
1567                         
1568                         trueExpr = trueExpr.Resolve (ec);
1569                         falseExpr = falseExpr.Resolve (ec);
1570
1571                         if (expr == null || trueExpr == null || falseExpr == null)
1572                                 return null;
1573
1574                         if (trueExpr.Type == falseExpr.Type)
1575                                 type = trueExpr.Type;
1576                         else {
1577                                 Expression conv;
1578
1579                                 //
1580                                 // First, if an implicit conversion exists from trueExpr
1581                                 // to falseExpr, then the result type is of type falseExpr.Type
1582                                 //
1583                                 conv = ConvertImplicit (ec, trueExpr, falseExpr.Type, loc);
1584                                 if (conv != null){
1585                                         type = falseExpr.Type;
1586                                         trueExpr = conv;
1587                                 } else if ((conv = ConvertImplicit(ec, falseExpr,trueExpr.Type,loc))!= null){
1588                                         type = trueExpr.Type;
1589                                         falseExpr = conv;
1590                                 } else {
1591                                         Error (173, loc, "The type of the conditional expression can " +
1592                                                "not be computed because there is no implicit conversion" +
1593                                                " from `" + TypeManager.CSharpName (trueExpr.Type) + "'" +
1594                                                " and `" + TypeManager.CSharpName (falseExpr.Type) + "'");
1595                                         return null;
1596                                 }
1597                         }
1598
1599                         if (expr is BoolLiteral){
1600                                 BoolLiteral bl = (BoolLiteral) expr;
1601
1602                                 if (bl.Value)
1603                                         return trueExpr;
1604                                 else
1605                                         return falseExpr;
1606                         }
1607                         
1608                         eclass = ExprClass.Value;
1609                         return this;
1610                 }
1611
1612                 public override void Emit (EmitContext ec)
1613                 {
1614                         ILGenerator ig = ec.ig;
1615                         Label false_target = ig.DefineLabel ();
1616                         Label end_target = ig.DefineLabel ();
1617
1618                         expr.Emit (ec);
1619                         ig.Emit (OpCodes.Brfalse, false_target);
1620                         trueExpr.Emit (ec);
1621                         ig.Emit (OpCodes.Br, end_target);
1622                         ig.MarkLabel (false_target);
1623                         falseExpr.Emit (ec);
1624                         ig.MarkLabel (end_target);
1625                 }
1626
1627                 public override Expression Reduce (EmitContext ec)
1628                 {
1629                         expr = expr.Reduce (ec);
1630                         trueExpr = trueExpr.Reduce (ec);
1631                         falseExpr = falseExpr.Reduce (ec);
1632
1633                         if (!(expr is Literal && trueExpr is Literal && falseExpr is Literal))
1634                                 return this;
1635
1636                         BoolLiteral bl = (BoolLiteral) expr;
1637
1638                         if (bl.Value)
1639                                 return trueExpr;
1640                         else
1641                                 return falseExpr;
1642                 }
1643         }
1644
1645         public class LocalVariableReference : Expression, IAssignMethod, IMemoryLocation {
1646                 public readonly string Name;
1647                 public readonly Block Block;
1648
1649                 VariableInfo variable_info;
1650                 
1651                 public LocalVariableReference (Block block, string name)
1652                 {
1653                         Block = block;
1654                         Name = name;
1655                         eclass = ExprClass.Variable;
1656                 }
1657
1658                 public VariableInfo VariableInfo {
1659                         get {
1660                                 if (variable_info == null)
1661                                         variable_info = Block.GetVariableInfo (Name);
1662                                 return variable_info;
1663                         }
1664                 }
1665                 
1666                 public override Expression DoResolve (EmitContext ec)
1667                 {
1668                         VariableInfo vi = VariableInfo;
1669
1670                         type = vi.VariableType;
1671                         return this;
1672                 }
1673
1674                 public override void Emit (EmitContext ec)
1675                 {
1676                         VariableInfo vi = VariableInfo;
1677                         ILGenerator ig = ec.ig;
1678                         int idx = vi.Idx;
1679
1680                         vi.Used = true;
1681
1682                         switch (idx){
1683                         case 0:
1684                                 ig.Emit (OpCodes.Ldloc_0);
1685                                 break;
1686                                 
1687                         case 1:
1688                                 ig.Emit (OpCodes.Ldloc_1);
1689                                 break;
1690                                 
1691                         case 2:
1692                                 ig.Emit (OpCodes.Ldloc_2);
1693                                 break;
1694                                 
1695                         case 3:
1696                                 ig.Emit (OpCodes.Ldloc_3);
1697                                 break;
1698                                 
1699                         default:
1700                                 if (idx <= 255)
1701                                         ig.Emit (OpCodes.Ldloc_S, (byte) idx);
1702                                 else
1703                                         ig.Emit (OpCodes.Ldloc, idx);
1704                                 break;
1705                         }
1706                 }
1707                 
1708                 public static void Store (ILGenerator ig, int idx)
1709                 {
1710                         switch (idx){
1711                         case 0:
1712                                 ig.Emit (OpCodes.Stloc_0);
1713                                 break;
1714                                 
1715                         case 1:
1716                                 ig.Emit (OpCodes.Stloc_1);
1717                                 break;
1718                                 
1719                         case 2:
1720                                 ig.Emit (OpCodes.Stloc_2);
1721                                 break;
1722                                 
1723                         case 3:
1724                                 ig.Emit (OpCodes.Stloc_3);
1725                                 break;
1726                                 
1727                         default:
1728                                 if (idx <= 255)
1729                                         ig.Emit (OpCodes.Stloc_S, (byte) idx);
1730                                 else
1731                                         ig.Emit (OpCodes.Stloc, idx);
1732                                 break;
1733                         }
1734                 }
1735
1736                 public void EmitAssign (EmitContext ec, Expression source)
1737                 {
1738                         ILGenerator ig = ec.ig;
1739                         VariableInfo vi = VariableInfo;
1740
1741                         vi.Assigned = true;
1742
1743                         source.Emit (ec);
1744                         
1745                         // Funny seems the code below generates optimal code for us, but
1746                         // seems to take too long to generate what we need.
1747                         // ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
1748
1749                         Store (ig, vi.Idx);
1750                 }
1751                 
1752                 public void AddressOf (EmitContext ec)
1753                 {
1754                         VariableInfo vi = VariableInfo;
1755                         int idx = vi.Idx;
1756
1757                         vi.Used = true;
1758                         vi.Assigned = true;
1759                         
1760                         if (idx <= 255)
1761                                 ec.ig.Emit (OpCodes.Ldloca_S, (byte) idx);
1762                         else
1763                                 ec.ig.Emit (OpCodes.Ldloca, idx);
1764                 }
1765         }
1766
1767         /// <summary>
1768         ///   This represents a reference to a parameter in the intermediate
1769         ///   representation.
1770         /// </summary>
1771         public class ParameterReference : Expression, IAssignMethod, IMemoryLocation {
1772                 public readonly Parameters Pars;
1773                 public readonly String Name;
1774                 public readonly int Idx;
1775                 int arg_idx;
1776                 
1777                 public ParameterReference (Parameters pars, int idx, string name)
1778                 {
1779                         Pars = pars;
1780                         Idx  = idx;
1781                         Name = name;
1782                         eclass = ExprClass.Variable;
1783                 }
1784
1785                 public override Expression DoResolve (EmitContext ec)
1786                 {
1787                         Type [] types = Pars.GetParameterInfo (ec.TypeContainer);
1788
1789                         type = types [Idx];
1790
1791                         arg_idx = Idx;
1792                         if (!ec.IsStatic)
1793                                 arg_idx++;
1794                         
1795                         return this;
1796                 }
1797
1798                 public override void Emit (EmitContext ec)
1799                 {
1800                         if (arg_idx <= 255)
1801                                 ec.ig.Emit (OpCodes.Ldarg_S, (byte) arg_idx);
1802                         else
1803                                 ec.ig.Emit (OpCodes.Ldarg, arg_idx);
1804                 }
1805
1806                 public void EmitAssign (EmitContext ec, Expression source)
1807                 {
1808                         source.Emit (ec);
1809                         
1810                         if (arg_idx <= 255)
1811                                 ec.ig.Emit (OpCodes.Starg_S, (byte) arg_idx);
1812                         else
1813                                 ec.ig.Emit (OpCodes.Starg, arg_idx);
1814                         
1815                 }
1816
1817                 public void AddressOf (EmitContext ec)
1818                 {
1819                         if (arg_idx <= 255)
1820                                 ec.ig.Emit (OpCodes.Ldarga_S, (byte) arg_idx);
1821                         else
1822                                 ec.ig.Emit (OpCodes.Ldarga, arg_idx);
1823                 }
1824         }
1825         
1826         /// <summary>
1827         ///   Used for arguments to New(), Invocation()
1828         /// </summary>
1829         public class Argument {
1830                 public enum AType : byte {
1831                         Expression,
1832                         Ref,
1833                         Out
1834                 };
1835
1836                 public readonly AType ArgType;
1837                 public Expression expr;
1838                 
1839                 public Argument (Expression expr, AType type)
1840                 {
1841                         this.expr = expr;
1842                         this.ArgType = type;
1843                 }
1844
1845                 public Expression Expr {
1846                         get {
1847                                 return expr;
1848                         }
1849
1850                         set {
1851                                 expr = value;
1852                         }
1853                 }
1854
1855                 public Type Type {
1856                         get {
1857                                 return expr.Type;
1858                         }
1859                 }
1860
1861                 public Parameter.Modifier GetParameterModifier ()
1862                 {
1863                         if (ArgType == AType.Ref)
1864                                 return Parameter.Modifier.REF;
1865
1866                         if (ArgType == AType.Out)
1867                                 return Parameter.Modifier.OUT;
1868
1869                         return Parameter.Modifier.NONE;
1870                 }
1871
1872                 public static string FullDesc (Argument a)
1873                 {
1874                         return (a.ArgType == AType.Ref ? "ref " :
1875                                 (a.ArgType == AType.Out ? "out " : "")) +
1876                                 TypeManager.CSharpName (a.Expr.Type);
1877                 }
1878                 
1879                 public bool Resolve (EmitContext ec, Location loc)
1880                 {
1881                         expr = expr.Resolve (ec);
1882
1883                         if (ArgType == AType.Expression)
1884                                 return expr != null;
1885
1886                         if (expr.ExprClass != ExprClass.Variable){
1887                                 Report.Error (206, loc,
1888                                               "A property or indexer can not be passed as an out or ref " +
1889                                               "parameter");
1890                                 return false;
1891                         }
1892                                 
1893                         return expr != null;
1894                 }
1895
1896                 public void Emit (EmitContext ec)
1897                 {
1898                         if (ArgType == AType.Ref || ArgType == AType.Out)
1899                                 ((IMemoryLocation)expr).AddressOf (ec);
1900                         else
1901                                 expr.Emit (ec);
1902                 }
1903         }
1904
1905         /// <summary>
1906         ///   Invocation of methods or delegates.
1907         /// </summary>
1908         public class Invocation : ExpressionStatement {
1909                 public readonly ArrayList Arguments;
1910                 Location loc;
1911
1912                 Expression expr;
1913                 MethodBase method = null;
1914                         
1915                 static Hashtable method_parameter_cache;
1916
1917                 static Invocation ()
1918                 {
1919                         method_parameter_cache = new Hashtable ();
1920                 }
1921                         
1922                 //
1923                 // arguments is an ArrayList, but we do not want to typecast,
1924                 // as it might be null.
1925                 //
1926                 // FIXME: only allow expr to be a method invocation or a
1927                 // delegate invocation (7.5.5)
1928                 //
1929                 public Invocation (Expression expr, ArrayList arguments, Location l)
1930                 {
1931                         this.expr = expr;
1932                         Arguments = arguments;
1933                         loc = l;
1934                 }
1935
1936                 public Expression Expr {
1937                         get {
1938                                 return expr;
1939                         }
1940                 }
1941
1942                 /// <summary>
1943                 ///   Returns the Parameters (a ParameterData interface) for the
1944                 ///   Method `mb'
1945                 /// </summary>
1946                 public static ParameterData GetParameterData (MethodBase mb)
1947                 {
1948                         object pd = method_parameter_cache [mb];
1949                         object ip;
1950                         
1951                         if (pd != null)
1952                                 return (ParameterData) pd;
1953
1954                         
1955                         ip = TypeContainer.LookupParametersByBuilder (mb);
1956                         if (ip != null){
1957                                 method_parameter_cache [mb] = ip;
1958
1959                                 return (ParameterData) ip;
1960                         } else {
1961                                 ParameterInfo [] pi = mb.GetParameters ();
1962                                 ReflectionParameters rp = new ReflectionParameters (pi);
1963                                 method_parameter_cache [mb] = rp;
1964
1965                                 return (ParameterData) rp;
1966                         }
1967                 }
1968
1969                 /// <summary>
1970                 ///   Tells whether a user defined conversion from Type `from' to
1971                 ///   Type `to' exists.
1972                 ///
1973                 ///   FIXME: we could implement a cache here. 
1974                 /// </summary>
1975                 static bool ConversionExists (EmitContext ec, Type from, Type to, Location loc)
1976                 {
1977                         // Locate user-defined implicit operators
1978
1979                         Expression mg;
1980                         
1981                         mg = MemberLookup (ec, to, "op_Implicit", false, loc);
1982
1983                         if (mg != null) {
1984                                 MethodGroupExpr me = (MethodGroupExpr) mg;
1985                                 
1986                                 for (int i = me.Methods.Length; i > 0;) {
1987                                         i--;
1988                                         MethodBase mb = me.Methods [i];
1989                                         ParameterData pd = GetParameterData (mb);
1990                                         
1991                                         if (from == pd.ParameterType (0))
1992                                                 return true;
1993                                 }
1994                         }
1995
1996                         mg = MemberLookup (ec, from, "op_Implicit", false, loc);
1997
1998                         if (mg != null) {
1999                                 MethodGroupExpr me = (MethodGroupExpr) mg;
2000
2001                                 for (int i = me.Methods.Length; i > 0;) {
2002                                         i--;
2003                                         MethodBase mb = me.Methods [i];
2004                                         MethodInfo mi = (MethodInfo) mb;
2005                                         
2006                                         if (mi.ReturnType == to)
2007                                                 return true;
2008                                 }
2009                         }
2010                         
2011                         return false;
2012                 }
2013                 
2014                 /// <summary>
2015                 ///  Determines "better conversion" as specified in 7.4.2.3
2016                 ///  Returns : 1 if a->p is better
2017                 ///            0 if a->q or neither is better 
2018                 /// </summary>
2019                 static int BetterConversion (EmitContext ec, Argument a, Type p, Type q, bool use_standard,
2020                                              Location loc)
2021                 {
2022                         Type argument_type = a.Type;
2023                         Expression argument_expr = a.Expr;
2024
2025                         if (argument_type == null)
2026                                 throw new Exception ("Expression of type " + a.Expr + " does not resolve its type");
2027
2028                         if (p == q)
2029                                 return 0;
2030                         
2031                         if (argument_type == p)
2032                                 return 1;
2033
2034                         if (argument_type == q)
2035                                 return 0;
2036
2037                         //
2038                         // Now probe whether an implicit constant expression conversion
2039                         // can be used.
2040                         //
2041                         // An implicit constant expression conversion permits the following
2042                         // conversions:
2043                         //
2044                         //    * A constant-expression of type `int' can be converted to type
2045                         //      sbyte, byute, short, ushort, uint, ulong provided the value of
2046                         //      of the expression is withing the range of the destination type.
2047                         //
2048                         //    * A constant-expression of type long can be converted to type
2049                         //      ulong, provided the value of the constant expression is not negative
2050                         //
2051                         // FIXME: Note that this assumes that constant folding has
2052                         // taken place.  We dont do constant folding yet.
2053                         //
2054
2055                         if (argument_expr is IntLiteral){
2056                                 IntLiteral ei = (IntLiteral) argument_expr;
2057                                 int value = ei.Value;
2058                                 
2059                                 if (p == TypeManager.sbyte_type){
2060                                         if (value >= SByte.MinValue && value <= SByte.MaxValue)
2061                                                 return 1;
2062                                 } else if (p == TypeManager.byte_type){
2063                                         if (Byte.MinValue >= 0 && value <= Byte.MaxValue)
2064                                                 return 1;
2065                                 } else if (p == TypeManager.short_type){
2066                                         if (value >= Int16.MinValue && value <= Int16.MaxValue)
2067                                                 return 1;
2068                                 } else if (p == TypeManager.ushort_type){
2069                                         if (value >= UInt16.MinValue && value <= UInt16.MaxValue)
2070                                                 return 1;
2071                                 } else if (p == TypeManager.uint32_type){
2072                                         //
2073                                         // we can optimize this case: a positive int32
2074                                         // always fits on a uint32
2075                                         //
2076                                         if (value >= 0)
2077                                                 return 1;
2078                                 } else if (p == TypeManager.uint64_type){
2079                                         //
2080                                         // we can optimize this case: a positive int32
2081                                         // always fits on a uint64
2082                                         //
2083                                         if (value >= 0)
2084                                                 return 1;
2085                                 }
2086                         } else if (argument_type == TypeManager.int64_type && argument_expr is LongLiteral){
2087                                 LongLiteral ll = (LongLiteral) argument_expr;
2088                                 
2089                                 if (p == TypeManager.uint64_type){
2090                                         if (ll.Value > 0)
2091                                                 return 1;
2092                                 }
2093                         }
2094
2095                         if (q == null) {
2096
2097                                 Expression tmp;
2098
2099                                 if (use_standard)
2100                                         tmp = ConvertImplicitStandard (ec, argument_expr, p, loc);
2101                                 else
2102                                         tmp = ConvertImplicit (ec, argument_expr, p, loc);
2103
2104                                 if (tmp != null)
2105                                         return 1;
2106                                 else
2107                                         return 0;
2108
2109                         }
2110
2111                         if (ConversionExists (ec, p, q, loc) == true &&
2112                             ConversionExists (ec, q, p, loc) == false)
2113                                 return 1;
2114
2115                         if (p == TypeManager.sbyte_type)
2116                                 if (q == TypeManager.byte_type || q == TypeManager.ushort_type ||
2117                                     q == TypeManager.uint32_type || q == TypeManager.uint64_type)
2118                                         return 1;
2119
2120                         if (p == TypeManager.short_type)
2121                                 if (q == TypeManager.ushort_type || q == TypeManager.uint32_type ||
2122                                     q == TypeManager.uint64_type)
2123                                         return 1;
2124
2125                         if (p == TypeManager.int32_type)
2126                                 if (q == TypeManager.uint32_type || q == TypeManager.uint64_type)
2127                                         return 1;
2128
2129                         if (p == TypeManager.int64_type)
2130                                 if (q == TypeManager.uint64_type)
2131                                         return 1;
2132
2133                         return 0;
2134                 }
2135                 
2136                 /// <summary>
2137                 ///  Determines "Better function"
2138                 /// </summary>
2139                 /// <remarks>
2140                 ///    and returns an integer indicating :
2141                 ///    0 if candidate ain't better
2142                 ///    1 if candidate is better than the current best match
2143                 /// </remarks>
2144                 static int BetterFunction (EmitContext ec, ArrayList args,
2145                                            MethodBase candidate, MethodBase best,
2146                                            bool use_standard, Location loc)
2147                 {
2148                         ParameterData candidate_pd = GetParameterData (candidate);
2149                         ParameterData best_pd;
2150                         int argument_count;
2151
2152                         if (args == null)
2153                                 argument_count = 0;
2154                         else
2155                                 argument_count = args.Count;
2156
2157                         if (candidate_pd.Count == 0 && argument_count == 0)
2158                                 return 1;
2159
2160                         if (best == null) {
2161                                 if (candidate_pd.Count == argument_count) {
2162                                         int x = 0;
2163                                         for (int j = argument_count; j > 0;) {
2164                                                 j--;
2165                                                 
2166                                                 Argument a = (Argument) args [j];
2167                                                 
2168                                                 x = BetterConversion (
2169                                                         ec, a, candidate_pd.ParameterType (j), null,
2170                                                         use_standard, loc);
2171                                                 
2172                                                 if (x <= 0)
2173                                                         break;
2174                                         }
2175                                         
2176                                         if (x > 0)
2177                                                 return 1;
2178                                         else
2179                                                 return 0;
2180                                         
2181                                 } else
2182                                         return 0;
2183                         }
2184
2185                         best_pd = GetParameterData (best);
2186
2187                         if (candidate_pd.Count == argument_count && best_pd.Count == argument_count) {
2188                                 int rating1 = 0, rating2 = 0;
2189                                 
2190                                 for (int j = argument_count; j > 0;) {
2191                                         j--;
2192                                         int x, y;
2193                                         
2194                                         Argument a = (Argument) args [j];
2195
2196                                         x = BetterConversion (ec, a, candidate_pd.ParameterType (j),
2197                                                               best_pd.ParameterType (j), use_standard, loc);
2198                                         y = BetterConversion (ec, a, best_pd.ParameterType (j),
2199                                                               candidate_pd.ParameterType (j), use_standard,
2200                                                               loc);
2201                                         
2202                                         rating1 += x;
2203                                         rating2 += y;
2204                                 }
2205
2206                                 if (rating1 > rating2)
2207                                         return 1;
2208                                 else
2209                                         return 0;
2210                         } else
2211                                 return 0;
2212                         
2213                 }
2214
2215                 public static string FullMethodDesc (MethodBase mb)
2216                 {
2217                         StringBuilder sb = new StringBuilder (mb.Name);
2218                         ParameterData pd = GetParameterData (mb);
2219
2220                         int count = pd.Count;
2221                         sb.Append (" (");
2222                         
2223                         for (int i = count; i > 0; ) {
2224                                 i--;
2225                                 
2226                                 sb.Append (pd.ParameterDesc (count - i - 1));
2227                                 if (i != 0)
2228                                         sb.Append (", ");
2229                         }
2230                         
2231                         sb.Append (")");
2232                         return sb.ToString ();
2233                 }
2234
2235                 public static MethodGroupExpr MakeUnionSet (Expression mg1, Expression mg2)
2236                 {
2237                         MemberInfo [] miset;
2238                         MethodGroupExpr union;
2239                         
2240                         if (mg1 != null && mg2 != null) {
2241                                 
2242                                 MethodGroupExpr left_set = null, right_set = null;
2243                                 int length1 = 0, length2 = 0;
2244                                 
2245                                 left_set = (MethodGroupExpr) mg1;
2246                                 length1 = left_set.Methods.Length;
2247                                 
2248                                 right_set = (MethodGroupExpr) mg2;
2249                                 length2 = right_set.Methods.Length;
2250
2251                                 ArrayList common = new ArrayList ();
2252                                 
2253                                 for (int i = 0; i < left_set.Methods.Length; i++) {
2254                                         for (int j = 0; j < right_set.Methods.Length; j++) {
2255                                                 if (left_set.Methods [i] == right_set.Methods [j]) 
2256                                                         common.Add (left_set.Methods [i]);
2257                                         }
2258                                 }
2259                                 
2260                                 miset = new MemberInfo [length1 + length2 - common.Count];
2261
2262                                 left_set.Methods.CopyTo (miset, 0);
2263
2264                                 int k = 0;
2265                                 
2266                                 for (int j = 0; j < right_set.Methods.Length; j++)
2267                                         if (!common.Contains (right_set.Methods [j]))
2268                                                 miset [length1 + k++] = right_set.Methods [j];
2269                                 
2270                                 union = new MethodGroupExpr (miset);
2271
2272                                 return union;
2273
2274                         } else if (mg1 == null && mg2 != null) {
2275                                 
2276                                 MethodGroupExpr me = (MethodGroupExpr) mg2; 
2277                                 
2278                                 miset = new MemberInfo [me.Methods.Length];
2279                                 me.Methods.CopyTo (miset, 0);
2280
2281                                 union = new MethodGroupExpr (miset);
2282                                 
2283                                 return union;
2284
2285                         } else if (mg2 == null && mg1 != null) {
2286                                 
2287                                 MethodGroupExpr me = (MethodGroupExpr) mg1; 
2288                                 
2289                                 miset = new MemberInfo [me.Methods.Length];
2290                                 me.Methods.CopyTo (miset, 0);
2291
2292                                 union = new MethodGroupExpr (miset);
2293                                 
2294                                 return union;
2295                         }
2296                         
2297                         return null;
2298                 }
2299
2300                 /// <summary>
2301                 ///  Determines is the candidate method, if a params method, is applicable
2302                 ///  in its expanded form to the given set of arguments
2303                 /// </summary>
2304                 static bool IsParamsMethodApplicable (ArrayList arguments, MethodBase candidate)
2305                 {
2306                         int arg_count;
2307                         
2308                         if (arguments == null)
2309                                 arg_count = 0;
2310                         else
2311                                 arg_count = arguments.Count;
2312                         
2313                         ParameterData pd = GetParameterData (candidate);
2314                         
2315                         int pd_count = pd.Count;
2316
2317                         if (pd.ParameterModifier (pd_count - 1) != Parameter.Modifier.PARAMS)
2318                                 return false;
2319
2320                         if (pd_count - 1 > arg_count)
2321                                 return false;
2322
2323                         // If we have come this far, the case which remains is when the number of parameters
2324                         // is less than or equal to the argument count. So, we now check if the element type
2325                         // of the params array is compatible with each argument type
2326                         //
2327
2328                         Type element_type = pd.ParameterType (pd_count - 1).GetElementType ();
2329
2330                         for (int i = pd_count - 1; i < arg_count - 1; i++) {
2331                                 Argument a = (Argument) arguments [i];
2332                                 if (!StandardConversionExists (a.Type, element_type))
2333                                         return false;
2334                         }
2335                         
2336                         return true;
2337                 }
2338
2339                 /// <summary>
2340                 ///  Determines if the candidate method is applicable (section 14.4.2.1)
2341                 ///  to the given set of arguments
2342                 /// </summary>
2343                 static bool IsApplicable (ArrayList arguments, MethodBase candidate)
2344                 {
2345                         int arg_count;
2346
2347                         if (arguments == null)
2348                                 arg_count = 0;
2349                         else
2350                                 arg_count = arguments.Count;
2351
2352                         ParameterData pd = GetParameterData (candidate);
2353
2354                         int pd_count = pd.Count;
2355
2356                         if (arg_count != pd.Count)
2357                                 return false;
2358
2359                         for (int i = arg_count; i > 0; ) {
2360                                 i--;
2361
2362                                 Argument a = (Argument) arguments [i];
2363
2364                                 Parameter.Modifier a_mod = a.GetParameterModifier ();
2365                                 Parameter.Modifier p_mod = pd.ParameterModifier (i);
2366
2367                                 if (a_mod == p_mod) {
2368                                         
2369                                         if (a_mod == Parameter.Modifier.NONE)
2370                                                 if (!StandardConversionExists (a.Type, pd.ParameterType (i)))
2371                                                         return false;
2372                                         
2373                                         if (a_mod == Parameter.Modifier.REF ||
2374                                             a_mod == Parameter.Modifier.OUT)
2375                                                 if (pd.ParameterType (i) != a.Type)
2376                                                         return false;
2377                                 } else
2378                                         return false;
2379                         }
2380
2381                         return true;
2382                 }
2383                 
2384                 
2385
2386                 /// <summary>
2387                 ///   Find the Applicable Function Members (7.4.2.1)
2388                 ///
2389                 ///   me: Method Group expression with the members to select.
2390                 ///       it might contain constructors or methods (or anything
2391                 ///       that maps to a method).
2392                 ///
2393                 ///   Arguments: ArrayList containing resolved Argument objects.
2394                 ///
2395                 ///   loc: The location if we want an error to be reported, or a Null
2396                 ///        location for "probing" purposes.
2397                 ///
2398                 ///   use_standard: controls whether OverloadResolve should use the 
2399                 ///   ConvertImplicit or ConvertImplicitStandard during overload resolution.
2400                 ///
2401                 ///   Returns: The MethodBase (either a ConstructorInfo or a MethodInfo)
2402                 ///            that is the best match of me on Arguments.
2403                 ///
2404                 /// </summary>
2405                 public static MethodBase OverloadResolve (EmitContext ec, MethodGroupExpr me,
2406                                                           ArrayList Arguments, Location loc,
2407                                                           bool use_standard)
2408                 {
2409                         ArrayList afm = new ArrayList ();
2410                         int best_match_idx = -1;
2411                         MethodBase method = null;
2412                         int argument_count;
2413                         
2414                         for (int i = me.Methods.Length; i > 0; ){
2415                                 i--;
2416                                 MethodBase candidate  = me.Methods [i];
2417                                 int x;
2418
2419                                 // Check if candidate is applicable (section 14.4.2.1)
2420                                 if (!IsApplicable (Arguments, candidate))
2421                                         continue;
2422
2423                                 x = BetterFunction (ec, Arguments, candidate, method, use_standard, loc);
2424                                 
2425                                 if (x == 0)
2426                                         continue;
2427                                 else {
2428                                         best_match_idx = i;
2429                                         method = me.Methods [best_match_idx];
2430                                 }
2431                         }
2432
2433                         if (Arguments == null)
2434                                 argument_count = 0;
2435                         else
2436                                 argument_count = Arguments.Count;
2437                         
2438                         //
2439                         // Now we see if we can find params functions, applicable in their expanded form
2440                         // since if they were applicable in their normal form, they would have been selected
2441                         // above anyways
2442                         //
2443                         if (best_match_idx == -1) {
2444
2445                                 for (int i = me.Methods.Length; i > 0; ) {
2446                                         i--;
2447                                         MethodBase candidate = me.Methods [i];
2448
2449                                         if (IsParamsMethodApplicable (Arguments, candidate)) {
2450                                                 best_match_idx = i;
2451                                                 method = me.Methods [best_match_idx];
2452                                                 break;
2453                                         }
2454                                 }
2455                         }
2456
2457                         //
2458                         // Now we see if we can at least find a method with the same number of arguments
2459                         //
2460                         ParameterData pd;
2461                         
2462                         if (best_match_idx == -1) {
2463                                 
2464                                 for (int i = me.Methods.Length; i > 0;) {
2465                                         i--;
2466                                         MethodBase mb = me.Methods [i];
2467                                         pd = GetParameterData (mb);
2468                                         
2469                                         if (pd.Count == argument_count) {
2470                                                 best_match_idx = i;
2471                                                 method = me.Methods [best_match_idx];
2472                                                 break;
2473                                         } else
2474                                                 continue;
2475                                 }
2476                         }
2477
2478                         if (method == null)
2479                                 return null;
2480                         
2481                         // And now convert implicitly, each argument to the required type
2482                         
2483                         pd = GetParameterData (method);
2484                         int pd_count = pd.Count;
2485
2486                         for (int j = 0; j < argument_count; j++) {
2487
2488                                 Argument a = (Argument) Arguments [j];
2489                                 Expression a_expr = a.Expr;
2490                                 Type parameter_type = pd.ParameterType (j);
2491
2492                                 //
2493                                 // Note that we need to compare against the element type
2494                                 // when we have a params method
2495                                 //
2496                                 if (pd.ParameterModifier (pd_count - 1) == Parameter.Modifier.PARAMS) {
2497                                         if (j >= pd_count - 1) 
2498                                                 parameter_type = pd.ParameterType (pd_count - 1).GetElementType ();
2499                                 }
2500
2501                                 if (a.Type != parameter_type){
2502                                         Expression conv;
2503                                         
2504                                         if (use_standard)
2505                                                 conv = ConvertImplicitStandard (ec, a_expr, parameter_type, Location.Null);
2506                                         else
2507                                                 conv = ConvertImplicit (ec, a_expr, parameter_type, Location.Null);
2508
2509                                         if (conv == null) {
2510                                                 if (!Location.IsNull (loc)) {
2511                                                         Error (1502, loc,
2512                                                         "The best overloaded match for method '" + FullMethodDesc (method)+
2513                                                                "' has some invalid arguments");
2514                                                         Error (1503, loc,
2515                                                          "Argument " + (j+1) +
2516                                                          ": Cannot convert from '" + Argument.FullDesc (a) 
2517                                                          + "' to '" + pd.ParameterDesc (j) + "'");
2518                                                 }
2519                                                 return null;
2520                                         }
2521                                         
2522                         
2523                                         
2524                                         //
2525                                         // Update the argument with the implicit conversion
2526                                         //
2527                                         if (a_expr != conv)
2528                                                 a.Expr = conv;
2529
2530                                         // FIXME : For the case of params methods, we need to actually instantiate
2531                                         // an array and initialize it with the argument values etc etc.
2532
2533                                 }
2534                                 
2535                                 if (a.GetParameterModifier () != pd.ParameterModifier (j) &&
2536                                     pd.ParameterModifier (j) != Parameter.Modifier.PARAMS) {
2537                                         if (!Location.IsNull (loc)) {
2538                                                 Error (1502, loc,
2539                                                        "The best overloaded match for method '" + FullMethodDesc (method)+
2540                                                        "' has some invalid arguments");
2541                                                 Error (1503, loc,
2542                                                        "Argument " + (j+1) +
2543                                                        ": Cannot convert from '" + Argument.FullDesc (a) 
2544                                                        + "' to '" + pd.ParameterDesc (j) + "'");
2545                                         }
2546                                         return null;
2547                                 }
2548                                 
2549                                 
2550                         }
2551                         
2552                         return method;
2553                 }
2554                 
2555                 public static MethodBase OverloadResolve (EmitContext ec, MethodGroupExpr me,
2556                                                           ArrayList Arguments, Location loc)
2557                 {
2558                         return OverloadResolve (ec, me, Arguments, loc, false);
2559                 }
2560                         
2561                 public override Expression DoResolve (EmitContext ec)
2562                 {
2563                         //
2564                         // First, resolve the expression that is used to
2565                         // trigger the invocation
2566                         //
2567                         expr = expr.Resolve (ec);
2568                         if (expr == null)
2569                                 return null;
2570
2571                         if (!(expr is MethodGroupExpr)) {
2572                                 Type expr_type = expr.Type;
2573
2574                                 if (expr_type != null){
2575                                         bool IsDelegate = TypeManager.IsDelegateType (expr_type);
2576                                         if (IsDelegate)
2577                                                 return (new DelegateInvocation (
2578                                                         this.expr, Arguments, loc)).Resolve (ec);
2579                                 }
2580                         }
2581
2582                         if (!(expr is MethodGroupExpr)){
2583                                 report118 (loc, this.expr, "method group");
2584                                 return null;
2585                         }
2586
2587                         //
2588                         // Next, evaluate all the expressions in the argument list
2589                         //
2590                         if (Arguments != null){
2591                                 for (int i = Arguments.Count; i > 0;){
2592                                         --i;
2593                                         Argument a = (Argument) Arguments [i];
2594
2595                                         if (!a.Resolve (ec, loc))
2596                                                 return null;
2597                                 }
2598                         }
2599
2600                         method = OverloadResolve (ec, (MethodGroupExpr) this.expr, Arguments, loc);
2601
2602                         if (method == null){
2603                                 Error (-6, loc,
2604                                        "Could not find any applicable function for this argument list");
2605                                 return null;
2606                         }
2607
2608                         if (method is MethodInfo)
2609                                 type = ((MethodInfo)method).ReturnType;
2610
2611                         eclass = ExprClass.Value;
2612                         return this;
2613                 }
2614
2615                 // <summary>
2616                 //   Emits the list of arguments as an array
2617                 // </summary>
2618                 static void EmitParams (EmitContext ec, int idx, ArrayList arguments)
2619                 {
2620                         ILGenerator ig = ec.ig;
2621                         int count = arguments.Count - idx;
2622                         Argument a = (Argument) arguments [idx];
2623                         Type t = a.expr.Type;
2624                         string array_type = t.FullName + "[]";
2625                         LocalBuilder array;
2626                         
2627                         array = ig.DeclareLocal (Type.GetType (array_type));
2628                         IntLiteral.EmitInt (ig, count);
2629                         ig.Emit (OpCodes.Newarr, t);
2630                         ig.Emit (OpCodes.Stloc, array);
2631
2632                         int top = arguments.Count;
2633                         for (int j = idx; j < top; j++){
2634                                 a = (Argument) arguments [j];
2635                                 
2636                                 ig.Emit (OpCodes.Ldloc, array);
2637                                 IntLiteral.EmitInt (ig, j - idx);
2638                                 a.Emit (ec);
2639                                 
2640                                 ArrayAccess.EmitStoreOpcode (ig, t);
2641                         }
2642                         ig.Emit (OpCodes.Ldloc, array);
2643                 }
2644                 
2645                 /// <summary>
2646                 ///   Emits a list of resolved Arguments that are in the arguments
2647                 ///   ArrayList.
2648                 /// 
2649                 ///   The MethodBase argument might be null if the
2650                 ///   emission of the arguments is known not to contain
2651                 ///   a `params' field (for example in constructors or other routines
2652                 ///   that keep their arguments in this structure
2653                 /// </summary>
2654                 public static void EmitArguments (EmitContext ec, MethodBase mb, ArrayList arguments)
2655                 {
2656                         ParameterData pd = null;
2657                         int top;
2658
2659                         if (arguments != null)
2660                                 top = arguments.Count;
2661                         else
2662                                 top = 0;
2663
2664                         if (mb != null)
2665                                  pd = GetParameterData (mb);
2666
2667                         for (int i = 0; i < top; i++){
2668                                 Argument a = (Argument) arguments [i];
2669
2670                                 if (pd != null){
2671                                         if (pd.ParameterModifier (i) == Parameter.Modifier.PARAMS){
2672                                                 EmitParams (ec, i, arguments);
2673                                                 return;
2674                                         }
2675                                 }
2676                                             
2677                                 a.Emit (ec);
2678                         }
2679                 }
2680
2681                 public static void EmitCall (EmitContext ec,
2682                                              bool is_static, Expression instance_expr,
2683                                              MethodBase method, ArrayList Arguments)
2684                 {
2685                         ILGenerator ig = ec.ig;
2686                         bool struct_call = false;
2687                                 
2688                         if (!is_static){
2689                                 //
2690                                 // If this is ourselves, push "this"
2691                                 //
2692                                 if (instance_expr == null){
2693                                         ig.Emit (OpCodes.Ldarg_0);
2694                                 } else {
2695                                         //
2696                                         // Push the instance expression
2697                                         //
2698                                         if (instance_expr.Type.IsSubclassOf (TypeManager.value_type)){
2699
2700                                                 struct_call = true;
2701
2702                                                 //
2703                                                 // If the expression implements IMemoryLocation, then
2704                                                 // we can optimize and use AddressOf on the
2705                                                 // return.
2706                                                 //
2707                                                 // If not we have to use some temporary storage for
2708                                                 // it.
2709                                                 if (instance_expr is IMemoryLocation)
2710                                                         ((IMemoryLocation) instance_expr).AddressOf (ec);
2711                                                 else {
2712                                                         Type t = instance_expr.Type;
2713                                                         
2714                                                         instance_expr.Emit (ec);
2715                                                         LocalBuilder temp = ig.DeclareLocal (t);
2716                                                         ig.Emit (OpCodes.Stloc, temp);
2717                                                         ig.Emit (OpCodes.Ldloca, temp);
2718                                                 }
2719                                         } else 
2720                                                 instance_expr.Emit (ec);
2721                                 }
2722                         }
2723
2724                         if (Arguments != null)
2725                                 EmitArguments (ec, method, Arguments);
2726
2727                         if (is_static || struct_call){
2728                                 if (method is MethodInfo)
2729                                         ig.Emit (OpCodes.Call, (MethodInfo) method);
2730                                 else
2731                                         ig.Emit (OpCodes.Call, (ConstructorInfo) method);
2732                         } else {
2733                                 if (method is MethodInfo)
2734                                         ig.Emit (OpCodes.Callvirt, (MethodInfo) method);
2735                                 else
2736                                         ig.Emit (OpCodes.Callvirt, (ConstructorInfo) method);
2737                         }
2738                 }
2739                 
2740                 public override void Emit (EmitContext ec)
2741                 {
2742                         MethodGroupExpr mg = (MethodGroupExpr) this.expr;
2743                         EmitCall (ec, method.IsStatic, mg.InstanceExpression, method, Arguments);
2744                 }
2745                 
2746                 public override void EmitStatement (EmitContext ec)
2747                 {
2748                         Emit (ec);
2749
2750                         // 
2751                         // Pop the return value if there is one
2752                         //
2753                         if (method is MethodInfo){
2754                                 if (((MethodInfo)method).ReturnType != TypeManager.void_type)
2755                                         ec.ig.Emit (OpCodes.Pop);
2756                         }
2757                 }
2758         }
2759
2760         /// <summary>
2761         ///    Implements the new expression 
2762         /// </summary>
2763         public class New : ExpressionStatement {
2764                 public readonly ArrayList Arguments;
2765                 public readonly string    RequestedType;
2766
2767                 Location loc;
2768                 MethodBase method = null;
2769
2770                 //
2771                 // If set, the new expression is for a value_target, and
2772                 // we will not leave anything on the stack.
2773                 //
2774                 Expression value_target;
2775                 
2776                 public New (string requested_type, ArrayList arguments, Location l)
2777                 {
2778                         RequestedType = requested_type;
2779                         Arguments = arguments;
2780                         loc = l;
2781                 }
2782
2783                 public Expression ValueTypeVariable {
2784                         get {
2785                                 return value_target;
2786                         }
2787
2788                         set {
2789                                 value_target = value;
2790                         }
2791                 }
2792
2793                 public override Expression DoResolve (EmitContext ec)
2794                 {
2795                         type = ec.TypeContainer.LookupType (RequestedType, false);
2796                         
2797                         if (type == null)
2798                                 return null;
2799                         
2800                         bool IsDelegate = TypeManager.IsDelegateType (type);
2801                         
2802                         if (IsDelegate)
2803                                 return (new NewDelegate (type, Arguments, loc)).Resolve (ec);
2804                         
2805                         Expression ml;
2806                         
2807                         ml = MemberLookup (ec, type, ".ctor", false,
2808                                            MemberTypes.Constructor, AllBindingsFlags, loc);
2809                         
2810                         bool is_struct = false;
2811                         is_struct = type.IsSubclassOf (TypeManager.value_type);
2812                         
2813                         if (! (ml is MethodGroupExpr)){
2814                                 if (!is_struct){
2815                                         report118 (loc, ml, "method group");
2816                                         return null;
2817                                 }
2818                         }
2819                         
2820                         if (ml != null) {
2821                                 if (Arguments != null){
2822                                         for (int i = Arguments.Count; i > 0;){
2823                                                 --i;
2824                                                 Argument a = (Argument) Arguments [i];
2825                                                 
2826                                                 if (!a.Resolve (ec, loc))
2827                                                         return null;
2828                                         }
2829                                 }
2830
2831                                 method = Invocation.OverloadResolve (ec, (MethodGroupExpr) ml,
2832                                                                      Arguments, loc);
2833                         }
2834                         
2835                         if (method == null && !is_struct) {
2836                                 Error (-6, loc,
2837                                        "New invocation: Can not find a constructor for " +
2838                                        "this argument list");
2839                                 return null;
2840                         }
2841                         
2842                         eclass = ExprClass.Value;
2843                         return this;
2844                 }
2845
2846                 //
2847                 // This DoEmit can be invoked in two contexts:
2848                 //    * As a mechanism that will leave a value on the stack (new object)
2849                 //    * As one that wont (init struct)
2850                 //
2851                 // You can control whether a value is required on the stack by passing
2852                 // need_value_on_stack.  The code *might* leave a value on the stack
2853                 // so it must be popped manually
2854                 //
2855                 // Returns whether a value is left on the stack
2856                 //
2857                 bool DoEmit (EmitContext ec, bool need_value_on_stack)
2858                 {
2859                         if (method == null){
2860                                 IMemoryLocation ml = (IMemoryLocation) value_target;
2861
2862                                 ml.AddressOf (ec);
2863                         } else {
2864                                 Invocation.EmitArguments (ec, method, Arguments);
2865                                 ec.ig.Emit (OpCodes.Newobj, (ConstructorInfo) method);
2866                                 return true;
2867                         }
2868
2869                         //
2870                         // It must be a value type, sanity check
2871                         //
2872                         if (value_target != null){
2873                                 ec.ig.Emit (OpCodes.Initobj, type);
2874
2875                                 if (need_value_on_stack){
2876                                         value_target.Emit (ec);
2877                                         return true;
2878                                 }
2879                                 return false;
2880                         }
2881
2882                         throw new Exception ("No method and no value type");
2883                 }
2884
2885                 public override void Emit (EmitContext ec)
2886                 {
2887                         DoEmit (ec, true);
2888                 }
2889                 
2890                 public override void EmitStatement (EmitContext ec)
2891                 {
2892                         if (DoEmit (ec, false))
2893                                 ec.ig.Emit (OpCodes.Pop);
2894                 }
2895         }
2896
2897         /// <summary>
2898         ///   Represents an array creation expression.
2899         /// </summary>
2900         ///
2901         /// <remarks>
2902         ///   There are two possible scenarios here: one is an array creation
2903         ///   expression that specifies the dimensions and optionally the
2904         ///   initialization data
2905         /// </remarks>
2906         public class ArrayCreation : ExpressionStatement {
2907
2908                 string RequestedType;
2909                 string Rank;
2910                 ArrayList Initializers;
2911                 Location  loc;
2912                 ArrayList Arguments;
2913
2914                 MethodBase method = null;
2915                 Type array_element_type;
2916                 bool IsOneDimensional = false;
2917                 
2918                 bool IsBuiltinType = false;
2919
2920                 int dimensions = 0;
2921                 Type underlying_type;
2922
2923                 ArrayList ArrayData;
2924
2925                 public ArrayCreation (string requested_type, ArrayList exprs,
2926                                       string rank, ArrayList initializers, Location l)
2927                 {
2928                         RequestedType = requested_type;
2929                         Rank          = rank;
2930                         Initializers  = initializers;
2931                         loc = l;
2932
2933                         Arguments = new ArrayList ();
2934
2935                         foreach (Expression e in exprs)
2936                                 Arguments.Add (new Argument (e, Argument.AType.Expression));
2937                         
2938                 }
2939
2940                 public ArrayCreation (string requested_type, string rank, ArrayList initializers, Location l)
2941                 {
2942                         RequestedType = requested_type;
2943                         Initializers = initializers;
2944                         loc = l;
2945
2946                         Rank = rank.Substring (0, rank.LastIndexOf ("["));
2947
2948                         string tmp = rank.Substring (rank.LastIndexOf ("["));
2949
2950                         dimensions = tmp.Length - 1;
2951                 }
2952
2953                 public static string FormArrayType (string base_type, int idx_count, string rank)
2954                 {
2955                         StringBuilder sb = new StringBuilder (base_type);
2956
2957                         sb.Append (rank);
2958                         
2959                         sb.Append ("[");
2960                         for (int i = 1; i < idx_count; i++)
2961                                 sb.Append (",");
2962                         sb.Append ("]");
2963                         
2964                         return sb.ToString ();
2965                 }
2966
2967                 public static string FormElementType (string base_type, int idx_count, string rank)
2968                 {
2969                         StringBuilder sb = new StringBuilder (base_type);
2970                         
2971                         sb.Append ("[");
2972                         for (int i = 1; i < idx_count; i++)
2973                                 sb.Append (",");
2974                         sb.Append ("]");
2975
2976                         sb.Append (rank);
2977
2978                         string val = sb.ToString ();
2979
2980                         return val.Substring (0, val.LastIndexOf ("["));
2981                 }
2982
2983                 void error178 ()
2984                 {
2985                         Report.Error (178, loc, "Incorrectly structured array initializer");
2986                 }
2987                 
2988                 public bool CheckIndices (EmitContext ec, ArrayList probe, int idx,
2989                                           bool require_constant, bool specified_dims)
2990                 {
2991                         foreach (object o in probe) {
2992
2993                                 if (o is ArrayList) {
2994
2995                                         if (specified_dims) { 
2996                                                 Argument a = (Argument) Arguments [idx];
2997                                                 
2998                                                 if (!a.Resolve (ec, loc))
2999                                                         return false;
3000                                                 
3001                                                 Expression e = Expression.Reduce (ec, a.Expr);
3002                                                 
3003                                                 if (!(e is Literal) && require_constant) {
3004                                                         Report.Error (150, loc, "A constant value is expected");
3005                                                         return false;
3006                                                 }
3007                                                 
3008                                                 int value = (int) ((Literal) e).GetValue ();
3009                                                 
3010                                                 if (value != probe.Count) {
3011                                                         error178 ();
3012                                                         return false;
3013                                                 }
3014                                         }
3015
3016                                         bool ret = CheckIndices (ec, (ArrayList) o, ++idx,
3017                                                                  require_constant, specified_dims);
3018                                         if (!ret)
3019                                                 return false;
3020                                         
3021                                 } else {
3022
3023                                         Expression tmp = (Expression) o;
3024                                         tmp = tmp.Resolve (ec);
3025                                         tmp = Expression.Reduce (ec, tmp);
3026                                         
3027                                         if (!(tmp is Literal) && require_constant) {
3028                                                 Report.Error (150, loc, "A constant value is expected");
3029                                                 return false;
3030                                         }
3031                                         
3032                                         Expression conv = ConvertImplicitRequired (ec, tmp,
3033                                                                                    underlying_type, loc);
3034                                         
3035                                         if (conv == null) 
3036                                                 return false;
3037
3038                                         ArrayData.Add (((Literal) tmp).GetValue ());
3039                                 }
3040                         }
3041
3042                         return true;
3043                 }
3044                 
3045                 public void UpdateIndices (EmitContext ec)
3046                 {                       
3047                         for (ArrayList probe = Initializers; probe != null;) {
3048
3049                                 if (probe [0] is ArrayList) {
3050                                         Expression e = new IntLiteral (probe.Count);
3051                                         Arguments.Add (new Argument (e, Argument.AType.Expression));
3052
3053                                         probe = (ArrayList) probe [0];
3054                                         
3055                                 } else {
3056                                         Expression e = new IntLiteral (probe.Count);
3057                                         Arguments.Add (new Argument (e, Argument.AType.Expression));
3058                                         
3059                                         probe = null;
3060                                 }
3061                         }
3062
3063                 }
3064                 
3065                 public bool ValidateInitializers (EmitContext ec)
3066                 {
3067                         if (Initializers == null)
3068                                 return true;
3069
3070                         underlying_type = ec.TypeContainer.LookupType (RequestedType, false);
3071
3072                         //
3073                         // We use this to store all the date values in the order in which we
3074                         // will need to store them in the byte blob later
3075                         //
3076                         ArrayData = new ArrayList ();
3077                         
3078                         bool ret;
3079
3080                         if (Arguments != null) {
3081                                 ret = CheckIndices (ec, Initializers, 0, true, true);
3082                                 return ret;
3083                                 
3084                         } else {
3085                                 Arguments = new ArrayList ();
3086
3087                                 ret = CheckIndices (ec, Initializers, 0, true, false);
3088                                 
3089                                 if (!ret)
3090                                         return false;
3091                                 
3092                                 UpdateIndices (ec);
3093                                 
3094                                 if (Arguments.Count != dimensions) {
3095                                         error178 ();
3096                                         return false;
3097                                 }
3098
3099                                 return ret;
3100                         }
3101                 }
3102                 
3103                 public override Expression DoResolve (EmitContext ec)
3104                 {
3105                         int arg_count;
3106
3107                         if (!ValidateInitializers (ec))
3108                                 return null;
3109
3110                         if (Arguments == null)
3111                                 arg_count = 0;
3112                         else
3113                                 arg_count = Arguments.Count;
3114                         
3115                         string array_type = FormArrayType (RequestedType, arg_count, Rank);
3116
3117                         string element_type = FormElementType (RequestedType, arg_count, Rank);
3118
3119                         type = ec.TypeContainer.LookupType (array_type, false);
3120                         
3121                         array_element_type = ec.TypeContainer.LookupType (element_type, false);
3122                         
3123                         if (type == null)
3124                                 return null;
3125                         
3126                         if (arg_count == 1) {
3127                                 IsOneDimensional = true;
3128                                 eclass = ExprClass.Value;
3129                                 return this;
3130                         }
3131
3132                         IsBuiltinType = TypeManager.IsBuiltinType (type);
3133                         
3134                         if (IsBuiltinType) {
3135                                 
3136                                 Expression ml;
3137                                 
3138                                 ml = MemberLookup (ec, type, ".ctor", false, MemberTypes.Constructor,
3139                                                    AllBindingsFlags, loc);
3140                                 
3141                                 if (!(ml is MethodGroupExpr)){
3142                                         report118 (loc, ml, "method group");
3143                                         return null;
3144                                 }
3145                                 
3146                                 if (ml == null) {
3147                                         Report.Error (-6, loc, "New invocation: Can not find a constructor for " +
3148                                                       "this argument list");
3149                                         return null;
3150                                 }
3151                                 
3152                                 if (Arguments != null) {
3153                                         for (int i = arg_count; i > 0;){
3154                                                 --i;
3155                                                 Argument a = (Argument) Arguments [i];
3156                                                 
3157                                                 if (!a.Resolve (ec, loc))
3158                                                         return null;
3159                                         }
3160                                 }
3161                                 
3162                                 method = Invocation.OverloadResolve (ec, (MethodGroupExpr) ml, Arguments, loc);
3163                                 
3164                                 if (method == null) {
3165                                         Report.Error (-6, loc, "New invocation: Can not find a constructor for " +
3166                                                       "this argument list");
3167                                         return null;
3168                                 }
3169                                 
3170                                 eclass = ExprClass.Value;
3171                                 return this;
3172                                 
3173                         } else {
3174
3175                                 ModuleBuilder mb = ec.TypeContainer.RootContext.ModuleBuilder;
3176
3177                                 ArrayList args = new ArrayList ();
3178                                 if (Arguments != null){
3179                                         for (int i = arg_count; i > 0;){
3180                                                 --i;
3181                                                 Argument a = (Argument) Arguments [i];
3182                                                 
3183                                                 if (!a.Resolve (ec, loc))
3184                                                         return null;
3185                                                 
3186                                                 args.Add (a.Type);
3187                                         }
3188                                 }
3189                                 
3190                                 Type [] arg_types = null;
3191                                 
3192                                 if (args.Count > 0)
3193                                         arg_types = new Type [args.Count];
3194                                 
3195                                 args.CopyTo (arg_types, 0);
3196                                 
3197                                 method = mb.GetArrayMethod (type, ".ctor", CallingConventions.HasThis, null,
3198                                                             arg_types);
3199                                 
3200                                 if (method == null) {
3201                                         Report.Error (-6, loc, "New invocation: Can not find a constructor for " +
3202                                                       "this argument list");
3203                                         return null;
3204                                 }
3205                                 
3206                                 eclass = ExprClass.Value;
3207                                 return this;
3208                                 
3209                         }
3210                 }
3211
3212                 public static byte [] MakeByteBlob (ArrayList ArrayData, Type underlying_type, Location loc)
3213                 {
3214                         int factor;
3215                         byte [] data;
3216
3217                         int count = ArrayData.Count;
3218
3219                         if (underlying_type == TypeManager.int32_type ||
3220                             underlying_type == TypeManager.uint32_type ||
3221                             underlying_type == TypeManager.float_type)
3222                                 factor = 4;
3223                         else if (underlying_type == TypeManager.int64_type ||
3224                                  underlying_type == TypeManager.uint64_type ||
3225                                  underlying_type == TypeManager.double_type)
3226                                 factor = 8;
3227                         else if (underlying_type == TypeManager.byte_type ||
3228                                  underlying_type == TypeManager.sbyte_type ||
3229                                  underlying_type == TypeManager.char_type ||
3230                                  underlying_type == TypeManager.bool_type)      
3231                                 factor = 1;
3232                         else if (underlying_type == TypeManager.short_type ||
3233                                  underlying_type == TypeManager.ushort_type)
3234                                 factor = 2;
3235                         else {  
3236                                 Report.Error (-100, loc, "Unhandled type in MakeByteBlob!!");
3237                                 return null;
3238                         }
3239
3240                         data = new byte [count * factor];
3241                         
3242                         for (int i = 0; i < count; ++i) {
3243                                 int val = (int) ArrayData [i];
3244                                 for (int j = 0; j < factor; ++j) {
3245                                         data [(i * factor) + j] = (byte) (val & 0xFF);
3246                                         val = val >> 8;
3247                                 }
3248                         }
3249                         
3250                         return data;
3251                 }
3252                 
3253                 public override void Emit (EmitContext ec)
3254                 {
3255                         ILGenerator ig = ec.ig;
3256                         
3257                         if (IsOneDimensional) {
3258                                 Invocation.EmitArguments (ec, null, Arguments);
3259                                 ig.Emit (OpCodes.Newarr, array_element_type);
3260                                 
3261                         } else {
3262                                 Invocation.EmitArguments (ec, null, Arguments);
3263
3264                                 if (IsBuiltinType)
3265                                         ig.Emit (OpCodes.Newobj, (ConstructorInfo) method);
3266                                 else
3267                                         ig.Emit (OpCodes.Newobj, (MethodInfo) method);
3268                         }
3269
3270                         if (Initializers != null) {
3271                                 FieldBuilder fb;
3272
3273                                 byte [] data = MakeByteBlob (ArrayData, underlying_type, loc);
3274
3275                                 if (data != null) {
3276                                         fb = ec.TypeContainer.RootContext.MakeStaticData (data);
3277                                         
3278                                         ig.Emit (OpCodes.Dup);
3279                                         ig.Emit (OpCodes.Ldtoken, fb);
3280                                         ig.Emit (OpCodes.Call, TypeManager.void_initializearray_array_fieldhandle);
3281                                 }
3282                         }
3283                 }
3284                 
3285                 public override void EmitStatement (EmitContext ec)
3286                 {
3287                         Emit (ec);
3288                         ec.ig.Emit (OpCodes.Pop);
3289                 }
3290                 
3291         }
3292         
3293         /// <summary>
3294         ///   Represents the `this' construct
3295         /// </summary>
3296         public class This : Expression, IAssignMethod, IMemoryLocation {
3297                 Location loc;
3298                 
3299                 public This (Location loc)
3300                 {
3301                         this.loc = loc;
3302                 }
3303
3304                 public override Expression DoResolve (EmitContext ec)
3305                 {
3306                         eclass = ExprClass.Variable;
3307                         type = ec.TypeContainer.TypeBuilder;
3308
3309                         if (ec.IsStatic){
3310                                 Report.Error (26, loc,
3311                                               "Keyword this not valid in static code");
3312                                 return null;
3313                         }
3314                         
3315                         return this;
3316                 }
3317
3318                 public Expression DoResolveLValue (EmitContext ec)
3319                 {
3320                         DoResolve (ec);
3321                         
3322                         if (ec.TypeContainer is Class){
3323                                 Report.Error (1604, loc, "Cannot assign to `this'");
3324                                 return null;
3325                         }
3326
3327                         return this;
3328                 }
3329
3330                 public override void Emit (EmitContext ec)
3331                 {
3332                         ec.ig.Emit (OpCodes.Ldarg_0);
3333                 }
3334
3335                 public void EmitAssign (EmitContext ec, Expression source)
3336                 {
3337                         source.Emit (ec);
3338                         ec.ig.Emit (OpCodes.Starg, 0);
3339                 }
3340
3341                 public void AddressOf (EmitContext ec)
3342                 {
3343                         ec.ig.Emit (OpCodes.Ldarga_S, (byte) 0);
3344                 }
3345         }
3346
3347         /// <summary>
3348         ///   Implements the typeof operator
3349         /// </summary>
3350         public class TypeOf : Expression {
3351                 public readonly string QueriedType;
3352                 Type typearg;
3353                 
3354                 public TypeOf (string queried_type)
3355                 {
3356                         QueriedType = queried_type;
3357                 }
3358
3359                 public override Expression DoResolve (EmitContext ec)
3360                 {
3361                         typearg = ec.TypeContainer.LookupType (QueriedType, false);
3362
3363                         if (typearg == null)
3364                                 return null;
3365
3366                         type = TypeManager.type_type;
3367                         eclass = ExprClass.Type;
3368                         return this;
3369                 }
3370
3371                 public override void Emit (EmitContext ec)
3372                 {
3373                         ec.ig.Emit (OpCodes.Ldtoken, typearg);
3374                         ec.ig.Emit (OpCodes.Call, TypeManager.system_type_get_type_from_handle);
3375                 }
3376         }
3377
3378         /// <summary>
3379         ///   Implements the sizeof expression
3380         /// </summary>
3381         public class SizeOf : Expression {
3382                 public readonly string QueriedType;
3383                 
3384                 public SizeOf (string queried_type)
3385                 {
3386                         this.QueriedType = queried_type;
3387                 }
3388
3389                 public override Expression DoResolve (EmitContext ec)
3390                 {
3391                         // FIXME: Implement;
3392                         throw new Exception ("Unimplemented");
3393                         // return this;
3394                 }
3395
3396                 public override void Emit (EmitContext ec)
3397                 {
3398                         throw new Exception ("Implement me");
3399                 }
3400         }
3401
3402         /// <summary>
3403         ///   Implements the member access expression
3404         /// </summary>
3405         public class MemberAccess : Expression {
3406                 public readonly string Identifier;
3407                 Expression expr;
3408                 Expression member_lookup;
3409                 Location loc;
3410                 
3411                 public MemberAccess (Expression expr, string id, Location l)
3412                 {
3413                         this.expr = expr;
3414                         Identifier = id;
3415                         loc = l;
3416                 }
3417
3418                 public Expression Expr {
3419                         get {
3420                                 return expr;
3421                         }
3422                 }
3423
3424                 void error176 (Location loc, string name)
3425                 {
3426                         Report.Error (176, loc, "Static member `" +
3427                                       name + "' cannot be accessed " +
3428                                       "with an instance reference, qualify with a " +
3429                                       "type name instead");
3430                 }
3431                 
3432                 public override Expression DoResolve (EmitContext ec)
3433                 {
3434                         //
3435                         // We are the sole users of ResolveWithSimpleName (ie, the only
3436                         // ones that can cope with it
3437                         //
3438                         expr = expr.ResolveWithSimpleName (ec);
3439
3440                         if (expr == null)
3441                                 return null;
3442
3443                         if (expr is SimpleName){
3444                                 SimpleName child_expr = (SimpleName) expr;
3445
3446                                 expr = new SimpleName (child_expr.Name + "." + Identifier, loc);
3447
3448                                 return expr.Resolve (ec);
3449                         }
3450                                         
3451                         member_lookup = MemberLookup (ec, expr.Type, Identifier, false, loc);
3452
3453                         if (member_lookup == null)
3454                                 return null;
3455                         
3456                         //
3457                         // Method Groups
3458                         //
3459                         if (member_lookup is MethodGroupExpr){
3460                                 MethodGroupExpr mg = (MethodGroupExpr) member_lookup;
3461                                 
3462                                 //
3463                                 // Type.MethodGroup
3464                                 //
3465                                 if (expr is TypeExpr){
3466                                         if (!mg.RemoveInstanceMethods ()){
3467                                                 SimpleName.Error120 (loc, mg.Methods [0].Name); 
3468                                                 return null;
3469                                         }
3470
3471                                         return member_lookup;
3472                                 }
3473
3474                                 //
3475                                 // Instance.MethodGroup
3476                                 //
3477                                 if (!mg.RemoveStaticMethods ()){
3478                                         error176 (loc, mg.Methods [0].Name);
3479                                         return null;
3480                                 }
3481                                 
3482                                 mg.InstanceExpression = expr;
3483                                         
3484                                 return member_lookup;
3485                         }
3486
3487                         if (member_lookup is FieldExpr){
3488                                 FieldExpr fe = (FieldExpr) member_lookup;
3489                                 FieldInfo fi = fe.FieldInfo;
3490
3491                                 if (fi.IsLiteral) {
3492                                         Type t = fi.FieldType;
3493                                         Type decl_type = fi.DeclaringType;
3494                                         object o;
3495
3496                                         if (fi is FieldBuilder)
3497                                                 o = TypeManager.GetValue ((FieldBuilder) fi);
3498                                         else
3499                                                 o = fi.GetValue (fi);
3500                                         
3501                                         if (decl_type.IsSubclassOf (TypeManager.enum_type)) {
3502                                                 Expression enum_member = MemberLookup (ec, decl_type, "value__",
3503                                                                                        false, loc); 
3504
3505                                                 Enum en = TypeManager.LookupEnum (decl_type);
3506
3507                                                 Expression e;
3508                                                 if (en != null)
3509                                                         e = Literalize (o, en.UnderlyingType);
3510                                                 else 
3511                                                         e = Literalize (o, enum_member.Type);
3512                                                 
3513                                                 e.Resolve (ec);
3514                                                 return new EnumLiteral (e, decl_type);
3515                                         }
3516                                         
3517                                         Expression exp = Literalize (o, t);
3518                                         exp.Resolve (ec);
3519                                         
3520                                         return exp;
3521                                 }
3522                                 
3523                                 if (expr is TypeExpr){
3524                                         if (!fe.FieldInfo.IsStatic){
3525                                                 error176 (loc, fe.FieldInfo.Name);
3526                                                 return null;
3527                                         }
3528                                         return member_lookup;
3529                                 } else {
3530                                         if (fe.FieldInfo.IsStatic){
3531                                                 error176 (loc, fe.FieldInfo.Name);
3532                                                 return null;
3533                                         }
3534                                         fe.InstanceExpression = expr;
3535
3536                                         return fe;
3537                                 }
3538                         }
3539
3540                         if (member_lookup is PropertyExpr){
3541                                 PropertyExpr pe = (PropertyExpr) member_lookup;
3542
3543                                 if (expr is TypeExpr){
3544                                         if (!pe.IsStatic){
3545                                                 SimpleName.Error120 (loc, pe.PropertyInfo.Name);
3546                                                 return null;
3547                                         }
3548                                         return pe;
3549                                 } else {
3550                                         if (pe.IsStatic){
3551                                                 error176 (loc, pe.PropertyInfo.Name);
3552                                                 return null;
3553                                         }
3554                                         pe.InstanceExpression = expr;
3555
3556                                         return pe;
3557                                 }
3558                         }
3559                         
3560                         Console.WriteLine ("Support for [" + member_lookup + "] is not present yet");
3561                         Environment.Exit (0);
3562                         return null;
3563                 }
3564
3565                 public override void Emit (EmitContext ec)
3566                 {
3567                         throw new Exception ("Should not happen I think");
3568                 }
3569         }
3570
3571         /// <summary>
3572         ///   Implements checked expressions
3573         /// </summary>
3574         public class CheckedExpr : Expression {
3575
3576                 public Expression Expr;
3577
3578                 public CheckedExpr (Expression e)
3579                 {
3580                         Expr = e;
3581                 }
3582
3583                 public override Expression DoResolve (EmitContext ec)
3584                 {
3585                         Expr = Expr.Resolve (ec);
3586
3587                         if (Expr == null)
3588                                 return null;
3589
3590                         eclass = Expr.ExprClass;
3591                         type = Expr.Type;
3592                         return this;
3593                 }
3594
3595                 public override void Emit (EmitContext ec)
3596                 {
3597                         bool last_check = ec.CheckState;
3598                         
3599                         ec.CheckState = true;
3600                         Expr.Emit (ec);
3601                         ec.CheckState = last_check;
3602                 }
3603                 
3604         }
3605
3606         /// <summary>
3607         ///   Implements the unchecked expression
3608         /// </summary>
3609         public class UnCheckedExpr : Expression {
3610
3611                 public Expression Expr;
3612
3613                 public UnCheckedExpr (Expression e)
3614                 {
3615                         Expr = e;
3616                 }
3617
3618                 public override Expression DoResolve (EmitContext ec)
3619                 {
3620                         Expr = Expr.Resolve (ec);
3621
3622                         if (Expr == null)
3623                                 return null;
3624
3625                         eclass = Expr.ExprClass;
3626                         type = Expr.Type;
3627                         return this;
3628                 }
3629
3630                 public override void Emit (EmitContext ec)
3631                 {
3632                         bool last_check = ec.CheckState;
3633                         
3634                         ec.CheckState = false;
3635                         Expr.Emit (ec);
3636                         ec.CheckState = last_check;
3637                 }
3638                 
3639         }
3640
3641         /// <summary>
3642         ///   An Element Access expression.  During semantic
3643         ///   analysis these are transformed into IndexerAccess or
3644         ///   ArrayAccess expressions
3645         /// </summary>
3646         public class ElementAccess : Expression {
3647                 public ArrayList  Arguments;
3648                 public Expression Expr;
3649                 public Location   loc;
3650                 
3651                 public ElementAccess (Expression e, ArrayList e_list, Location l)
3652                 {
3653                         Expr = e;
3654
3655                         Arguments = new ArrayList ();
3656                         foreach (Expression tmp in e_list)
3657                                 Arguments.Add (new Argument (tmp, Argument.AType.Expression));
3658                         
3659                         loc  = l;
3660                 }
3661
3662                 bool CommonResolve (EmitContext ec)
3663                 {
3664                         Expr = Expr.Resolve (ec);
3665
3666                         if (Expr == null) 
3667                                 return false;
3668
3669                         if (Arguments == null)
3670                                 return false;
3671
3672                         for (int i = Arguments.Count; i > 0;){
3673                                 --i;
3674                                 Argument a = (Argument) Arguments [i];
3675                                 
3676                                 if (!a.Resolve (ec, loc))
3677                                         return false;
3678                         }
3679
3680                         return true;
3681                 }
3682                                 
3683                 public override Expression DoResolve (EmitContext ec)
3684                 {
3685                         if (!CommonResolve (ec))
3686                                 return null;
3687
3688                         //
3689                         // We perform some simple tests, and then to "split" the emit and store
3690                         // code we create an instance of a different class, and return that.
3691                         //
3692                         // I am experimenting with this pattern.
3693                         //
3694                         if (Expr.Type.IsSubclassOf (TypeManager.array_type))
3695                                 return (new ArrayAccess (this)).Resolve (ec);
3696                         else
3697                                 return (new IndexerAccess (this)).Resolve (ec);
3698                 }
3699
3700                 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
3701                 {
3702                         if (!CommonResolve (ec))
3703                                 return null;
3704
3705                         if (Expr.Type.IsSubclassOf (TypeManager.array_type))
3706                                 return (new ArrayAccess (this)).ResolveLValue (ec, right_side);
3707                         else
3708                                 return (new IndexerAccess (this)).ResolveLValue (ec, right_side);
3709                 }
3710                 
3711                 public override void Emit (EmitContext ec)
3712                 {
3713                         throw new Exception ("Should never be reached");
3714                 }
3715         }
3716
3717         /// <summary>
3718         ///   Implements array access 
3719         /// </summary>
3720         public class ArrayAccess : Expression, IAssignMethod {
3721                 //
3722                 // Points to our "data" repository
3723                 //
3724                 ElementAccess ea;
3725                 
3726                 public ArrayAccess (ElementAccess ea_data)
3727                 {
3728                         ea = ea_data;
3729                         eclass = ExprClass.Variable;
3730                 }
3731
3732                 public override Expression DoResolve (EmitContext ec)
3733                 {
3734                         if (ea.Expr.ExprClass != ExprClass.Variable) {
3735                                 report118 (ea.loc, ea.Expr, "variable");
3736                                 return null;
3737                         }
3738
3739                         Type t = ea.Expr.Type;
3740
3741                         if (t.GetArrayRank () != ea.Arguments.Count){
3742                                 Report.Error (22, ea.loc,
3743                                               "Incorrect number of indexes for array " +
3744                                               " expected: " + t.GetArrayRank () + " got: " +
3745                                               ea.Arguments.Count);
3746                                 return null;
3747                         }
3748                         type = t.GetElementType ();
3749                         eclass = ExprClass.Variable;
3750
3751                         return this;
3752                 }
3753
3754                 /// <summary>
3755                 ///    Emits the right opcode to load an object of Type `t'
3756                 ///    from an array of T
3757                 /// </summary>
3758                 static public void EmitLoadOpcode (ILGenerator ig, Type type)
3759                 {
3760                         if (type == TypeManager.byte_type)
3761                                 ig.Emit (OpCodes.Ldelem_I1);
3762                         else if (type == TypeManager.sbyte_type)
3763                                 ig.Emit (OpCodes.Ldelem_U1);
3764                         else if (type == TypeManager.short_type)
3765                                 ig.Emit (OpCodes.Ldelem_I2);
3766                         else if (type == TypeManager.ushort_type)
3767                                 ig.Emit (OpCodes.Ldelem_U2);
3768                         else if (type == TypeManager.int32_type)
3769                                 ig.Emit (OpCodes.Ldelem_I4);
3770                         else if (type == TypeManager.uint32_type)
3771                                 ig.Emit (OpCodes.Ldelem_U4);
3772                         else if (type == TypeManager.uint64_type)
3773                                 ig.Emit (OpCodes.Ldelem_I8);
3774                         else if (type == TypeManager.int64_type)
3775                                 ig.Emit (OpCodes.Ldelem_I8);
3776                         else if (type == TypeManager.float_type)
3777                                 ig.Emit (OpCodes.Ldelem_R4);
3778                         else if (type == TypeManager.double_type)
3779                                 ig.Emit (OpCodes.Ldelem_R8);
3780                         else if (type == TypeManager.intptr_type)
3781                                 ig.Emit (OpCodes.Ldelem_I);
3782                         else
3783                                 ig.Emit (OpCodes.Ldelem_Ref);
3784                 }
3785
3786                 /// <summary>
3787                 ///    Emits the right opcode to store an object of Type `t'
3788                 ///    from an array of T.  
3789                 /// </summary>
3790                 static public void EmitStoreOpcode (ILGenerator ig, Type t)
3791                 {
3792                         if (t == TypeManager.byte_type || t == TypeManager.sbyte_type)
3793                                 ig.Emit (OpCodes.Stelem_I1);
3794                         else if (t == TypeManager.short_type || t == TypeManager.ushort_type)
3795                                 ig.Emit (OpCodes.Stelem_I2);
3796                         else if (t == TypeManager.int32_type || t == TypeManager.uint32_type)
3797                                 ig.Emit (OpCodes.Stelem_I4);
3798                         else if (t == TypeManager.int64_type || t == TypeManager.uint64_type)
3799                                 ig.Emit (OpCodes.Stelem_I8);
3800                         else if (t == TypeManager.float_type)
3801                                 ig.Emit (OpCodes.Stelem_R4);
3802                         else if (t == TypeManager.double_type)
3803                                 ig.Emit (OpCodes.Stelem_R8);
3804                         else if (t == TypeManager.intptr_type)
3805                                 ig.Emit (OpCodes.Stelem_I);
3806                         else
3807                                 ig.Emit (OpCodes.Stelem_Ref);
3808                 }
3809                 
3810                 public override void Emit (EmitContext ec)
3811                 {
3812                         int rank = ea.Expr.Type.GetArrayRank ();
3813                         ILGenerator ig = ec.ig;
3814
3815                         ea.Expr.Emit (ec);
3816
3817                         foreach (Argument a in ea.Arguments)
3818                                 a.Expr.Emit (ec);
3819
3820                         if (rank == 1)
3821                                 EmitLoadOpcode (ig, type);
3822                         else {
3823                                 ModuleBuilder mb = ec.TypeContainer.RootContext.ModuleBuilder;
3824                                 Type [] args = new Type [ea.Arguments.Count];
3825                                 MethodInfo get;
3826                                 
3827                                 int i = 0;
3828                                 
3829                                 foreach (Argument a in ea.Arguments)
3830                                         args [i++] = a.Type;
3831                                 
3832                                 get = mb.GetArrayMethod (
3833                                         ea.Expr.Type, "Get",
3834                                         CallingConventions.HasThis |
3835                                         CallingConventions.Standard,
3836                                         type, args);
3837                                 
3838                                 ig.Emit (OpCodes.Call, get);
3839                         }
3840                 }
3841
3842                 public void EmitAssign (EmitContext ec, Expression source)
3843                 {
3844                         int rank = ea.Expr.Type.GetArrayRank ();
3845                         ILGenerator ig = ec.ig;
3846
3847                         ea.Expr.Emit (ec);
3848
3849                         foreach (Argument a in ea.Arguments)
3850                                 a.Expr.Emit (ec);
3851
3852                         source.Emit (ec);
3853
3854                         Type t = source.Type;
3855                         if (rank == 1)
3856                                 EmitStoreOpcode (ig, t);
3857                         else {
3858                                 ModuleBuilder mb = ec.TypeContainer.RootContext.ModuleBuilder;
3859                                 Type [] args = new Type [ea.Arguments.Count + 1];
3860                                 MethodInfo set;
3861                                 
3862                                 int i = 0;
3863                                 
3864                                 foreach (Argument a in ea.Arguments)
3865                                         args [i++] = a.Type;
3866
3867                                 args [i] = type;
3868                                 
3869                                 set = mb.GetArrayMethod (
3870                                         ea.Expr.Type, "Set",
3871                                         CallingConventions.HasThis |
3872                                         CallingConventions.Standard,
3873                                         TypeManager.void_type, args);
3874                                 
3875                                 ig.Emit (OpCodes.Call, set);
3876                         }
3877                 }
3878         }
3879
3880         
3881         class Indexers {
3882                 public ArrayList getters, setters;
3883                 static Hashtable map;
3884
3885                 static Indexers ()
3886                 {
3887                         map = new Hashtable ();
3888                 }
3889
3890                 Indexers (MemberInfo [] mi)
3891                 {
3892                         foreach (PropertyInfo property in mi){
3893                                 MethodInfo get, set;
3894                                 
3895                                 get = property.GetGetMethod (true);
3896                                 if (get != null){
3897                                         if (getters == null)
3898                                                 getters = new ArrayList ();
3899
3900                                         getters.Add (get);
3901                                 }
3902                                 
3903                                 set = property.GetSetMethod (true);
3904                                 if (set != null){
3905                                         if (setters == null)
3906                                                 setters = new ArrayList ();
3907                                         setters.Add (set);
3908                                 }
3909                         }
3910                 }
3911                 
3912                 static public Indexers GetIndexersForType (Type t, TypeManager tm, Location loc) 
3913                 {
3914                         Indexers ix = (Indexers) map [t];
3915                         string p_name = TypeManager.IndexerPropertyName (t);
3916                         
3917                         if (ix != null)
3918                                 return ix;
3919
3920                         MemberInfo [] mi = tm.FindMembers (
3921                                 t, MemberTypes.Property,
3922                                 BindingFlags.Public | BindingFlags.Instance,
3923                                 Type.FilterName, p_name);
3924
3925                         if (mi == null || mi.Length == 0){
3926                                 Report.Error (21, loc,
3927                                               "Type `" + TypeManager.CSharpName (t) + "' does not have " +
3928                                               "any indexers defined");
3929                                 return null;
3930                         }
3931                         
3932                         ix = new Indexers (mi);
3933                         map [t] = ix;
3934
3935                         return ix;
3936                 }
3937         }
3938
3939         /// <summary>
3940         ///   Expressions that represent an indexer call.
3941         /// </summary>
3942         public class IndexerAccess : Expression, IAssignMethod {
3943                 //
3944                 // Points to our "data" repository
3945                 //
3946                 ElementAccess ea;
3947                 MethodInfo get, set;
3948                 Indexers ilist;
3949                 ArrayList set_arguments;
3950                 
3951                 public IndexerAccess (ElementAccess ea_data)
3952                 {
3953                         ea = ea_data;
3954                         eclass = ExprClass.Value;
3955                 }
3956
3957                 public override Expression DoResolve (EmitContext ec)
3958                 {
3959                         Type indexer_type = ea.Expr.Type;
3960                         
3961                         //
3962                         // Step 1: Query for all `Item' *properties*.  Notice
3963                         // that the actual methods are pointed from here.
3964                         //
3965                         // This is a group of properties, piles of them.  
3966
3967                         if (ilist == null)
3968                                 ilist = Indexers.GetIndexersForType (
3969                                         indexer_type, ec.TypeContainer.RootContext.TypeManager, ea.loc);
3970
3971
3972                         //
3973                         // Step 2: find the proper match
3974                         //
3975                         if (ilist != null && ilist.getters != null && ilist.getters.Count > 0)
3976                                 get = (MethodInfo) Invocation.OverloadResolve (
3977                                         ec, new MethodGroupExpr (ilist.getters), ea.Arguments, ea.loc);
3978
3979                         if (get == null){
3980                                 Report.Error (154, ea.loc,
3981                                               "indexer can not be used in this context, because " +
3982                                               "it lacks a `get' accessor");
3983                                 return null;
3984                         }
3985
3986                         type = get.ReturnType;
3987                         eclass = ExprClass.IndexerAccess;
3988                         return this;
3989                 }
3990
3991                 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
3992                 {
3993                         Type indexer_type = ea.Expr.Type;
3994                         Type right_type = right_side.Type;
3995
3996                         if (ilist == null)
3997                                 ilist = Indexers.GetIndexersForType (
3998                                         indexer_type, ec.TypeContainer.RootContext.TypeManager, ea.loc);
3999
4000                         if (ilist != null && ilist.setters != null && ilist.setters.Count > 0){
4001                                 set_arguments = (ArrayList) ea.Arguments.Clone ();
4002                                 set_arguments.Add (new Argument (right_side, Argument.AType.Expression));
4003
4004                                 set = (MethodInfo) Invocation.OverloadResolve (
4005                                         ec, new MethodGroupExpr (ilist.setters), set_arguments, ea.loc);
4006                         }
4007                         
4008                         if (set == null){
4009                                 Report.Error (200, ea.loc,
4010                                               "indexer X.this [" + TypeManager.CSharpName (right_type) +
4011                                               "] lacks a `set' accessor");
4012                                         return null;
4013                         }
4014
4015                         type = TypeManager.void_type;
4016                         eclass = ExprClass.IndexerAccess;
4017                         return this;
4018                 }
4019                 
4020                 public override void Emit (EmitContext ec)
4021                 {
4022                         Invocation.EmitCall (ec, false, ea.Expr, get, ea.Arguments);
4023                 }
4024
4025                 //
4026                 // source is ignored, because we already have a copy of it from the
4027                 // LValue resolution and we have already constructed a pre-cached
4028                 // version of the arguments (ea.set_arguments);
4029                 //
4030                 public void EmitAssign (EmitContext ec, Expression source)
4031                 {
4032                         Invocation.EmitCall (ec, false, ea.Expr, set, set_arguments);
4033                 }
4034         }
4035         
4036         public class BaseAccess : Expression {
4037
4038                 public enum BaseAccessType : byte {
4039                         Member,
4040                         Indexer
4041                 };
4042                 
4043                 public readonly BaseAccessType BAType;
4044                 public readonly string         Member;
4045                 public readonly ArrayList      Arguments;
4046
4047                 public BaseAccess (BaseAccessType t, string member, ArrayList args)
4048                 {
4049                         BAType = t;
4050                         Member = member;
4051                         Arguments = args;
4052                         
4053                 }
4054
4055                 public override Expression DoResolve (EmitContext ec)
4056                 {
4057                         // FIXME: Implement;
4058                         throw new Exception ("Unimplemented");
4059                         // return this;
4060                 }
4061
4062                 public override void Emit (EmitContext ec)
4063                 {
4064                         throw new Exception ("Unimplemented");
4065                 }
4066         }
4067
4068         /// <summary>
4069         ///   This class exists solely to pass the Type around and to be a dummy
4070         ///   that can be passed to the conversion functions (this is used by
4071         ///   foreach implementation to typecast the object return value from
4072         ///   get_Current into the proper type.  All code has been generated and
4073         ///   we only care about the side effect conversions to be performed
4074         /// </summary>
4075         public class EmptyExpression : Expression {
4076                 public EmptyExpression ()
4077                 {
4078                         type = TypeManager.object_type;
4079                         eclass = ExprClass.Value;
4080                 }
4081
4082                 public EmptyExpression (Type t)
4083                 {
4084                         type = t;
4085                         eclass = ExprClass.Value;
4086                 }
4087                 
4088                 public override Expression DoResolve (EmitContext ec)
4089                 {
4090                         return this;
4091                 }
4092
4093                 public override void Emit (EmitContext ec)
4094                 {
4095                         // nothing, as we only exist to not do anything.
4096                 }
4097         }
4098
4099         public class UserCast : Expression {
4100                 MethodBase method;
4101                 Expression source;
4102                 
4103                 public UserCast (MethodInfo method, Expression source)
4104                 {
4105                         this.method = method;
4106                         this.source = source;
4107                         type = method.ReturnType;
4108                         eclass = ExprClass.Value;
4109                 }
4110
4111                 public override Expression DoResolve (EmitContext ec)
4112                 {
4113                         //
4114                         // We are born fully resolved
4115                         //
4116                         return this;
4117                 }
4118
4119                 public override void Emit (EmitContext ec)
4120                 {
4121                         ILGenerator ig = ec.ig;
4122
4123                         source.Emit (ec);
4124                         
4125                         if (method is MethodInfo)
4126                                 ig.Emit (OpCodes.Call, (MethodInfo) method);
4127                         else
4128                                 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
4129
4130                 }
4131
4132         }
4133 }