2001-09-26 Miguel de Icaza <miguel@ximian.com>
[mono.git] / mcs / mcs / expression.cs
1 //
2 // expression.cs: Expression representation for the IL tree.
3 //
4 // Author:
5 //   Miguel de Icaza (miguel@ximian.com)
6 //
7 // (C) 2001 Ximian, Inc.
8 //
9 //
10 // Ideas:
11 //   Maybe we should make Resolve be an instance method that just calls
12 //   the virtual DoResolve function and checks conditions like the eclass
13 //   and type being set if a non-null value is returned.  For robustness
14 //   purposes.
15 //
16
17 namespace CIR {
18         using System.Collections;
19         using System.Diagnostics;
20         using System;
21         using System.Reflection;
22         using System.Reflection.Emit;
23         using System.Text;
24         
25         // <remarks>
26         //   The ExprClass class contains the is used to pass the 
27         //   classification of an expression (value, variable, namespace,
28         //   type, method group, property access, event access, indexer access,
29         //   nothing).
30         // </remarks>
31         public enum ExprClass {
32                 Invalid,
33                 
34                 Value,
35                 Variable,   // Every Variable should implement LValue
36                 Namespace,
37                 Type,
38                 MethodGroup,
39                 PropertyAccess,
40                 EventAccess,
41                 IndexerAccess,
42                 Nothing, 
43         }
44
45         // <remarks>
46         //   Base class for expressions
47         // </remarks>
48         public abstract class Expression {
49                 protected ExprClass eclass;
50                 protected Type      type;
51                 
52                 public Type Type {
53                         get {
54                                 return type;
55                         }
56
57                         set {
58                                 type = value;
59                         }
60                 }
61
62                 public ExprClass ExprClass {
63                         get {
64                                 return eclass;
65                         }
66
67                         set {
68                                 eclass = value;
69                         }
70                 }
71
72                 // <summary>
73                 //   Performs semantic analysis on the Expression
74                 // </summary>
75                 //
76                 // <remarks>
77                 //   The Resolve method is invoked to perform the semantic analysis
78                 //   on the node.
79                 //
80                 //   The return value is an expression (it can be the
81                 //   same expression in some cases) or a new
82                 //   expression that better represents this node.
83                 //   
84                 //   For example, optimizations of Unary (LiteralInt)
85                 //   would return a new LiteralInt with a negated
86                 //   value.
87                 //   
88                 //   If there is an error during semantic analysis,
89                 //   then an error should
90                 //   be reported (using TypeContainer.RootContext.Report) and a null
91                 //   value should be returned.
92                 //   
93                 //   There are two side effects expected from calling
94                 //   Resolve(): the the field variable "eclass" should
95                 //   be set to any value of the enumeration
96                 //   `ExprClass' and the type variable should be set
97                 //   to a valid type (this is the type of the
98                 //   expression).
99                 // </remarks>
100                 
101                 public abstract Expression Resolve (TypeContainer tc);
102
103                 // <summary>
104                 //   Emits the code for the expression
105                 // </summary>
106                 //
107                 // <remarks>
108                 // 
109                 //   The Emit method is invoked to generate the code
110                 //   for the expression.  
111                 //
112                 // </remarks>
113                 public abstract void Emit (EmitContext ec);
114                 
115                 // <summary>
116                 //   Protected constructor.  Only derivate types should
117                 //   be able to be created
118                 // </summary>
119
120                 protected Expression ()
121                 {
122                         eclass = ExprClass.Invalid;
123                         type = null;
124                 }
125
126                 // 
127                 // Returns a fully formed expression after a MemberLookup
128                 //
129                 static Expression ExprClassFromMemberInfo (MemberInfo mi)
130                 {
131                         if (mi is EventInfo){
132                                 return new EventExpr ((EventInfo) mi);
133                         } else if (mi is FieldInfo){
134                                 return new FieldExpr ((FieldInfo) mi);
135                         } else if (mi is PropertyInfo){
136                                 return new PropertyExpr ((PropertyInfo) mi);
137                         } else if (mi is Type)
138                                 return new TypeExpr ((Type) mi);
139
140                         return null;
141                 }
142                 
143                 //
144                 // FIXME: Probably implement a cache for (t,name,current_access_set)?
145                 //
146                 // FIXME: We need to cope with access permissions here, or this wont
147                 // work!
148                 //
149                 // This code could use some optimizations, but we need to do some
150                 // measurements.  For example, we could use a delegate to `flag' when
151                 // something can not any longer be a method-group (because it is something
152                 // else).
153                 //
154                 // Return values:
155                 //     If the return value is an Array, then it is an array of
156                 //     MethodBases
157                 //   
158                 //     If the return value is an MemberInfo, it is anything, but a Method
159                 //
160                 //     null on error.
161                 //
162                 // FIXME: When calling MemberLookup inside an `Invocation', we should pass
163                 // the arguments here and have MemberLookup return only the methods that
164                 // match the argument count/type, unlike we are doing now (we delay this
165                 // decision).
166                 //
167                 // This is so we can catch correctly attempts to invoke instance methods
168                 // from a static body (scan for error 120 in ResolveSimpleName).
169                 //
170                 public static Expression MemberLookup (RootContext rc, Type t, string name,
171                                                           bool same_type, MemberTypes mt, BindingFlags bf)
172                 {
173                         if (same_type)
174                                 bf |= BindingFlags.NonPublic;
175
176                         MemberInfo [] mi = rc.TypeManager.FindMembers (t, mt, bf, Type.FilterName, name);
177
178                         if (mi == null)
179                                 return null;
180                         
181                         if (mi.Length == 1 && !(mi [0] is MethodBase))
182                                 return Expression.ExprClassFromMemberInfo (mi [0]);
183                         
184                         for (int i = 0; i < mi.Length; i++)
185                                 if (!(mi [i] is MethodBase)){
186                                         rc.Report.Error (-5, "Do not know how to reproduce this case: " + 
187                                                          "Methods and non-Method with the same name, report this please");
188
189                                         for (i = 0; i < mi.Length; i++){
190                                                 Type tt = mi [i].GetType ();
191
192                                                 Console.WriteLine (i + ": " + mi [i]);
193                                                 while (tt != TypeManager.object_type){
194                                                         Console.WriteLine (tt);
195                                                         tt = tt.BaseType;
196                                                 }
197                                         }
198                                 }
199
200                         return new MethodGroupExpr (mi);
201                 }
202
203                 public const MemberTypes AllMemberTypes =
204                         MemberTypes.Constructor |
205                         MemberTypes.Event       |
206                         MemberTypes.Field       |
207                         MemberTypes.Method      |
208                         MemberTypes.NestedType  |
209                         MemberTypes.Property;
210                 
211                 public const BindingFlags AllBindingsFlags =
212                         BindingFlags.Public |
213                         BindingFlags.Static |
214                         BindingFlags.Instance;
215
216                 public static Expression MemberLookup (RootContext rc, Type t, string name,
217                                                        bool same_type)
218                 {
219                         return MemberLookup (rc, t, name, same_type, AllMemberTypes, AllBindingsFlags);
220                 }
221                 
222                 // <summary>
223                 //   Resolves the E in `E.I' side for a member_access
224                 //
225                 //   This is suboptimal and should be merged with ResolveMemberAccess
226                 // </summary>
227                 static Expression ResolvePrimary (TypeContainer tc, string name)
228                 {
229                         int dot_pos = name.LastIndexOf (".");
230
231                         if (tc.RootContext.IsNamespace (name))
232                                 return new NamespaceExpr (name);
233
234                         if (dot_pos != -1){
235                         } else {
236                                 Type t = tc.LookupType (name, false);
237
238                                 if (t != null)
239                                         return new TypeExpr (t);
240                         }
241
242                         return null;
243                 }
244                         
245                 static public Expression ResolveMemberAccess (TypeContainer tc, string name)
246                 {
247                         Expression left_e;
248                         int dot_pos = name.LastIndexOf (".");
249                         string left = name.Substring (0, dot_pos);
250                         string right = name.Substring (dot_pos + 1);
251
252                         left_e = ResolvePrimary (tc, left);
253                         if (left_e == null)
254                                 return null;
255
256                         switch (left_e.ExprClass){
257                         case ExprClass.Type:
258                                 return  MemberLookup (tc.RootContext,
259                                                       left_e.Type, right,
260                                                       left_e.Type == tc.TypeBuilder);
261                                 
262                         case ExprClass.Namespace:
263                         case ExprClass.PropertyAccess:
264                         case ExprClass.IndexerAccess:
265                         case ExprClass.Variable:
266                         case ExprClass.Value:
267                         case ExprClass.Nothing:
268                         case ExprClass.EventAccess:
269                         case ExprClass.MethodGroup:
270                         case ExprClass.Invalid:
271                                 tc.RootContext.Report.Error (-1000,
272                                                              "Internal compiler error, should have " +
273                                                              "got these handled before");
274                                 break;
275                         }
276                         
277                         return null;
278                 }
279
280                 static public Expression ImplicitReferenceConversion (Expression expr, Type target_type)
281                 {
282                         Type expr_type = expr.Type;
283                         
284                         if (target_type == TypeManager.object_type) {
285                                 if (expr_type.IsClass)
286                                         return new EmptyCast (expr, target_type);
287                                 if (expr_type.IsValueType)
288                                         return new BoxedCast (expr, target_type);
289                         } else if (expr_type.IsSubclassOf (target_type))
290                                 return new EmptyCast (expr, target_type);
291                         else 
292                                 // FIXME: missing implicit reference conversions:
293                                 // 
294                                 // from any class-type S to any interface-type T.
295                                 // from any interface type S to interface-type T.
296                                 // from an array-type S to an array-type of type T
297                                 // from an array-type to System.Array
298                                 // from any delegate type to System.Delegate
299                                 // from any array-type or delegate type into System.ICloneable.
300                                 // from the null type to any reference-type.
301                                      
302                                 return null;
303
304                         return null;
305                 }
306
307                 // <summary>
308                 //   Handles expressions like this: decimal d; d = 1;
309                 //   and changes them into: decimal d; d = new System.Decimal (1);
310                 // </summary>
311                 static Expression InternalTypeConstructor (TypeContainer tc, Expression expr, Type target)
312                 {
313                         ArrayList args = new ArrayList ();
314
315                         args.Add (new Argument (expr, Argument.AType.Expression));
316                         
317                         Expression ne = new New (target.FullName, args,
318                                                  new Location ("FIXME", 1, 1));
319
320                         return ne.Resolve (tc);
321                 }
322                                                     
323                 // <summary>
324                 //   Converts implicitly the resolved expression `expr' into the
325                 //   `target_type'.  It returns a new expression that can be used
326                 //   in a context that expects a `target_type'. 
327                 // </summary>
328                 static public Expression ConvertImplicit (TypeContainer tc, Expression expr, Type target_type)
329                 {
330                         Type expr_type = expr.Type;
331
332                         if (expr_type == target_type)
333                                 return expr;
334                         
335                         //
336                         // Step 1: Perform implicit conversions as found on expr.Type
337                         //
338                         Expression imp;
339
340                         imp = new UserImplicitCast (expr, target_type);
341
342                         imp = imp.Resolve (tc);
343
344                         if (imp != null)
345                                 return imp;
346
347                         //
348                         // Step 2: Built-in conversions.
349                         //
350                         if (expr_type == TypeManager.sbyte_type){
351                                 //
352                                 // From sbyte to short, int, long, float, double.
353                                 //
354                                 if (target_type == TypeManager.int32_type)
355                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_I4);
356                                 if (target_type == TypeManager.int64_type)
357                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_U8);
358                                 if (target_type == TypeManager.double_type)
359                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_R8);
360                                 if (target_type == TypeManager.float_type)
361                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_R4);
362                                 if (target_type == TypeManager.short_type)
363                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_I2);
364                                 if (target_type == TypeManager.decimal_type)
365                                         return InternalTypeConstructor (tc, expr, target_type);
366                         } else if (expr_type == TypeManager.byte_type){
367                                 //
368                                 // From byte to short, ushort, int, uint, long, ulong, float, double
369                                 // 
370                                 if ((target_type == TypeManager.short_type) ||
371                                     (target_type == TypeManager.ushort_type) ||
372                                     (target_type == TypeManager.int32_type) ||
373                                     (target_type == TypeManager.uint32_type))
374                                         return new EmptyCast (expr, target_type);
375
376                                 if (target_type == TypeManager.uint64_type)
377                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_U8);
378                                 if (target_type == TypeManager.int64_type)
379                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_I8);
380                                 
381                                 if (target_type == TypeManager.float_type)
382                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_R4);
383                                 if (target_type == TypeManager.double_type)
384                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_R8);
385                                 if (target_type == TypeManager.decimal_type)
386                                         return InternalTypeConstructor (tc, expr, target_type);
387                         } else if (expr_type == TypeManager.short_type){
388                                 //
389                                 // From short to int, long, float, double
390                                 // 
391                                 if (target_type == TypeManager.int32_type)
392                                         return new EmptyCast (expr, target_type);
393                                 if (target_type == TypeManager.int64_type)
394                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_I8);
395                                 if (target_type == TypeManager.double_type)
396                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_R8);
397                                 if (target_type == TypeManager.float_type)
398                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_R4);
399                                 if (target_type == TypeManager.decimal_type)
400                                         return InternalTypeConstructor (tc, expr, target_type);
401                         } else if (expr_type == TypeManager.ushort_type){
402                                 //
403                                 // From ushort to int, uint, long, ulong, float, double
404                                 //
405                                 if ((target_type == TypeManager.uint32_type) ||
406                                     (target_type == TypeManager.uint64_type))
407                                         return new EmptyCast (expr, target_type);
408                                         
409                                 if (target_type == TypeManager.int32_type)
410                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_I4);
411                                 if (target_type == TypeManager.int64_type)
412                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_I8);
413                                 if (target_type == TypeManager.double_type)
414                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_R8);
415                                 if (target_type == TypeManager.float_type)
416                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_R4);
417                                 if (target_type == TypeManager.decimal_type)
418                                         return InternalTypeConstructor (tc, expr, target_type);
419                         } else if (expr_type == TypeManager.int32_type){
420                                 //
421                                 // From int to long, float, double
422                                 //
423                                 if (target_type == TypeManager.int64_type)
424                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_I8);
425                                 if (target_type == TypeManager.double_type)
426                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_R8);
427                                 if (target_type == TypeManager.float_type)
428                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_R4);
429                                 if (target_type == TypeManager.decimal_type)
430                                         return InternalTypeConstructor (tc, expr, target_type);
431                         } else if (expr_type == TypeManager.uint32_type){
432                                 //
433                                 // From uint to long, ulong, float, double
434                                 //
435                                 if (target_type == TypeManager.int64_type)
436                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_I8);
437                                 if (target_type == TypeManager.uint64_type)
438                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_U8);
439                                 if (target_type == TypeManager.double_type)
440                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_R_Un,
441                                                                OpCodes.Conv_R8);
442                                 if (target_type == TypeManager.float_type)
443                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_R_Un,
444                                                                OpCodes.Conv_R4);
445                                 if (target_type == TypeManager.decimal_type)
446                                         return InternalTypeConstructor (tc, expr, target_type);
447                         } else if ((expr_type == TypeManager.uint64_type) ||
448                                    (expr_type == TypeManager.int64_type)){
449                                 //
450                                 // From long to float, double
451                                 //
452                                 if (target_type == TypeManager.double_type)
453                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_R_Un,
454                                                                OpCodes.Conv_R8);
455                                 if (target_type == TypeManager.float_type)
456                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_R_Un,
457                                                                OpCodes.Conv_R4);        
458                                 if (target_type == TypeManager.decimal_type)
459                                         return InternalTypeConstructor (tc, expr, target_type);
460                         } else if (expr_type == TypeManager.char_type){
461                                 //
462                                 // From char to ushort, int, uint, long, ulong, float, double
463                                 // 
464                                 if ((target_type == TypeManager.ushort_type) ||
465                                     (target_type == TypeManager.int32_type) ||
466                                     (target_type == TypeManager.uint32_type))
467                                         return new EmptyCast (expr, target_type);
468                                 if (target_type == TypeManager.uint64_type)
469                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_U8);
470                                 if (target_type == TypeManager.int64_type)
471                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_I8);
472                                 if (target_type == TypeManager.float_type)
473                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_R4);
474                                 if (target_type == TypeManager.double_type)
475                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_R8);
476                                 if (target_type == TypeManager.decimal_type)
477                                         return InternalTypeConstructor (tc, expr, target_type);
478                         } else
479                                 return ImplicitReferenceConversion (expr, target_type);
480
481                         
482
483                         //
484                         //  Could not find an implicit cast.
485                         //
486                         return null;
487                 }
488
489                 // <summary>
490                 //   Attemptes to implicityly convert `target' into `type', using
491                 //   ConvertImplicit.  If there is no implicit conversion, then
492                 //   an error is signaled
493                 // </summary>
494                 static public Expression ConvertImplicitRequired (TypeContainer tc, Expression target,
495                                                                   Type type, Location l)
496                 {
497                         Expression e;
498                         
499                         e = ConvertImplicit (tc, target, type);
500                         if (e == null){
501                                 string msg = "Can not convert implicitly from `"+
502                                         TypeManager.CSharpName (target.Type) + "' to `" +
503                                         TypeManager.CSharpName (type) + "'";
504
505                                 tc.RootContext.Report.Error (29, l, msg);
506                         }
507                         return e;
508                 }
509                 
510                 // <summary>
511                 //   Performs an explicit conversion of the expression `expr' whose
512                 //   type is expr.Type to `target_type'.
513                 // </summary>
514                 static public Expression ConvertExplicit (Expression expr, Type target_type)
515                 {
516                         return expr;
517                 }
518
519                 void report (TypeContainer tc, int error, string s)
520                 {
521                         tc.RootContext.Report.Error (error, s);
522                 }
523
524                 static string ExprClassName (ExprClass c)
525                 {
526                         switch (c){
527                         case ExprClass.Invalid:
528                                 return "Invalid";
529                         case ExprClass.Value:
530                                 return "value";
531                         case ExprClass.Variable:
532                                 return "variable";
533                         case ExprClass.Namespace:
534                                 return "namespace";
535                         case ExprClass.Type:
536                                 return "type";
537                         case ExprClass.MethodGroup:
538                                 return "method group";
539                         case ExprClass.PropertyAccess:
540                                 return "property access";
541                         case ExprClass.EventAccess:
542                                 return "event access";
543                         case ExprClass.IndexerAccess:
544                                 return "indexer access";
545                         case ExprClass.Nothing:
546                                 return "null";
547                         }
548                         throw new Exception ("Should not happen");
549                 }
550                 
551                 // <summary>
552                 //   Reports that we were expecting `expr' to be of class `expected'
553                 // </summary>
554                 protected void report118 (TypeContainer tc, Expression expr, string expected)
555                 {
556                         report (tc, 118, "Expression denotes a '" + ExprClassName (expr.ExprClass) +
557                                 "' where an " + expected + " was expected");
558                 }
559         }
560
561         // <summary>
562         //   This is just a base class for expressions that can
563         //   appear on statements (invocations, object creation,
564         //   assignments, post/pre increment and decrement).  The idea
565         //   being that they would support an extra Emition interface that
566         //   does not leave a result on the stack.
567         // </summary>
568
569         public abstract class ExpressionStatement : Expression {
570
571                 // <summary>
572                 //   Requests the expression to be emitted in a `statement'
573                 //   context.  This means that no new value is left on the
574                 //   stack after invoking this method (constrasted with
575                 //   Emit that will always leave a value on the stack).
576                 // </summary>
577                 public abstract void EmitStatement (EmitContext ec);
578         }
579
580         // <summary>
581         //   This kind of cast is used to encapsulate the child
582         //   whose type is child.Type into an expression that is
583         //   reported to return "return_type".  This is used to encapsulate
584         //   expressions which have compatible types, but need to be dealt
585         //   at higher levels with.
586         //
587         //   For example, a "byte" expression could be encapsulated in one
588         //   of these as an "unsigned int".  The type for the expression
589         //   would be "unsigned int".
590         //
591         // </summary>
592         
593         public class EmptyCast : Expression {
594                 protected Expression child;
595
596                 public EmptyCast (Expression child, Type return_type)
597                 {
598                         ExprClass = child.ExprClass;
599                         type = return_type;
600                         this.child = child;
601                 }
602
603                 public override Expression Resolve (TypeContainer tc)
604                 {
605                         // This should never be invoked, we are born in fully
606                         // initialized state.
607
608                         return this;
609                 }
610
611                 public override void Emit (EmitContext ec)
612                 {
613                         child.Emit (ec);
614                 }                       
615         }
616
617         // <summary>
618         //   This kind of cast is used to encapsulate Value Types in objects.
619         //
620         //   The effect of it is to box the value type emitted by the previous
621         //   operation.
622         // </summary>
623         public class BoxedCast : EmptyCast {
624
625                 public BoxedCast (Expression expr, Type target_type)
626                         : base (expr, target_type)
627                 {
628                 }
629
630                 public override Expression Resolve (TypeContainer tc)
631                 {
632                         // This should never be invoked, we are born in fully
633                         // initialized state.
634
635                         return this;
636                 }
637
638                 public override void Emit (EmitContext ec)
639                 {
640                         base.Emit (ec);
641                         ec.ig.Emit (OpCodes.Box, child.Type);
642                 }
643         }
644
645         // <summary>
646         //   This kind of cast is used to encapsulate a child expression
647         //   that can be trivially converted to a target type using one or 
648         //   two opcodes.  The opcodes are passed as arguments.
649         // </summary>
650         public class OpcodeCast : EmptyCast {
651                 OpCode op, op2;
652                 bool second_valid;
653                 
654                 public OpcodeCast (Expression child, Type return_type, OpCode op)
655                         : base (child, return_type)
656                         
657                 {
658                         this.op = op;
659                         second_valid = false;
660                 }
661
662                 public OpcodeCast (Expression child, Type return_type, OpCode op, OpCode op2)
663                         : base (child, return_type)
664                         
665                 {
666                         this.op = op;
667                         this.op2 = op2;
668                         second_valid = true;
669                 }
670
671                 public override Expression Resolve (TypeContainer tc)
672                 {
673                         // This should never be invoked, we are born in fully
674                         // initialized state.
675
676                         return this;
677                 }
678
679                 public override void Emit (EmitContext ec)
680                 {
681                         base.Emit (ec);
682                         ec.ig.Emit (op);
683
684                         if (second_valid)
685                                 ec.ig.Emit (op2);
686                 }                       
687                 
688         }
689         
690         public class Unary : ExpressionStatement {
691                 public enum Operator {
692                         Add, Subtract, Negate, BitComplement,
693                         Indirection, AddressOf, PreIncrement,
694                         PreDecrement, PostIncrement, PostDecrement
695                 }
696
697                 Operator   oper;
698                 Expression expr;
699                 ArrayList  Arguments;
700                 MethodBase method;
701                 Location   location;
702                 
703                 public Unary (Operator op, Expression expr, Location loc)
704                 {
705                         this.oper = op;
706                         this.expr = expr;
707                         this.location = loc;
708                 }
709
710                 public Expression Expr {
711                         get {
712                                 return expr;
713                         }
714
715                         set {
716                                 expr = value;
717                         }
718                 }
719
720                 public Operator Oper {
721                         get {
722                                 return oper;
723                         }
724
725                         set {
726                                 oper = value;
727                         }
728                 }
729
730                 // <summary>
731                 //   Returns a stringified representation of the Operator
732                 // </summary>
733                 string OperName ()
734                 {
735                         switch (oper){
736                         case Operator.Add:
737                                 return "+";
738                         case Operator.Subtract:
739                                 return "-";
740                         case Operator.Negate:
741                                 return "!";
742                         case Operator.BitComplement:
743                                 return "~";
744                         case Operator.AddressOf:
745                                 return "&";
746                         case Operator.Indirection:
747                                 return "*";
748                         case Operator.PreIncrement : case Operator.PostIncrement :
749                                 return "++";
750                         case Operator.PreDecrement : case Operator.PostDecrement :
751                                 return "--";
752                         }
753
754                         return oper.ToString ();
755                 }
756
757                 Expression ForceConversion (TypeContainer tc, Expression expr, Type target_type)
758                 {
759                         if (expr.Type == target_type)
760                                 return expr;
761
762                         return ConvertImplicit (tc, expr, target_type);
763                 }
764
765                 void report23 (Report r, Type t)
766                 {
767                         r.Error (23, "Operator " + OperName () + " cannot be applied to operand of type `" +
768                                  TypeManager.CSharpName (t) + "'");
769                 }
770
771                 // <summary>
772                 //   Returns whether an object of type `t' can be incremented
773                 //   or decremented with add/sub (ie, basically whether we can
774                 //   use pre-post incr-decr operations on it, but it is not a
775                 //   System.Decimal, which we test elsewhere)
776                 // </summary>
777                 static bool IsIncrementableNumber (Type t)
778                 {
779                         return (t == TypeManager.sbyte_type) ||
780                                 (t == TypeManager.byte_type) ||
781                                 (t == TypeManager.short_type) ||
782                                 (t == TypeManager.ushort_type) ||
783                                 (t == TypeManager.int32_type) ||
784                                 (t == TypeManager.uint32_type) ||
785                                 (t == TypeManager.int64_type) ||
786                                 (t == TypeManager.uint64_type) ||
787                                 (t == TypeManager.char_type) ||
788                                 (t.IsSubclassOf (TypeManager.enum_type)) ||
789                                 (t == TypeManager.float_type) ||
790                                 (t == TypeManager.double_type);
791                 }
792                         
793                 Expression ResolveOperator (TypeContainer tc)
794                 {
795                         Type expr_type = expr.Type;
796
797                         //
798                         // Step 1: Perform Operator Overload location
799                         //
800                         Expression mg;
801                         string op_name;
802                                 
803                         if (oper == Operator.PostIncrement || oper == Operator.PreIncrement)
804                                 op_name = "op_Increment";
805                         else if (oper == Operator.PostDecrement || oper == Operator.PreDecrement)
806                                 op_name = "op_Decrement";
807                         else
808                                 op_name = "op_" + oper;
809
810                         mg = MemberLookup (tc.RootContext, expr_type, op_name, false);
811                         
812                         if (mg != null) {
813                                 Arguments = new ArrayList ();
814                                 Arguments.Add (new Argument (expr, Argument.AType.Expression));
815                                 
816                                 method = Invocation.OverloadResolve (tc, (MethodGroupExpr) mg, Arguments, location);
817                                 if (method != null) {
818                                         MethodInfo mi = (MethodInfo) method;
819
820                                         type = mi.ReturnType;
821                                         return this;
822                                 }
823                         }
824
825                         //
826                         // Step 2: Default operations on CLI native types.
827                         //
828
829                         // Only perform numeric promotions on:
830                         // +, -, ++, --
831
832                         if (expr_type == null)
833                                 return null;
834                         
835                         if (oper == Operator.Negate){
836                                 if (expr_type != TypeManager.bool_type) {
837                                         report23 (tc.RootContext.Report, expr.Type);
838                                         return null;
839                                 }
840                                 
841                                 type = TypeManager.bool_type;
842                                 return this;
843                         }
844
845                         if (oper == Operator.BitComplement) {
846                                 if (!((expr_type == TypeManager.int32_type) ||
847                                       (expr_type == TypeManager.uint32_type) ||
848                                       (expr_type == TypeManager.int64_type) ||
849                                       (expr_type == TypeManager.uint64_type) ||
850                                       (expr_type.IsSubclassOf (TypeManager.enum_type)))){
851                                         report23 (tc.RootContext.Report, expr.Type);
852                                         return null;
853                                 }
854                                 type = expr_type;
855                                 return this;
856                         }
857
858                         if (oper == Operator.Add) {
859                                 //
860                                 // A plus in front of something is just a no-op, so return the child.
861                                 //
862                                 return expr;
863                         }
864
865                         //
866                         // Deals with -literals
867                         // int     operator- (int x)
868                         // long    operator- (long x)
869                         // float   operator- (float f)
870                         // double  operator- (double d)
871                         // decimal operator- (decimal d)
872                         //
873                         if (oper == Operator.Subtract){
874                                 //
875                                 // Fold a "- Constant" into a negative constant
876                                 //
877                         
878                                 Expression e = null;
879
880                                 //
881                                 // Is this a constant? 
882                                 //
883                                 if (expr is IntLiteral)
884                                         e = new IntLiteral (-((IntLiteral) expr).Value);
885                                 else if (expr is LongLiteral)
886                                         e = new LongLiteral (-((LongLiteral) expr).Value);
887                                 else if (expr is FloatLiteral)
888                                         e = new FloatLiteral (-((FloatLiteral) expr).Value);
889                                 else if (expr is DoubleLiteral)
890                                         e = new DoubleLiteral (-((DoubleLiteral) expr).Value);
891                                 else if (expr is DecimalLiteral)
892                                         e = new DecimalLiteral (-((DecimalLiteral) expr).Value);
893                                 
894                                 if (e != null){
895                                         e = e.Resolve (tc);
896                                         return e;
897                                 }
898
899                                 //
900                                 // Not a constant we can optimize, perform numeric 
901                                 // promotions to int, long, double.
902                                 //
903                                 //
904                                 // The following is inneficient, because we call
905                                 // ConvertImplicit too many times.
906                                 //
907                                 // It is also not clear if we should convert to Float
908                                 // or Double initially.
909                                 //
910                                 if (expr_type == TypeManager.uint32_type){
911                                         //
912                                         // FIXME: handle exception to this rule that
913                                         // permits the int value -2147483648 (-2^31) to
914                                         // bt written as a decimal interger literal
915                                         //
916                                         type = TypeManager.int64_type;
917                                         expr = ConvertImplicit (tc, expr, type);
918                                         return this;
919                                 }
920
921                                 if (expr_type == TypeManager.uint64_type){
922                                         //
923                                         // FIXME: Handle exception of `long value'
924                                         // -92233720368547758087 (-2^63) to be written as
925                                         // decimal integer literal.
926                                         //
927                                         report23 (tc.RootContext.Report, expr_type);
928                                         return null;
929                                 }
930
931                                 e = ConvertImplicit (tc, expr, TypeManager.int32_type);
932                                 if (e != null){
933                                         expr = e;
934                                         type = e.Type;
935                                         return this;
936                                 } 
937
938                                 e = ConvertImplicit (tc, expr, TypeManager.int64_type);
939                                 if (e != null){
940                                         expr = e;
941                                         type = e.Type;
942                                         return this;
943                                 }
944
945                                 e = ConvertImplicit (tc, expr, TypeManager.double_type);
946                                 if (e != null){
947                                         expr = e;
948                                         type = e.Type;
949                                         return this;
950                                 }
951
952                                 report23 (tc.RootContext.Report, expr_type);
953                                 return null;
954                         }
955
956                         //
957                         // The operand of the prefix/postfix increment decrement operators
958                         // should be an expression that is classified as a variable,
959                         // a property access or an indexer access
960                         //
961                         if (oper == Operator.PreDecrement || oper == Operator.PreIncrement ||
962                             oper == Operator.PostDecrement || oper == Operator.PostIncrement){
963                                 if (expr.ExprClass == ExprClass.Variable){
964                                         if (IsIncrementableNumber (expr_type) ||
965                                             expr_type == TypeManager.decimal_type){
966                                                 type = expr_type;
967                                                 return this;
968                                         }
969                                 } else if (expr.ExprClass == ExprClass.IndexerAccess){
970                                         //
971                                         // FIXME: Verify that we have both get and set methods
972                                         //
973                                         throw new Exception ("Implement me");
974                                 } else if (expr.ExprClass == ExprClass.PropertyAccess){
975                                         //
976                                         // FIXME: Verify that we have both get and set methods
977                                         //
978                                         throw new Exception ("Implement me");
979                                 } else {
980                                         report118 (tc, expr, "variable, indexer or property access");
981                                 }
982                         }
983
984                         tc.RootContext.Report.Error (187, "No such operator '" + OperName () +
985                                                      "' defined for type '" +
986                                                      TypeManager.CSharpName (expr_type) + "'");
987                         return null;
988
989                 }
990
991                 public override Expression Resolve (TypeContainer tc)
992                 {
993                         expr = expr.Resolve (tc);
994
995                         if (expr == null)
996                                 return null;
997                         
998                         return ResolveOperator (tc);
999                 }
1000
1001                 public override void Emit (EmitContext ec)
1002                 {
1003                         ILGenerator ig = ec.ig;
1004                         Type expr_type = expr.Type;
1005
1006                         if (method != null) {
1007
1008                                 // Note that operators are static anyway
1009                                 
1010                                 if (Arguments != null) 
1011                                         Invocation.EmitArguments (ec, method, Arguments);
1012
1013                                 //
1014                                 // Post increment/decrement operations need a copy at this
1015                                 // point.
1016                                 //
1017                                 if (oper == Operator.PostDecrement || oper == Operator.PostIncrement)
1018                                         ig.Emit (OpCodes.Dup);
1019                                 
1020
1021                                 ig.Emit (OpCodes.Call, (MethodInfo) method);
1022
1023                                 //
1024                                 // Pre Increment and Decrement operators
1025                                 //
1026                                 if (oper == Operator.PreIncrement || oper == Operator.PreDecrement){
1027                                         ig.Emit (OpCodes.Dup);
1028                                 }
1029                                 
1030                                 //
1031                                 // Increment and Decrement should store the result
1032                                 //
1033                                 if (oper == Operator.PreDecrement || oper == Operator.PreIncrement ||
1034                                     oper == Operator.PostDecrement || oper == Operator.PostIncrement){
1035                                         ((LValue) expr).Store (ig);
1036                                 }
1037                                 return;
1038                         }
1039                         
1040                         switch (oper) {
1041                         case Operator.Add:
1042                                 throw new Exception ("This should be caught by Resolve");
1043                                 
1044                         case Operator.Subtract:
1045                                 expr.Emit (ec);
1046                                 ig.Emit (OpCodes.Neg);
1047                                 break;
1048                                 
1049                         case Operator.Negate:
1050                                 expr.Emit (ec);
1051                                 ig.Emit (OpCodes.Ldc_I4_0);
1052                                 ig.Emit (OpCodes.Ceq);
1053                                 break;
1054                                 
1055                         case Operator.BitComplement:
1056                                 expr.Emit (ec);
1057                                 ig.Emit (OpCodes.Not);
1058                                 break;
1059                                 
1060                         case Operator.AddressOf:
1061                                 throw new Exception ("Not implemented yet");
1062                                 
1063                         case Operator.Indirection:
1064                                 throw new Exception ("Not implemented yet");
1065                                 
1066                         case Operator.PreIncrement:
1067                         case Operator.PreDecrement:
1068                                 if (expr.ExprClass == ExprClass.Variable){
1069                                         //
1070                                         // Resolve already verified that it is an "incrementable"
1071                                         // 
1072                                         expr.Emit (ec);
1073                                         ig.Emit (OpCodes.Ldc_I4_1);
1074                                         
1075                                         if (oper == Operator.PreDecrement)
1076                                                 ig.Emit (OpCodes.Sub);
1077                                         else
1078                                                 ig.Emit (OpCodes.Add);
1079                                         ig.Emit (OpCodes.Dup);
1080                                         ((LValue) expr).Store (ig);
1081                                 } else {
1082                                         throw new Exception ("Handle Indexers and Properties here");
1083                                 }
1084                                 break;
1085                                 
1086                         case Operator.PostIncrement:
1087                         case Operator.PostDecrement:
1088                                 if (expr.ExprClass == ExprClass.Variable){
1089                                         //
1090                                         // Resolve already verified that it is an "incrementable"
1091                                         // 
1092                                         expr.Emit (ec);
1093                                         ig.Emit (OpCodes.Dup);
1094                                         ig.Emit (OpCodes.Ldc_I4_1);
1095                                         
1096                                         if (oper == Operator.PostDecrement)
1097                                                 ig.Emit (OpCodes.Sub);
1098                                         else
1099                                                 ig.Emit (OpCodes.Add);
1100                                         ((LValue) expr).Store (ig);
1101                                 } else {
1102                                         throw new Exception ("Handle Indexers and Properties here");
1103                                 }
1104                                 break;
1105                                 
1106                         default:
1107                                 throw new Exception ("This should not happen: Operator = "
1108                                                      + oper.ToString ());
1109                         }
1110                 }
1111                 
1112
1113                 public override void EmitStatement (EmitContext ec)
1114                 {
1115                         //
1116                         // FIXME: we should rewrite this code to generate
1117                         // better code for ++ and -- as we know we wont need
1118                         // the values on the stack
1119                         //
1120                         Emit (ec);
1121                         ec.ig.Emit (OpCodes.Pop);
1122                 }
1123         }
1124         
1125         public class Probe : Expression {
1126                 string probe_type;
1127                 Expression expr;
1128                 Operator oper;
1129
1130                 public enum Operator {
1131                         Is, As
1132                 }
1133                 
1134                 public Probe (Operator oper, Expression expr, string probe_type)
1135                 {
1136                         this.oper = oper;
1137                         this.probe_type = probe_type;
1138                         this.expr = expr;
1139                 }
1140
1141                 public Operator Oper {
1142                         get {
1143                                 return oper;
1144                         }
1145                 }
1146
1147                 public Expression Expr {
1148                         get {
1149                                 return expr;
1150                         }
1151                 }
1152
1153                 public string ProbeType {
1154                         get {
1155                                 return probe_type;
1156                         }
1157                 }
1158
1159                 public override Expression Resolve (TypeContainer tc)
1160                 {
1161                         // FIXME: Implement;
1162                         throw new Exception ("Unimplemented");
1163                         // return this;
1164                 }
1165
1166                 public override void Emit (EmitContext ec)
1167                 {
1168                 }
1169         }
1170         
1171         public class Cast : Expression {
1172                 string target_type;
1173                 Expression expr;
1174                 
1175                 public Cast (string cast_type, Expression expr)
1176                 {
1177                         this.target_type = cast_type;
1178                         this.expr = expr;
1179                 }
1180
1181                 public string TargetType {
1182                         get {
1183                                 return target_type;
1184                         }
1185                 }
1186
1187                 public Expression Expr {
1188                         get {
1189                                 return expr;
1190                         }
1191                         set {
1192                                 expr = value;
1193                         }
1194                 }
1195                 
1196                 public override Expression Resolve (TypeContainer tc)
1197                 {
1198                         type = tc.LookupType (target_type, false);
1199                         eclass = ExprClass.Value;
1200                         
1201                         if (type == null)
1202                                 return null;
1203
1204                         //
1205                         // FIXME: Unimplemented
1206                         //
1207                         throw new Exception ("FINISH ME");
1208                 }
1209
1210                 public override void Emit (EmitContext ec)
1211                 {
1212                 }
1213         }
1214
1215         public class Binary : Expression {
1216                 public enum Operator {
1217                         Multiply, Division, Modulus,
1218                         Addition, Subtraction,
1219                         LeftShift, RightShift,
1220                         LessThan, GreaterThan, LessThanOrEqual, GreaterThanOrEqual, 
1221                         Equality, Inequality,
1222                         BitwiseAnd,
1223                         ExclusiveOr,
1224                         BitwiseOr,
1225                         LogicalAnd,
1226                         LogicalOr
1227                 }
1228
1229                 Operator oper;
1230                 Expression left, right;
1231                 MethodBase method;
1232                 ArrayList  Arguments;
1233                 Location   location;
1234                 
1235
1236                 public Binary (Operator oper, Expression left, Expression right, Location loc)
1237                 {
1238                         this.oper = oper;
1239                         this.left = left;
1240                         this.right = right;
1241                         this.location = loc;
1242                 }
1243
1244                 public Operator Oper {
1245                         get {
1246                                 return oper;
1247                         }
1248                         set {
1249                                 oper = value;
1250                         }
1251                 }
1252                 
1253                 public Expression Left {
1254                         get {
1255                                 return left;
1256                         }
1257                         set {
1258                                 left = value;
1259                         }
1260                 }
1261
1262                 public Expression Right {
1263                         get {
1264                                 return right;
1265                         }
1266                         set {
1267                                 right = value;
1268                         }
1269                 }
1270
1271
1272                 // <summary>
1273                 //   Returns a stringified representation of the Operator
1274                 // </summary>
1275                 string OperName ()
1276                 {
1277                         switch (oper){
1278                         case Operator.Multiply:
1279                                 return "*";
1280                         case Operator.Division:
1281                                 return "/";
1282                         case Operator.Modulus:
1283                                 return "%";
1284                         case Operator.Addition:
1285                                 return "+";
1286                         case Operator.Subtraction:
1287                                 return "-";
1288                         case Operator.LeftShift:
1289                                 return "<<";
1290                         case Operator.RightShift:
1291                                 return ">>";
1292                         case Operator.LessThan:
1293                                 return "<";
1294                         case Operator.GreaterThan:
1295                                 return ">";
1296                         case Operator.LessThanOrEqual:
1297                                 return "<=";
1298                         case Operator.GreaterThanOrEqual:
1299                                 return ">=";
1300                         case Operator.Equality:
1301                                 return "==";
1302                         case Operator.Inequality:
1303                                 return "!=";
1304                         case Operator.BitwiseAnd:
1305                                 return "&";
1306                         case Operator.BitwiseOr:
1307                                 return "|";
1308                         case Operator.ExclusiveOr:
1309                                 return "^";
1310                         case Operator.LogicalOr:
1311                                 return "||";
1312                         case Operator.LogicalAnd:
1313                                 return "&&";
1314                         }
1315
1316                         return oper.ToString ();
1317                 }
1318
1319                 Expression ForceConversion (TypeContainer tc, Expression expr, Type target_type)
1320                 {
1321                         if (expr.Type == target_type)
1322                                 return expr;
1323
1324                         return ConvertImplicit (tc, expr, target_type);
1325                 }
1326                 
1327                 //
1328                 // Note that handling the case l == Decimal || r == Decimal
1329                 // is taken care of by the Step 1 Operator Overload resolution.
1330                 //
1331                 void DoNumericPromotions (TypeContainer tc, Type l, Type r)
1332                 {
1333                         if (l == TypeManager.double_type || r == TypeManager.double_type){
1334                                 //
1335                                 // If either operand is of type double, the other operand is
1336                                 // conveted to type double.
1337                                 //
1338                                 if (r != TypeManager.double_type)
1339                                         right = ConvertImplicit (tc, right, TypeManager.double_type);
1340                                 if (l != TypeManager.double_type)
1341                                         left = ConvertImplicit (tc, left, TypeManager.double_type);
1342                                 
1343                                 type = TypeManager.double_type;
1344                         } else if (l == TypeManager.float_type || r == TypeManager.float_type){
1345                                 //
1346                                 // if either operand is of type float, th eother operand is
1347                                 // converd to type float.
1348                                 //
1349                                 if (r != TypeManager.double_type)
1350                                         right = ConvertImplicit (tc, right, TypeManager.float_type);
1351                                 if (l != TypeManager.double_type)
1352                                         left = ConvertImplicit (tc, left, TypeManager.float_type);
1353                                 type = TypeManager.float_type;
1354                         } else if (l == TypeManager.uint64_type || r == TypeManager.uint64_type){
1355                                 //
1356                                 // If either operand is of type ulong, the other operand is
1357                                 // converted to type ulong.  or an error ocurrs if the other
1358                                 // operand is of type sbyte, short, int or long
1359                                 //
1360                                 Type other = null;
1361                                 
1362                                 if (l == TypeManager.uint64_type)
1363                                         other = r;
1364                                 else if (r == TypeManager.uint64_type)
1365                                         other = l;
1366
1367                                 if ((other == TypeManager.sbyte_type) ||
1368                                     (other == TypeManager.short_type) ||
1369                                     (other == TypeManager.int32_type) ||
1370                                     (other == TypeManager.int64_type)){
1371                                         string oper = OperName ();
1372                                         
1373                                         tc.RootContext.Report.Error (34, "Operator `" + OperName ()
1374                                                                      + "' is ambiguous on operands of type `"
1375                                                                      + TypeManager.CSharpName (l) + "' "
1376                                                                      + "and `" + TypeManager.CSharpName (r)
1377                                                                      + "'");
1378                                 }
1379                                 type = TypeManager.uint64_type;
1380                         } else if (l == TypeManager.int64_type || r == TypeManager.int64_type){
1381                                 //
1382                                 // If either operand is of type long, the other operand is converted
1383                                 // to type long.
1384                                 //
1385                                 if (l != TypeManager.int64_type)
1386                                         left = ConvertImplicit (tc, left, TypeManager.int64_type);
1387                                 if (r != TypeManager.int64_type)
1388                                         right = ConvertImplicit (tc, right, TypeManager.int64_type);
1389
1390                                 type = TypeManager.int64_type;
1391                         } else if (l == TypeManager.uint32_type || r == TypeManager.uint32_type){
1392                                 //
1393                                 // If either operand is of type uint, and the other
1394                                 // operand is of type sbyte, short or int, othe operands are
1395                                 // converted to type long.
1396                                 //
1397                                 Type other = null;
1398                                 
1399                                 if (l == TypeManager.uint32_type)
1400                                         other = r;
1401                                 else if (r == TypeManager.uint32_type)
1402                                         other = l;
1403
1404                                 if ((other == TypeManager.sbyte_type) ||
1405                                     (other == TypeManager.short_type) ||
1406                                     (other == TypeManager.int32_type)){
1407                                         left = ForceConversion (tc, left, TypeManager.int64_type);
1408                                         right = ForceConversion (tc, right, TypeManager.int64_type);
1409                                         type = TypeManager.int64_type;
1410                                 } else {
1411                                         //
1412                                         // if either operand is of type uint, the other
1413                                         // operand is converd to type uint
1414                                         //
1415                                         left = ForceConversion (tc, left, TypeManager.uint32_type);
1416                                         right = ForceConversion (tc, left, TypeManager.uint32_type);
1417                                         type = TypeManager.uint32_type;
1418                                 } 
1419                         } else if (l == TypeManager.decimal_type || r == TypeManager.decimal_type){
1420                                 if (l != TypeManager.decimal_type)
1421                                         left = ConvertImplicit (tc, left, TypeManager.decimal_type);
1422                                 if (r != TypeManager.decimal_type)
1423                                         right = ConvertImplicit (tc, right, TypeManager.decimal_type);
1424
1425                                 type = TypeManager.decimal_type;
1426                         } else {
1427                                 left = ForceConversion (tc, left, TypeManager.int32_type);
1428                                 right = ForceConversion (tc, right, TypeManager.int32_type);
1429                                 type = TypeManager.int32_type;
1430                         }
1431                 }
1432
1433                 void error19 (TypeContainer tc)
1434                 {
1435                         tc.RootContext.Report.Error (
1436                                 19,
1437                                 "Operator " + OperName () + " cannot be applied to operands of type `" +
1438                                 TypeManager.CSharpName (left.Type) + "' and `" +
1439                                 TypeManager.CSharpName (right.Type) + "'");
1440                                                      
1441                 }
1442                 
1443                 Expression CheckShiftArguments (TypeContainer tc)
1444                 {
1445                         Expression e;
1446                         Type l = left.Type;
1447                         Type r = right.Type;
1448
1449                         e = ForceConversion (tc, right, TypeManager.int32_type);
1450                         if (e == null){
1451                                 error19 (tc);
1452                                 return null;
1453                         }
1454                         right = e;
1455
1456                         if (((e = ConvertImplicit (tc, left, TypeManager.int32_type)) != null) ||
1457                             ((e = ConvertImplicit (tc, left, TypeManager.uint32_type)) != null) ||
1458                             ((e = ConvertImplicit (tc, left, TypeManager.int64_type)) != null) ||
1459                             ((e = ConvertImplicit (tc, left, TypeManager.uint64_type)) != null)){
1460                                 left = e;
1461
1462                                 return this;
1463                         }
1464                         error19 (tc);
1465                         return null;
1466                 }
1467                 
1468                 Expression ResolveOperator (TypeContainer tc)
1469                 {
1470                         Type l = left.Type;
1471                         Type r = right.Type;
1472
1473                         //
1474                         // Step 1: Perform Operator Overload location
1475                         //
1476                         Expression left_expr, right_expr;
1477                         
1478                         string op = "op_" + oper;
1479
1480                         left_expr = MemberLookup (tc.RootContext, l, op, false);
1481
1482                         right_expr = MemberLookup (tc.RootContext, r, op, false);
1483
1484                         Console.WriteLine ("Looking up: " + op);
1485                         
1486                         if (left_expr != null || right_expr != null) {
1487                                 //
1488                                 // Now we need to form the union of these two sets and
1489                                 // then call OverloadResolve on that.
1490                                 //
1491                                 MethodGroupExpr left_set = null, right_set = null;
1492                                 int length1 = 0, length2 = 0;
1493
1494                                 if (left_expr != null) {
1495                                         left_set = (MethodGroupExpr) left_expr;
1496                                         length1 = left_set.Methods.Length;
1497                                 }
1498
1499                                 if (right_expr != null) {
1500                                         right_set = (MethodGroupExpr) right_expr;
1501                                         length2 = right_set.Methods.Length;
1502                                 }
1503
1504                                 MemberInfo [] miset = new MemberInfo [length1 + length2];
1505                                 if (left_set != null)
1506                                         left_set.Methods.CopyTo (miset, 0);
1507                                 if (right_set != null)
1508                                         right_set.Methods.CopyTo (miset, length1);
1509                                 
1510                                 MethodGroupExpr union = new MethodGroupExpr (miset);
1511                                 
1512                                 Arguments = new ArrayList ();
1513                                 Arguments.Add (new Argument (left, Argument.AType.Expression));
1514                                 Arguments.Add (new Argument (right, Argument.AType.Expression));
1515
1516                         
1517                                 method = Invocation.OverloadResolve (tc, union, Arguments, location);
1518                                 if (method != null) {
1519                                         MethodInfo mi = (MethodInfo) method;
1520                                         
1521                                         type = mi.ReturnType;
1522                                         return this;
1523                                 }
1524                         }
1525
1526                         //
1527                         // Step 2: Default operations on CLI native types.
1528                         //
1529                         
1530                         // Only perform numeric promotions on:
1531                         // +, -, *, /, %, &, |, ^, ==, !=, <, >, <=, >=
1532                         //
1533                         if (oper == Operator.LeftShift || oper == Operator.RightShift){
1534                                 return CheckShiftArguments (tc);
1535                         } else if (oper == Operator.LogicalOr || oper == Operator.LogicalAnd){
1536
1537                                 if (l != TypeManager.bool_type || r != TypeManager.bool_type)
1538                                         error19 (tc);
1539                         } else
1540                                 DoNumericPromotions (tc, l, r);
1541
1542                         if (left == null || right == null)
1543                                 return null;
1544
1545                         if (oper == Operator.BitwiseAnd ||
1546                             oper == Operator.BitwiseOr ||
1547                             oper == Operator.ExclusiveOr){
1548                                 if (!((l == TypeManager.int32_type) ||
1549                                       (l == TypeManager.uint32_type) ||
1550                                       (l == TypeManager.int64_type) ||
1551                                       (l == TypeManager.uint64_type))){
1552                                         error19 (tc);
1553                                         return null;
1554                                 }
1555                         }
1556
1557                         if (oper == Operator.Equality ||
1558                             oper == Operator.Inequality ||
1559                             oper == Operator.LessThanOrEqual ||
1560                             oper == Operator.LessThan ||
1561                             oper == Operator.GreaterThanOrEqual ||
1562                             oper == Operator.GreaterThan){
1563                                 type = TypeManager.bool_type;
1564                         }
1565                         
1566                         return this;
1567                 }
1568                 
1569                 public override Expression Resolve (TypeContainer tc)
1570                 {
1571                         left = left.Resolve (tc);
1572                         right = right.Resolve (tc);
1573
1574                         if (left == null || right == null)
1575                                 return null;
1576
1577                         return ResolveOperator (tc);
1578                 }
1579
1580                 public bool IsBranchable ()
1581                 {
1582                         if (oper == Operator.Equality ||
1583                             oper == Operator.Inequality ||
1584                             oper == Operator.LessThan ||
1585                             oper == Operator.GreaterThan ||
1586                             oper == Operator.LessThanOrEqual ||
1587                             oper == Operator.GreaterThanOrEqual){
1588                                 return true;
1589                         } else
1590                                 return false;
1591                 }
1592
1593                 // <summary>
1594                 //   This entry point is used by routines that might want
1595                 //   to emit a brfalse/brtrue after an expression, and instead
1596                 //   they could use a more compact notation.
1597                 //
1598                 //   Typically the code would generate l.emit/r.emit, followed
1599                 //   by the comparission and then a brtrue/brfalse.  The comparissions
1600                 //   are sometimes inneficient (there are not as complete as the branches
1601                 //   look for the hacks in Emit using double ceqs).
1602                 //
1603                 //   So for those cases we provide EmitBranchable that can emit the
1604                 //   branch with the test
1605                 // </summary>
1606                 public void EmitBranchable (EmitContext ec, int target)
1607                 {
1608                         OpCode opcode;
1609                         bool close_target = false;
1610                         
1611                         left.Emit (ec);
1612                         right.Emit (ec);
1613                         
1614                         switch (oper){
1615                         case Operator.Equality:
1616                                 if (close_target)
1617                                         opcode = OpCodes.Beq_S;
1618                                 else
1619                                         opcode = OpCodes.Beq;
1620                                 break;
1621
1622                         case Operator.Inequality:
1623                                 if (close_target)
1624                                         opcode = OpCodes.Bne_Un_S;
1625                                 else
1626                                         opcode = OpCodes.Bne_Un;
1627                                 break;
1628
1629                         case Operator.LessThan:
1630                                 if (close_target)
1631                                         opcode = OpCodes.Blt_S;
1632                                 else
1633                                         opcode = OpCodes.Blt;
1634                                 break;
1635
1636                         case Operator.GreaterThan:
1637                                 if (close_target)
1638                                         opcode = OpCodes.Bgt_S;
1639                                 else
1640                                         opcode = OpCodes.Bgt;
1641                                 break;
1642
1643                         case Operator.LessThanOrEqual:
1644                                 if (close_target)
1645                                         opcode = OpCodes.Ble_S;
1646                                 else
1647                                         opcode = OpCodes.Ble;
1648                                 break;
1649
1650                         case Operator.GreaterThanOrEqual:
1651                                 if (close_target)
1652                                         opcode = OpCodes.Bge_S;
1653                                 else
1654                                         opcode = OpCodes.Ble;
1655                                 break;
1656
1657                         default:
1658                                 throw new Exception ("EmitBranchable called on non-EmitBranchable operator: "
1659                                                      + oper.ToString ());
1660                         }
1661
1662                         ec.ig.Emit (opcode, target);
1663                 }
1664                 
1665                 public override void Emit (EmitContext ec)
1666                 {
1667                         ILGenerator ig = ec.ig;
1668                         Type l = left.Type;
1669                         Type r = right.Type;
1670                         OpCode opcode;
1671
1672                         if (method != null) {
1673
1674                                 // Note that operators are static anyway
1675                                 
1676                                 if (Arguments != null) 
1677                                         Invocation.EmitArguments (ec, method, Arguments);
1678                                 
1679                                 if (method is MethodInfo)
1680                                         ig.Emit (OpCodes.Call, (MethodInfo) method);
1681                                 else
1682                                         ig.Emit (OpCodes.Call, (ConstructorInfo) method);
1683
1684                                 return;
1685                         }
1686                         
1687                         left.Emit (ec);
1688                         right.Emit (ec);
1689
1690                         switch (oper){
1691                         case Operator.Multiply:
1692                                 if (ec.CheckState){
1693                                         if (l == TypeManager.int32_type || l == TypeManager.int64_type)
1694                                                 opcode = OpCodes.Mul_Ovf;
1695                                         else if (l==TypeManager.uint32_type || l==TypeManager.uint64_type)
1696                                                 opcode = OpCodes.Mul_Ovf_Un;
1697                                         else
1698                                                 opcode = OpCodes.Mul;
1699                                 } else
1700                                         opcode = OpCodes.Mul;
1701
1702                                 break;
1703
1704                         case Operator.Division:
1705                                 if (l == TypeManager.uint32_type || l == TypeManager.uint64_type)
1706                                         opcode = OpCodes.Div_Un;
1707                                 else
1708                                         opcode = OpCodes.Div;
1709                                 break;
1710
1711                         case Operator.Modulus:
1712                                 if (l == TypeManager.uint32_type || l == TypeManager.uint64_type)
1713                                         opcode = OpCodes.Rem_Un;
1714                                 else
1715                                         opcode = OpCodes.Rem;
1716                                 break;
1717
1718                         case Operator.Addition:
1719                                 if (ec.CheckState){
1720                                         if (l == TypeManager.int32_type || l == TypeManager.int64_type)
1721                                                 opcode = OpCodes.Add_Ovf;
1722                                         else if (l==TypeManager.uint32_type || l==TypeManager.uint64_type)
1723                                                 opcode = OpCodes.Add_Ovf_Un;
1724                                         else
1725                                                 opcode = OpCodes.Mul;
1726                                 } else
1727                                         opcode = OpCodes.Add;
1728                                 break;
1729
1730                         case Operator.Subtraction:
1731                                 if (ec.CheckState){
1732                                         if (l == TypeManager.int32_type || l == TypeManager.int64_type)
1733                                                 opcode = OpCodes.Sub_Ovf;
1734                                         else if (l==TypeManager.uint32_type || l==TypeManager.uint64_type)
1735                                                 opcode = OpCodes.Sub_Ovf_Un;
1736                                         else
1737                                                 opcode = OpCodes.Sub;
1738                                 } else
1739                                         opcode = OpCodes.Sub;
1740                                 break;
1741
1742                         case Operator.RightShift:
1743                                 opcode = OpCodes.Shr;
1744                                 break;
1745                                 
1746                         case Operator.LeftShift:
1747                                 opcode = OpCodes.Shl;
1748                                 break;
1749
1750                         case Operator.Equality:
1751                                 opcode = OpCodes.Ceq;
1752                                 break;
1753
1754                         case Operator.Inequality:
1755                                 ec.ig.Emit (OpCodes.Ceq);
1756                                 ec.ig.Emit (OpCodes.Ldc_I4_0);
1757                                 
1758                                 opcode = OpCodes.Ceq;
1759                                 break;
1760
1761                         case Operator.LessThan:
1762                                 opcode = OpCodes.Clt;
1763                                 break;
1764
1765                         case Operator.GreaterThan:
1766                                 opcode = OpCodes.Cgt;
1767                                 break;
1768
1769                         case Operator.LessThanOrEqual:
1770                                 ec.ig.Emit (OpCodes.Cgt);
1771                                 ec.ig.Emit (OpCodes.Ldc_I4_0);
1772                                 
1773                                 opcode = OpCodes.Ceq;
1774                                 break;
1775
1776                         case Operator.GreaterThanOrEqual:
1777                                 ec.ig.Emit (OpCodes.Clt);
1778                                 ec.ig.Emit (OpCodes.Ldc_I4_1);
1779                                 
1780                                 opcode = OpCodes.Sub;
1781                                 break;
1782
1783                         case Operator.LogicalOr:
1784                         case Operator.BitwiseOr:
1785                                 opcode = OpCodes.Or;
1786                                 break;
1787
1788                         case Operator.LogicalAnd:
1789                         case Operator.BitwiseAnd:
1790                                 opcode = OpCodes.And;
1791                                 break;
1792
1793                         case Operator.ExclusiveOr:
1794                                 opcode = OpCodes.Xor;
1795                                 break;
1796
1797                         default:
1798                                 throw new Exception ("This should not happen: Operator = "
1799                                                      + oper.ToString ());
1800                         }
1801
1802                         ig.Emit (opcode);
1803                 }
1804         }
1805
1806         public class Conditional : Expression {
1807                 Expression expr, trueExpr, falseExpr;
1808                 
1809                 public Conditional (Expression expr, Expression trueExpr, Expression falseExpr)
1810                 {
1811                         this.expr = expr;
1812                         this.trueExpr = trueExpr;
1813                         this.falseExpr = falseExpr;
1814                 }
1815
1816                 public Expression Expr {
1817                         get {
1818                                 return expr;
1819                         }
1820                 }
1821
1822                 public Expression TrueExpr {
1823                         get {
1824                                 return trueExpr;
1825                         }
1826                 }
1827
1828                 public Expression FalseExpr {
1829                         get {
1830                                 return falseExpr;
1831                         }
1832                 }
1833
1834                 public override Expression Resolve (TypeContainer tc)
1835                 {
1836                         // FIXME: Implement;
1837                         throw new Exception ("Unimplemented");
1838                         // return this;
1839                 }
1840
1841                 public override void Emit (EmitContext ec)
1842                 {
1843                 }
1844         }
1845
1846         public class SimpleName : Expression {
1847                 public readonly string Name;
1848                 public readonly Location Location;
1849                 
1850                 public SimpleName (string name, Location l)
1851                 {
1852                         Name = name;
1853                         Location = l;
1854                 }
1855
1856                 //
1857                 // Checks whether we are trying to access an instance
1858                 // property, method or field from a static body.
1859                 //
1860                 Expression MemberStaticCheck (Report r, Expression e)
1861                 {
1862                         if (e is FieldExpr){
1863                                 FieldInfo fi = ((FieldExpr) e).FieldInfo;
1864                                 
1865                                 if (!fi.IsStatic){
1866                                         r.Error (120,
1867                                                  "An object reference is required " +
1868                                                  "for the non-static field `"+Name+"'");
1869                                         return null;
1870                                 }
1871                         } else if (e is MethodGroupExpr){
1872                                 // FIXME: Pending reorganization of MemberLookup
1873                                 // Basically at this point we should have the
1874                                 // best match already selected for us, and
1875                                 // we should only have to check a *single*
1876                                 // Method for its static on/off bit.
1877                                 return e;
1878                         } else if (e is PropertyExpr){
1879                                 if (!((PropertyExpr) e).IsStatic){
1880                                         r.Error (120,
1881                                                  "An object reference is required " +
1882                                                  "for the non-static property access `"+
1883                                                  Name+"'");
1884                                         return null;
1885                                 }
1886                         }
1887
1888                         return e;
1889                 }
1890                 
1891                 //
1892                 // 7.5.2: Simple Names. 
1893                 //
1894                 // Local Variables and Parameters are handled at
1895                 // parse time, so they never occur as SimpleNames.
1896                 //
1897                 Expression ResolveSimpleName (TypeContainer tc)
1898                 {
1899                         Expression e;
1900                         Report r = tc.RootContext.Report;
1901
1902                         e = MemberLookup (tc.RootContext, tc.TypeBuilder, Name, true);
1903                         if (e != null){
1904                                 if (e is TypeExpr)
1905                                         return e;
1906                                 else if (e is FieldExpr){
1907                                         FieldExpr fe = (FieldExpr) e;
1908
1909                                         if (!fe.FieldInfo.IsStatic)
1910                                                 fe.Instance = new This ();
1911                                 }
1912                                 
1913                                 if ((tc.ModFlags & Modifiers.STATIC) != 0)
1914                                         return MemberStaticCheck (r, e);
1915                                 else
1916                                         return e;
1917                         }
1918
1919                         //
1920                         // Do step 3 of the Simple Name resolution.
1921                         //
1922                         // FIXME: implement me.
1923
1924                         r.Error (103, Location, "The name `" + Name + "' does not exist in the class `" +
1925                                  tc.Name + "'");
1926
1927                         return null;
1928                 }
1929                 
1930                 //
1931                 // SimpleName needs to handle a multitude of cases:
1932                 //
1933                 // simple_names and qualified_identifiers are placed on
1934                 // the tree equally.
1935                 //
1936                 public override Expression Resolve (TypeContainer tc)
1937                 {
1938                         if (Name.IndexOf (".") != -1)
1939                                 return ResolveMemberAccess (tc, Name);
1940                         else
1941                                 return ResolveSimpleName (tc);
1942                 }
1943
1944                 public override void Emit (EmitContext ec)
1945                 {
1946                         throw new Exception ("SimpleNames should be gone from the tree");
1947                 }
1948         }
1949
1950         // <summary>
1951         //   A simple interface that should be implemeneted by LValues
1952         // </summary>
1953         public interface LValue {
1954                 void Store (ILGenerator ig);
1955         }
1956         
1957         public class LocalVariableReference : Expression, LValue {
1958                 public readonly string Name;
1959                 public readonly Block Block;
1960                 
1961                 public LocalVariableReference (Block block, string name)
1962                 {
1963                         Block = block;
1964                         Name = name;
1965                         eclass = ExprClass.Variable;
1966                 }
1967
1968                 public VariableInfo VariableInfo {
1969                         get {
1970                                 return Block.GetVariableInfo (Name);
1971                         }
1972                 }
1973                 
1974                 public override Expression Resolve (TypeContainer tc)
1975                 {
1976                         VariableInfo vi = Block.GetVariableInfo (Name);
1977
1978                         type = vi.VariableType;
1979                         return this;
1980                 }
1981
1982                 public override void Emit (EmitContext ec)
1983                 {
1984                         VariableInfo vi = VariableInfo;
1985                         ILGenerator ig = ec.ig;
1986                         int idx = vi.Idx;
1987
1988                         switch (idx){
1989                         case 0:
1990                                 ig.Emit (OpCodes.Ldloc_0);
1991                                 break;
1992                                 
1993                         case 1:
1994                                 ig.Emit (OpCodes.Ldloc_1);
1995                                 break;
1996
1997                         case 2:
1998                                 ig.Emit (OpCodes.Ldloc_2);
1999                                 break;
2000
2001                         case 3:
2002                                 ig.Emit (OpCodes.Ldloc_3);
2003                                 break;
2004
2005                         default:
2006                                 if (idx < 255)
2007                                         ig.Emit (OpCodes.Ldloc_S, idx);
2008                                 else
2009                                         ig.Emit (OpCodes.Ldloc, idx);
2010                                 break;
2011                         }
2012                 }
2013
2014                 public void Store (ILGenerator ig)
2015                 {
2016                         VariableInfo vi = VariableInfo;
2017                         int idx = vi.Idx;
2018                                         
2019                         switch (idx){
2020                         case 0:
2021                                 ig.Emit (OpCodes.Stloc_0);
2022                                 break;
2023                                 
2024                         case 1:
2025                                 ig.Emit (OpCodes.Stloc_1);
2026                                 break;
2027                                 
2028                         case 2:
2029                                 ig.Emit (OpCodes.Stloc_2);
2030                                 break;
2031                                 
2032                         case 3:
2033                                 ig.Emit (OpCodes.Stloc_3);
2034                                 break;
2035                                 
2036                         default:
2037                                 if (idx < 255)
2038                                         ig.Emit (OpCodes.Stloc_S, idx);
2039                                 else
2040                                         ig.Emit (OpCodes.Stloc, idx);
2041                                 break;
2042                         }
2043                 }
2044         }
2045
2046         public class ParameterReference : Expression, LValue {
2047                 public readonly Parameters Pars;
2048                 public readonly String Name;
2049                 public readonly int Idx;
2050                 
2051                 public ParameterReference (Parameters pars, int idx, string name)
2052                 {
2053                         Pars = pars;
2054                         Idx  = idx;
2055                         Name = name;
2056                         eclass = ExprClass.Variable;
2057                 }
2058
2059                 public override Expression Resolve (TypeContainer tc)
2060                 {
2061                         Type [] types = Pars.GetParameterInfo (tc);
2062
2063                         type = types [Idx];
2064
2065                         return this;
2066                 }
2067
2068                 public override void Emit (EmitContext ec)
2069                 {
2070                         if (Idx < 255)
2071                                 ec.ig.Emit (OpCodes.Ldarg_S, Idx);
2072                         else
2073                                 ec.ig.Emit (OpCodes.Ldarg, Idx);
2074                 }
2075
2076                 public void Store (ILGenerator ig)
2077                 {
2078                         if (Idx < 255)
2079                                 ig.Emit (OpCodes.Starg_S, Idx);
2080                         else
2081                                 ig.Emit (OpCodes.Starg, Idx);
2082                         
2083                 }
2084         }
2085         
2086         // <summary>
2087         //   Used for arguments to New(), Invocation()
2088         // </summary>
2089         public class Argument {
2090                 public enum AType {
2091                         Expression,
2092                         Ref,
2093                         Out
2094                 };
2095
2096                 public readonly AType Type;
2097                 Expression expr;
2098
2099                 public Argument (Expression expr, AType type)
2100                 {
2101                         this.expr = expr;
2102                         this.Type = type;
2103                 }
2104
2105                 public Expression Expr {
2106                         get {
2107                                 return expr;
2108                         }
2109
2110                         set {
2111                                 expr = value;
2112                         }
2113                 }
2114
2115                 public bool Resolve (TypeContainer tc)
2116                 {
2117                         expr = expr.Resolve (tc);
2118
2119                         return expr != null;
2120                 }
2121
2122                 public void Emit (EmitContext ec)
2123                 {
2124                         expr.Emit (ec);
2125                 }
2126         }
2127
2128         // <summary>
2129         //   Invocation of methods or delegates.
2130         // </summary>
2131         public class Invocation : ExpressionStatement {
2132                 public readonly ArrayList Arguments;
2133                 public readonly Location Location;
2134                 
2135                 Expression expr;
2136                 MethodBase method = null;
2137                         
2138                 static Hashtable method_parameter_cache;
2139
2140                 static Invocation ()
2141                 {
2142                         method_parameter_cache = new Hashtable ();
2143                 }
2144                         
2145                 //
2146                 // arguments is an ArrayList, but we do not want to typecast,
2147                 // as it might be null.
2148                 //
2149                 // FIXME: only allow expr to be a method invocation or a
2150                 // delegate invocation (7.5.5)
2151                 //
2152                 public Invocation (Expression expr, ArrayList arguments, Location l)
2153                 {
2154                         this.expr = expr;
2155                         Arguments = arguments;
2156                         Location = l;
2157                 }
2158
2159                 public Expression Expr {
2160                         get {
2161                                 return expr;
2162                         }
2163                 }
2164
2165                 /// <summary>
2166                 ///   Computes whether Argument `a' and the Type t of the  ParameterInfo `pi' are
2167                 ///   compatible, and if so, how good is the match (in terms of
2168                 ///   "better conversions" (7.4.2.3).
2169                 ///
2170                 ///   0   is the best possible match.
2171                 ///   -1  represents a type mismatch.
2172                 ///   -2  represents a ref/out mismatch.
2173                 /// </summary>
2174                 static int Badness (Argument a, Type t)
2175                 {
2176                         Expression argument_expr = a.Expr;
2177                         Type argument_type = argument_expr.Type;
2178
2179                         if (argument_type == null){
2180                                 throw new Exception ("Expression of type " + a.Expr + " does not resolve its type");
2181                         }
2182                         
2183                         if (t == argument_type) 
2184                                 return 0;
2185
2186                         //
2187                         // Now probe whether an implicit constant expression conversion
2188                         // can be used.
2189                         //
2190                         // An implicit constant expression conversion permits the following
2191                         // conversions:
2192                         //
2193                         //    * A constant-expression of type `int' can be converted to type
2194                         //      sbyte, byute, short, ushort, uint, ulong provided the value of
2195                         //      of the expression is withing the range of the destination type.
2196                         //
2197                         //    * A constant-expression of type long can be converted to type
2198                         //      ulong, provided the value of the constant expression is not negative
2199                         //
2200                         // FIXME: Note that this assumes that constant folding has
2201                         // taken place.  We dont do constant folding yet.
2202                         //
2203
2204                         if (argument_type == TypeManager.int32_type && argument_expr is IntLiteral){
2205                                 IntLiteral ei = (IntLiteral) argument_expr;
2206                                 int value = ei.Value;
2207                                 
2208                                 if (t == TypeManager.sbyte_type){
2209                                         if (value >= SByte.MinValue && value <= SByte.MaxValue)
2210                                                 return 1;
2211                                 } else if (t == TypeManager.byte_type){
2212                                         if (Byte.MinValue >= 0 && value <= Byte.MaxValue)
2213                                                 return 1;
2214                                 } else if (t == TypeManager.short_type){
2215                                         if (value >= Int16.MinValue && value <= Int16.MaxValue)
2216                                                 return 1;
2217                                 } else if (t == TypeManager.ushort_type){
2218                                         if (value >= UInt16.MinValue && value <= UInt16.MaxValue)
2219                                                 return 1;
2220                                 } else if (t == TypeManager.uint32_type){
2221                                         //
2222                                         // we can optimize this case: a positive int32
2223                                         // always fits on a uint32
2224                                         //
2225                                         if (value >= 0)
2226                                                 return 1;
2227                                 } else if (t == TypeManager.uint64_type){
2228                                         //
2229                                         // we can optimize this case: a positive int32
2230                                         // always fits on a uint64
2231                                         //
2232                                         if (value >= 0)
2233                                                 return 1;
2234                                 }
2235                         } else if (argument_type == TypeManager.int64_type && argument_expr is LongLiteral){
2236                                 LongLiteral ll = (LongLiteral) argument_expr;
2237                                 
2238                                 if (t == TypeManager.uint64_type){
2239                                         if (ll.Value > 0)
2240                                                 return 1;
2241                                 }
2242                         }
2243                         
2244                         // FIXME: Implement user-defined implicit conversions here.
2245                         // FIXME: Implement better conversion here.
2246                         
2247                         return -1;
2248                 }
2249
2250                 // <summary>
2251                 //   Returns the Parameters (a ParameterData interface) for the
2252                 //   Method `mb'
2253                 // </summary>
2254                 static ParameterData GetParameterData (MethodBase mb)
2255                 {
2256                         object pd = method_parameter_cache [mb];
2257
2258                         if (pd != null)
2259                                 return (ParameterData) pd;
2260
2261                         if (mb is MethodBuilder || mb is ConstructorBuilder){
2262                                 MethodCore mc = TypeContainer.LookupMethodByBuilder (mb);
2263
2264                                 InternalParameters ip = mc.ParameterInfo;
2265                                 method_parameter_cache [mb] = ip;
2266
2267                                 return (ParameterData) ip;
2268                         } else {
2269                                 ParameterInfo [] pi = mb.GetParameters ();
2270                                 ReflectionParameters rp = new ReflectionParameters (pi);
2271                                 method_parameter_cache [mb] = rp;
2272
2273                                 return (ParameterData) rp;
2274                         }
2275                 }
2276
2277                 static bool ConversionExists (TypeContainer tc, Type from, Type to)
2278                 {
2279                         // Locate user-defined implicit operators
2280
2281                         Expression mg;
2282                         
2283                         mg = MemberLookup (tc.RootContext, to, "op_Implicit", false);
2284
2285                         if (mg != null) {
2286                                 MethodGroupExpr me = (MethodGroupExpr) mg;
2287                                 
2288                                 for (int i = me.Methods.Length; i > 0;) {
2289                                         i--;
2290                                         MethodBase mb = me.Methods [i];
2291                                         ParameterData pd = GetParameterData (mb);
2292                                         
2293                                         if (from == pd.ParameterType (0))
2294                                                 return true;
2295                                 }
2296                         }
2297
2298                         mg = MemberLookup (tc.RootContext, from, "op_Implicit", false);
2299
2300                         if (mg != null) {
2301                                 MethodGroupExpr me = (MethodGroupExpr) mg;
2302
2303                                 for (int i = me.Methods.Length; i > 0;) {
2304                                         i--;
2305                                         MethodBase mb = me.Methods [i];
2306                                         MethodInfo mi = (MethodInfo) mb;
2307                                         
2308                                         if (mi.ReturnType == to)
2309                                                 return true;
2310                                 }
2311                         }
2312                         
2313                         return false;
2314                 }
2315                 
2316                 // <summary>
2317                 //  Determines "better conversion" as specified in 7.4.2.3
2318                 //  Returns : 1 if a->p is better
2319                 //            0 if a->q or neither is better 
2320                 // </summary>
2321                 static int BetterConversion (TypeContainer tc, Argument a, Type p, Type q)
2322                 {
2323                         
2324                         Type argument_type = a.Expr.Type;
2325                         Expression argument_expr = a.Expr;
2326
2327                         if (argument_type == null)
2328                                 throw new Exception ("Expression of type " + a.Expr + " does not resolve its type");
2329                         
2330                         
2331                         if (p == q)
2332                                 return 0;
2333
2334                         if (argument_type == p)
2335                                 return 1;
2336
2337                         if (argument_type == q)
2338                                 return 0;
2339
2340                         //
2341                         // Now probe whether an implicit constant expression conversion
2342                         // can be used.
2343                         //
2344                         // An implicit constant expression conversion permits the following
2345                         // conversions:
2346                         //
2347                         //    * A constant-expression of type `int' can be converted to type
2348                         //      sbyte, byute, short, ushort, uint, ulong provided the value of
2349                         //      of the expression is withing the range of the destination type.
2350                         //
2351                         //    * A constant-expression of type long can be converted to type
2352                         //      ulong, provided the value of the constant expression is not negative
2353                         //
2354                         // FIXME: Note that this assumes that constant folding has
2355                         // taken place.  We dont do constant folding yet.
2356                         //
2357
2358                         if (argument_type == TypeManager.int32_type && argument_expr is IntLiteral){
2359                                 IntLiteral ei = (IntLiteral) argument_expr;
2360                                 int value = ei.Value;
2361                                 
2362                                 if (p == TypeManager.sbyte_type){
2363                                         if (value >= SByte.MinValue && value <= SByte.MaxValue)
2364                                                 return 1;
2365                                 } else if (p == TypeManager.byte_type){
2366                                         if (Byte.MinValue >= 0 && value <= Byte.MaxValue)
2367                                                 return 1;
2368                                 } else if (p == TypeManager.short_type){
2369                                         if (value >= Int16.MinValue && value <= Int16.MaxValue)
2370                                                 return 1;
2371                                 } else if (p == TypeManager.ushort_type){
2372                                         if (value >= UInt16.MinValue && value <= UInt16.MaxValue)
2373                                                 return 1;
2374                                 } else if (p == TypeManager.uint32_type){
2375                                         //
2376                                         // we can optimize this case: a positive int32
2377                                         // always fits on a uint32
2378                                         //
2379                                         if (value >= 0)
2380                                                 return 1;
2381                                 } else if (p == TypeManager.uint64_type){
2382                                         //
2383                                         // we can optimize this case: a positive int32
2384                                         // always fits on a uint64
2385                                         //
2386                                         if (value >= 0)
2387                                                 return 1;
2388                                 }
2389                         } else if (argument_type == TypeManager.int64_type && argument_expr is LongLiteral){
2390                                 LongLiteral ll = (LongLiteral) argument_expr;
2391                                 
2392                                 if (p == TypeManager.uint64_type){
2393                                         if (ll.Value > 0)
2394                                                 return 1;
2395                                 }
2396                         }
2397
2398                         // User-defined Implicit conversions come here
2399                         
2400                         if (q != null)
2401                                 if (ConversionExists (tc, p, q) == true &&
2402                                     ConversionExists (tc, q, p) == false)
2403                                         return 1;
2404                         
2405                         if (p == TypeManager.sbyte_type)
2406                                 if (q == TypeManager.byte_type || q == TypeManager.ushort_type ||
2407                                     q == TypeManager.uint32_type || q == TypeManager.uint64_type) 
2408                                         return 1;
2409
2410                         if (p == TypeManager.short_type)
2411                                 if (q == TypeManager.ushort_type || q == TypeManager.uint32_type ||
2412                                     q == TypeManager.uint64_type)
2413                                         return 1;
2414
2415                         if (p == TypeManager.int32_type)
2416                                 if (q == TypeManager.uint32_type || q == TypeManager.uint64_type)
2417                                         return 1;
2418
2419                         if (p == TypeManager.int64_type)
2420                                 if (q == TypeManager.uint64_type)
2421                                         return 1;
2422
2423                         return 0;
2424                 }
2425                 
2426                 // <summary>
2427                 //  Determines "Better function" and returns an integer indicating :
2428                 //  0 if candidate ain't better
2429                 //  1 if candidate is better than the current best match
2430                 // </summary>
2431                 static int BetterFunction (TypeContainer tc, ArrayList args, MethodBase candidate, MethodBase best)
2432                 {
2433                         ParameterData candidate_pd = GetParameterData (candidate);
2434                         ParameterData best_pd;
2435                         int argument_count;
2436
2437                         if (args == null)
2438                                 argument_count = 0;
2439                         else
2440                                 argument_count = args.Count;
2441
2442                         if (candidate_pd.Count == 0 && argument_count == 0)
2443                                 return 1;
2444
2445                         if (best == null) {
2446                                 if (candidate_pd.Count == argument_count) {
2447                                         int x = 0;
2448                                         for (int j = argument_count; j > 0;) {
2449                                                 j--;
2450                                                 
2451                                                 Argument a = (Argument) args [j];
2452                                                 
2453                                                 x = BetterConversion (tc, a, candidate_pd.ParameterType (j), null);
2454                                                 
2455                                                 if (x > 0)
2456                                                         continue;
2457                                                 else 
2458                                                         break;
2459                                         }
2460                                         
2461                                         if (x > 0)
2462                                                 return 1;
2463                                         else
2464                                                 return 0;
2465                                         
2466                                 } else
2467                                         return 0;
2468                         }
2469
2470                         best_pd = GetParameterData (best);
2471
2472                         if (candidate_pd.Count == argument_count && best_pd.Count == argument_count) {
2473                                 int rating1 = 0, rating2 = 0;
2474                                 
2475                                 for (int j = argument_count; j > 0;) {
2476                                         j--;
2477                                         int x, y;
2478                                         
2479                                         Argument a = (Argument) args [j];
2480
2481                                         x = BetterConversion (tc, a, candidate_pd.ParameterType (j),
2482                                                               best_pd.ParameterType (j));
2483                                         y = BetterConversion (tc, a, best_pd.ParameterType (j),
2484                                                               candidate_pd.ParameterType (j));
2485                                         
2486                                         rating1 += x;
2487                                         rating2 += y;
2488                                 }
2489
2490                                 if (rating1 > rating2)
2491                                         return 1;
2492                                 else
2493                                         return 0;
2494                         } else
2495                                 return 0;
2496                         
2497                 }
2498
2499                 public static string FullMethodDesc (MethodBase mb)
2500                 {
2501                         StringBuilder sb = new StringBuilder (mb.Name);
2502                         ParameterData pd = GetParameterData (mb);
2503                         
2504                         sb.Append (" (");
2505                         for (int i = pd.Count; i > 0;) {
2506                                 i--;
2507                                 sb.Append (TypeManager.CSharpName (pd.ParameterType (i)));
2508                                 if (i != 0)
2509                                         sb.Append (",");
2510                         }
2511                         
2512                         sb.Append (")");
2513                         return sb.ToString ();
2514                 }
2515                 
2516                 // <summary>
2517                 //   Find the Applicable Function Members (7.4.2.1)
2518                 //
2519                 //   me: Method Group expression with the members to select.
2520                 //       it might contain constructors or methods (or anything
2521                 //       that maps to a method).
2522                 //
2523                 //   Arguments: ArrayList containing resolved Argument objects.
2524                 //
2525                 //   Returns: The MethodBase (either a ConstructorInfo or a MethodInfo)
2526                 //            that is the best match of me on Arguments.
2527                 //
2528                 // </summary>
2529                 public static MethodBase OverloadResolve (TypeContainer tc, MethodGroupExpr me,
2530                                                           ArrayList Arguments, Location loc)
2531                 {
2532                         ArrayList afm = new ArrayList ();
2533                         int best_match_idx = -1;
2534                         MethodBase method = null;
2535                         int argument_count;
2536                         
2537                         for (int i = me.Methods.Length; i > 0; ){
2538                                 i--;
2539                                 MethodBase candidate  = me.Methods [i];
2540                                 int x;
2541                                 
2542                                 x = BetterFunction (tc, Arguments, candidate, method);
2543                                 
2544                                 if (x == 0)
2545                                         continue;
2546                                 else {
2547                                         best_match_idx = i;
2548                                         method = me.Methods [best_match_idx];
2549                                 }
2550                         }
2551                         
2552                         if (best_match_idx != -1)
2553                                 return method;
2554
2555                         // Now we see if we can at least find a method with the same number of arguments
2556                         // and then try doing implicit conversion on the arguments
2557
2558                         if (Arguments == null)
2559                                 argument_count = 0;
2560                         else
2561                                 argument_count = Arguments.Count;
2562
2563                         ParameterData pd = null;
2564                         
2565                         for (int i = me.Methods.Length; i > 0;) {
2566                                 i--;
2567                                 MethodBase mb = me.Methods [i];
2568                                 pd = GetParameterData (mb);
2569
2570                                 if (pd.Count == argument_count) {
2571                                         best_match_idx = i;
2572                                         method = me.Methods [best_match_idx];
2573                                         break;
2574                                 } else
2575                                         continue;
2576                         }
2577
2578                         if (best_match_idx == -1)
2579                                 return null;
2580
2581                         // And now convert implicitly, each argument to the required type
2582                         
2583                         pd = GetParameterData (method);
2584
2585                         for (int j = argument_count; j > 0;) {
2586                                 j--;
2587                                 Argument a = (Argument) Arguments [j];
2588                                 Expression a_expr = a.Expr;
2589                                 
2590                                 Expression conv = ConvertImplicit (tc, a_expr, pd.ParameterType (j));
2591
2592                                 if (conv == null) {
2593                                         tc.RootContext.Report.Error (1502, loc,
2594                                                "The best overloaded match for method '" + FullMethodDesc (method) +
2595                                                "' has some invalid arguments");
2596                                         tc.RootContext.Report.Error (1503, loc,
2597                                                "Argument " + (j+1) +
2598                                                " : Cannot convert from '" + TypeManager.CSharpName (a_expr.Type)
2599                                                + "' to '" + TypeManager.CSharpName (pd.ParameterType (j)) + "'");
2600                                         return null;
2601                                 }
2602
2603                                 //
2604                                 // Update the argument with the implicit conversion
2605                                 //
2606                                 if (a_expr != conv)
2607                                         a.Expr = conv;
2608                         }
2609                         
2610                         return method;
2611                 }
2612
2613                         
2614                 public override Expression Resolve (TypeContainer tc)
2615                 {
2616                         //
2617                         // First, resolve the expression that is used to
2618                         // trigger the invocation
2619                         //
2620                         this.expr = expr.Resolve (tc);
2621                         if (this.expr == null)
2622                                 return null;
2623
2624                         if (!(this.expr is MethodGroupExpr)){
2625                                 report118 (tc, this.expr, "method group");
2626                                 return null;
2627                         }
2628
2629                         //
2630                         // Next, evaluate all the expressions in the argument list
2631                         //
2632                         if (Arguments != null){
2633                                 for (int i = Arguments.Count; i > 0;){
2634                                         --i;
2635                                         Argument a = (Argument) Arguments [i];
2636
2637                                         if (!a.Resolve (tc))
2638                                                 return null;
2639                                 }
2640                         }
2641
2642                         method = OverloadResolve (tc, (MethodGroupExpr) this.expr, Arguments, Location);
2643
2644                         if (method == null){
2645                                 tc.RootContext.Report.Error (-6, Location,
2646                                        "Could not find any applicable function for this argument list");
2647                                 return null;
2648                         }
2649
2650                         if (method is MethodInfo)
2651                                 type = ((MethodInfo)method).ReturnType;
2652
2653                         return this;
2654                 }
2655
2656                 public static void EmitArguments (EmitContext ec, MethodBase method, ArrayList Arguments)
2657                 {
2658                         int top;
2659
2660                         if (Arguments != null)
2661                                 top = Arguments.Count;
2662                         else
2663                                 top = 0;
2664
2665                         for (int i = 0; i < top; i++){
2666                                 Argument a = (Argument) Arguments [i];
2667
2668                                 Console.WriteLine ("Perform the actual type widening of arguments here for things like: void fn (sbyte s);  ... fn (1)");
2669                                 
2670                                 a.Emit (ec);
2671                         }
2672                 }
2673                 
2674                 public override void Emit (EmitContext ec)
2675                 {
2676                         bool is_static = method.IsStatic;
2677
2678                         if (!is_static){
2679                                 MethodGroupExpr mg = (MethodGroupExpr) this.expr;
2680
2681                                 if (mg.InstanceExpression == null){
2682                                         throw new Exception ("Internal compiler error.  Should check in the method groups for static/instance");
2683                                 }
2684
2685                                 mg.InstanceExpression.Emit (ec);
2686                         }
2687
2688                         if (Arguments != null)
2689                                 EmitArguments (ec, method, Arguments);
2690
2691                         if (is_static){
2692                                 if (method is MethodInfo)
2693                                         ec.ig.Emit (OpCodes.Call, (MethodInfo) method);
2694                                 else
2695                                         ec.ig.Emit (OpCodes.Call, (ConstructorInfo) method);
2696                         } else {
2697                                 if (method is MethodInfo)
2698                                         ec.ig.Emit (OpCodes.Callvirt, (MethodInfo) method);
2699                                 else
2700                                         ec.ig.Emit (OpCodes.Callvirt, (ConstructorInfo) method);
2701                         }
2702                 }
2703
2704                 public override void EmitStatement (EmitContext ec)
2705                 {
2706                         Emit (ec);
2707
2708                         // 
2709                         // Pop the return value if there is one
2710                         //
2711                         if (method is MethodInfo){
2712                                 if (((MethodInfo)method).ReturnType != TypeManager.void_type)
2713                                         ec.ig.Emit (OpCodes.Pop);
2714                         }
2715                 }
2716         }
2717
2718         public class New : ExpressionStatement {
2719
2720                 public enum NType {
2721                         Object,
2722                         Array
2723                 };
2724
2725                 public readonly NType     NewType;
2726                 public readonly ArrayList Arguments;
2727                 public readonly string    RequestedType;
2728                 // These are for the case when we have an array
2729                 public readonly string    Rank;
2730                 public readonly ArrayList Indices;
2731                 public readonly ArrayList Initializers;
2732
2733                 Location Location;
2734                 MethodBase method = null;
2735
2736                 public New (string requested_type, ArrayList arguments, Location loc)
2737                 {
2738                         RequestedType = requested_type;
2739                         Arguments = arguments;
2740                         NewType = NType.Object;
2741                         Location = loc;
2742                 }
2743
2744                 public New (string requested_type, ArrayList exprs, string rank, ArrayList initializers, Location loc)
2745                 {
2746                         RequestedType = requested_type;
2747                         Indices       = exprs;
2748                         Rank          = rank;
2749                         Initializers  = initializers;
2750                         NewType       = NType.Array;
2751                         Location      = loc;
2752                 }
2753                 
2754                 public override Expression Resolve (TypeContainer tc)
2755                 {
2756                         type = tc.LookupType (RequestedType, false);
2757
2758                         if (type == null)
2759                                 return null;
2760
2761                         Expression ml;
2762
2763                         ml = MemberLookup (tc.RootContext, type, ".ctor", false,
2764                                            MemberTypes.Constructor, AllBindingsFlags);
2765
2766                         if (! (ml is MethodGroupExpr)){
2767                                 //
2768                                 // FIXME: Find proper error
2769                                 //
2770                                 report118 (tc, ml, "method group");
2771                                 return null;
2772                         }
2773                         
2774                         if (Arguments != null){
2775                                 for (int i = Arguments.Count; i > 0;){
2776                                         --i;
2777                                         Argument a = (Argument) Arguments [i];
2778
2779                                         if (!a.Resolve (tc))
2780                                                 return null;
2781                                 }
2782                         }
2783
2784                         method = Invocation.OverloadResolve (tc, (MethodGroupExpr) ml, Arguments, Location);
2785
2786                         if (method == null) {
2787                                 tc.RootContext.Report.Error (-6, Location,
2788                                 "New invocation: Can not find a constructor for this argument list");
2789                                 return null;
2790                         }
2791                         
2792                         return this;
2793                 }
2794
2795                 public override void Emit (EmitContext ec)
2796                 {
2797                         Invocation.EmitArguments (ec, method, Arguments);
2798                         ec.ig.Emit (OpCodes.Newobj, (ConstructorInfo) method);
2799                 }
2800
2801                 public override void EmitStatement (EmitContext ec)
2802                 {
2803                         Emit (ec);
2804                         ec.ig.Emit (OpCodes.Pop);
2805                 }
2806         }
2807
2808         //
2809         // Represents the `this' construct
2810         //
2811         public class This : Expression, LValue {
2812                 public override Expression Resolve (TypeContainer tc)
2813                 {
2814                         eclass = ExprClass.Variable;
2815                         type = tc.TypeBuilder;
2816
2817                         //
2818                         // FIXME: Verify that this is only used in instance contexts.
2819                         //
2820                         return this;
2821                 }
2822
2823                 public override void Emit (EmitContext ec)
2824                 {
2825                         ec.ig.Emit (OpCodes.Ldarg_0);
2826                 }
2827
2828                 public void Store (ILGenerator ig)
2829                 {
2830                         //
2831                         // Assignment to the "this" variable
2832                         //
2833                         ig.Emit (OpCodes.Starg, 0);
2834                 }
2835         }
2836
2837         public class TypeOf : Expression {
2838                 public readonly string QueriedType;
2839                 
2840                 public TypeOf (string queried_type)
2841                 {
2842                         QueriedType = queried_type;
2843                 }
2844
2845                 public override Expression Resolve (TypeContainer tc)
2846                 {
2847                         type = tc.LookupType (QueriedType, false);
2848
2849                         if (type == null)
2850                                 return null;
2851                         
2852                         eclass = ExprClass.Type;
2853                         return this;
2854                 }
2855
2856                 public override void Emit (EmitContext ec)
2857                 {
2858                         throw new Exception ("Implement me");
2859                         // FIXME: Implement.
2860                 }
2861         }
2862
2863         public class SizeOf : Expression {
2864                 public readonly string QueriedType;
2865                 
2866                 public SizeOf (string queried_type)
2867                 {
2868                         this.QueriedType = queried_type;
2869                 }
2870
2871                 public override Expression Resolve (TypeContainer tc)
2872                 {
2873                         // FIXME: Implement;
2874                         throw new Exception ("Unimplemented");
2875                         // return this;
2876                 }
2877
2878                 public override void Emit (EmitContext ec)
2879                 {
2880                         throw new Exception ("Implement me");
2881                 }
2882         }
2883
2884         public class MemberAccess : Expression {
2885                 public readonly string Identifier;
2886                 Expression expr;
2887                 Expression member_lookup;
2888                 
2889                 public MemberAccess (Expression expr, string id)
2890                 {
2891                         this.expr = expr;
2892                         Identifier = id;
2893                 }
2894
2895                 public Expression Expr {
2896                         get {
2897                                 return expr;
2898                         }
2899                 }
2900                 
2901                 public override Expression Resolve (TypeContainer tc)
2902                 {
2903                         Expression new_expression = expr.Resolve (tc);
2904
2905                         if (new_expression == null)
2906                                 return null;
2907
2908                         member_lookup = MemberLookup (tc.RootContext, expr.Type, Identifier, false);
2909
2910                         if (member_lookup is MethodGroupExpr){
2911                                 MethodGroupExpr mg = (MethodGroupExpr) member_lookup;
2912
2913                                 //
2914                                 // Bind the instance expression to it
2915                                 //
2916                                 // FIXME: This is a horrible way of detecting if it is
2917                                 // an instance expression.  Figure out how to fix this.
2918                                 //
2919
2920                                 if (expr is LocalVariableReference ||
2921                                     expr is ParameterReference ||
2922                                     expr is FieldExpr)
2923                                         mg.InstanceExpression = expr;
2924                                         
2925                                 return member_lookup;
2926                         } else if (member_lookup is FieldExpr){
2927                                 FieldExpr fe = (FieldExpr) member_lookup;
2928
2929                                 fe.Instance = expr;
2930
2931                                 return member_lookup;
2932                         } else
2933                                 //
2934                                 // FIXME: This should generate the proper node
2935                                 // ie, for a Property Access, it should like call it
2936                                 // and stuff.
2937
2938                                 return member_lookup;
2939                 }
2940
2941                 public override void Emit (EmitContext ec)
2942                 {
2943                         throw new Exception ("Implement me");
2944                 }
2945
2946         }
2947
2948         // <summary>
2949         //   Nodes of type Namespace are created during the semantic
2950         //   analysis to resolve member_access/qualified_identifier/simple_name
2951         //   accesses.
2952         //
2953         //   They are born `resolved'. 
2954         // </summary>
2955         public class NamespaceExpr : Expression {
2956                 public readonly string Name;
2957                 
2958                 public NamespaceExpr (string name)
2959                 {
2960                         Name = name;
2961                         eclass = ExprClass.Namespace;
2962                 }
2963
2964                 public override Expression Resolve (TypeContainer tc)
2965                 {
2966                         return this;
2967                 }
2968
2969                 public override void Emit (EmitContext ec)
2970                 {
2971                         throw new Exception ("Namespace expressions should never be emitted");
2972                 }
2973         }
2974
2975         // <summary>
2976         //   Fully resolved expression that evaluates to a type
2977         // </summary>
2978         public class TypeExpr : Expression {
2979                 public TypeExpr (Type t)
2980                 {
2981                         Type = t;
2982                         eclass = ExprClass.Type;
2983                 }
2984
2985                 override public Expression Resolve (TypeContainer tc)
2986                 {
2987                         return this;
2988                 }
2989
2990                 override public void Emit (EmitContext ec)
2991                 {
2992                         throw new Exception ("Implement me");
2993                 }
2994         }
2995
2996         // <summary>
2997         //   MethodGroup Expression.
2998         //  
2999         //   This is a fully resolved expression that evaluates to a type
3000         // </summary>
3001         public class MethodGroupExpr : Expression {
3002                 public readonly MethodBase [] Methods;
3003                 Expression instance_expression = null;
3004                 
3005                 public MethodGroupExpr (MemberInfo [] mi)
3006                 {
3007                         Methods = new MethodBase [mi.Length];
3008                         mi.CopyTo (Methods, 0);
3009                         eclass = ExprClass.MethodGroup;
3010                 }
3011
3012                 //
3013                 // `A method group may have associated an instance expression' 
3014                 // 
3015                 public Expression InstanceExpression {
3016                         get {
3017                                 return instance_expression;
3018                         }
3019
3020                         set {
3021                                 instance_expression = value;
3022                         }
3023                 }
3024                 
3025                 override public Expression Resolve (TypeContainer tc)
3026                 {
3027                         return this;
3028                 }
3029
3030                 override public void Emit (EmitContext ec)
3031                 {
3032                         throw new Exception ("This should never be reached");
3033                 }
3034         }
3035         
3036         public class BuiltinTypeAccess : Expression {
3037                 public readonly string AccessBase;
3038                 public readonly string Method;
3039                 
3040                 public BuiltinTypeAccess (string type, string method)
3041                 {
3042                         System.Console.WriteLine ("DUDE! This type should be fully resolved!");
3043                         AccessBase = type;
3044                         Method = method;
3045                 }
3046
3047                 public override Expression Resolve (TypeContainer tc)
3048                 {
3049                         // FIXME: Implement;
3050                         throw new Exception ("Unimplemented");
3051                         // return this;
3052                 }
3053
3054                 public override void Emit (EmitContext ec)
3055                 {
3056                         throw new Exception ("Unimplemented");
3057                 }
3058         }
3059
3060
3061         //   Fully resolved expression that evaluates to a Field
3062         // </summary>
3063         public class FieldExpr : Expression, LValue {
3064                 public readonly FieldInfo FieldInfo;
3065                 public Expression Instance;
3066                         
3067                 public FieldExpr (FieldInfo fi)
3068                 {
3069                         FieldInfo = fi;
3070                         eclass = ExprClass.Variable;
3071                         type = fi.FieldType;
3072                 }
3073
3074                 override public Expression Resolve (TypeContainer tc)
3075                 {
3076                         if (!FieldInfo.IsStatic){
3077                                 if (Instance == null){
3078                                         throw new Exception ("non-static FieldExpr without instance var\n" +
3079                                                              "You have to assign the Instance variable\n" +
3080                                                              "Of the FieldExpr to set this\n");
3081                                 }
3082
3083                                 Instance = Instance.Resolve (tc);
3084                                 if (Instance == null)
3085                                         return null;
3086                                 
3087                         }
3088                         return this;
3089                 }
3090
3091                 override public void Emit (EmitContext ec)
3092                 {
3093                         ILGenerator ig = ec.ig;
3094
3095                         if (FieldInfo.IsStatic)
3096                                 ig.Emit (OpCodes.Ldsfld, FieldInfo);
3097                         else {
3098                                 Instance.Emit (ec);
3099                                 
3100                                 ig.Emit (OpCodes.Ldfld, FieldInfo);
3101                         }
3102                 }
3103
3104                 public void Store (ILGenerator ig)
3105                 {
3106                         if (FieldInfo.IsStatic)
3107                                 ig.Emit (OpCodes.Stsfld, FieldInfo);
3108                         else
3109                                 ig.Emit (OpCodes.Stfld, FieldInfo);
3110                 }
3111         }
3112         
3113         // <summary>
3114         //   Fully resolved expression that evaluates to a Property
3115         // </summary>
3116         public class PropertyExpr : Expression {
3117                 public readonly PropertyInfo PropertyInfo;
3118                 public readonly bool IsStatic;
3119                 
3120                 public PropertyExpr (PropertyInfo pi)
3121                 {
3122                         PropertyInfo = pi;
3123                         eclass = ExprClass.PropertyAccess;
3124                         IsStatic = false;
3125                                 
3126                         MethodBase [] acc = pi.GetAccessors ();
3127
3128                         for (int i = 0; i < acc.Length; i++)
3129                                 if (acc [i].IsStatic)
3130                                         IsStatic = true;
3131
3132                         type = pi.PropertyType;
3133                 }
3134
3135                 override public Expression Resolve (TypeContainer tc)
3136                 {
3137                         // We are born in resolved state. 
3138                         return this;
3139                 }
3140
3141                 override public void Emit (EmitContext ec)
3142                 {
3143                         // FIXME: Implement;
3144                         throw new Exception ("Unimplemented");
3145                 }
3146         }
3147
3148         // <summary>
3149         //   Fully resolved expression that evaluates to a Property
3150         // </summary>
3151         public class EventExpr : Expression {
3152                 public readonly EventInfo EventInfo;
3153                 
3154                 public EventExpr (EventInfo ei)
3155                 {
3156                         EventInfo = ei;
3157                         eclass = ExprClass.EventAccess;
3158                 }
3159
3160                 override public Expression Resolve (TypeContainer tc)
3161                 {
3162                         // We are born in resolved state. 
3163                         return this;
3164                 }
3165
3166                 override public void Emit (EmitContext ec)
3167                 {
3168                         throw new Exception ("Implement me");
3169                         // FIXME: Implement.
3170                 }
3171         }
3172         
3173         public class CheckedExpr : Expression {
3174
3175                 public Expression Expr;
3176
3177                 public CheckedExpr (Expression e)
3178                 {
3179                         Expr = e;
3180                 }
3181
3182                 public override Expression Resolve (TypeContainer tc)
3183                 {
3184                         Expr = Expr.Resolve (tc);
3185
3186                         if (Expr == null)
3187                                 return null;
3188
3189                         eclass = Expr.ExprClass;
3190                         type = Expr.Type;
3191                         return this;
3192                 }
3193
3194                 public override void Emit (EmitContext ec)
3195                 {
3196                         bool last_check = ec.CheckState;
3197                         
3198                         ec.CheckState = true;
3199                         Expr.Emit (ec);
3200                         ec.CheckState = last_check;
3201                 }
3202                 
3203         }
3204
3205         public class UnCheckedExpr : Expression {
3206
3207                 public Expression Expr;
3208
3209                 public UnCheckedExpr (Expression e)
3210                 {
3211                         Expr = e;
3212                 }
3213
3214                 public override Expression Resolve (TypeContainer tc)
3215                 {
3216                         Expr = Expr.Resolve (tc);
3217
3218                         if (Expr == null)
3219                                 return null;
3220
3221                         eclass = Expr.ExprClass;
3222                         type = Expr.Type;
3223                         return this;
3224                 }
3225
3226                 public override void Emit (EmitContext ec)
3227                 {
3228                         bool last_check = ec.CheckState;
3229                         
3230                         ec.CheckState = false;
3231                         Expr.Emit (ec);
3232                         ec.CheckState = last_check;
3233                 }
3234                 
3235         }
3236         
3237         public class ElementAccess : Expression {
3238                 
3239                 public readonly ArrayList  Arguments;
3240                 public readonly Expression Expr;
3241                 
3242                 public ElementAccess (Expression e, ArrayList e_list)
3243                 {
3244                         Expr = e;
3245                         Arguments = e_list;
3246                 }
3247
3248                 public override Expression Resolve (TypeContainer tc)
3249                 {
3250                         // FIXME: Implement;
3251                         throw new Exception ("Unimplemented");
3252                         // return this;
3253                 }
3254                 
3255                 public override void Emit (EmitContext ec)
3256                 {
3257                         // FIXME : Implement !
3258                         throw new Exception ("Unimplemented");
3259                 }
3260                 
3261         }
3262         
3263         public class BaseAccess : Expression {
3264
3265                 public enum BaseAccessType {
3266                         Member,
3267                         Indexer
3268                 };
3269                 
3270                 public readonly BaseAccessType BAType;
3271                 public readonly string         Member;
3272                 public readonly ArrayList      Arguments;
3273
3274                 public BaseAccess (BaseAccessType t, string member, ArrayList args)
3275                 {
3276                         BAType = t;
3277                         Member = member;
3278                         Arguments = args;
3279                         
3280                 }
3281
3282                 public override Expression Resolve (TypeContainer tc)
3283                 {
3284                         // FIXME: Implement;
3285                         throw new Exception ("Unimplemented");
3286                         // return this;
3287                 }
3288
3289                 public override void Emit (EmitContext ec)
3290                 {
3291                         throw new Exception ("Unimplemented");
3292                 }
3293         }
3294
3295         public class UserImplicitCast : Expression {
3296
3297                 Expression source;
3298                 Type       target; 
3299                 MethodBase method;
3300                 ArrayList  arguments;
3301                 
3302                 public UserImplicitCast (Expression source, Type target)
3303                 {
3304                         this.source = source;
3305                         this.target = target;
3306                 }
3307
3308                 public override Expression Resolve (TypeContainer tc)
3309                 {
3310                         source = source.Resolve (tc);
3311
3312                         if (source == null)
3313                                 return null;
3314
3315                         Expression mg;
3316
3317                         mg = MemberLookup (tc.RootContext, source.Type, "op_Implicit", false);
3318
3319                         if (mg != null) {
3320                                 
3321                                 MethodGroupExpr me = (MethodGroupExpr) mg;
3322
3323                                 arguments = new ArrayList ();
3324                                 arguments.Add (new Argument (source, Argument.AType.Expression));
3325
3326                                 method = Invocation.OverloadResolve (tc, me, arguments, new Location ("", 0,0));
3327                                 if (method != null) {
3328                                         MethodInfo mi = (MethodInfo) method;
3329
3330                                         type = mi.ReturnType;
3331
3332                                         if (type != target)
3333                                                 return null;
3334                                         
3335                                         return this;
3336                                 } else
3337                                         return null;
3338
3339                         } else
3340                                 return null;
3341                 }
3342                 
3343                 public override void Emit (EmitContext ec)
3344                 {
3345                         ILGenerator ig = ec.ig;
3346                         
3347                         if (method != null) {
3348
3349                                 // Note that operators are static anyway
3350                                 
3351                                 if (arguments != null) 
3352                                         Invocation.EmitArguments (ec, method, arguments);
3353                                 
3354                                 if (method is MethodInfo)
3355                                         ig.Emit (OpCodes.Call, (MethodInfo) method);
3356                                 else
3357                                         ig.Emit (OpCodes.Call, (ConstructorInfo) method);
3358
3359                                 return;
3360                         }
3361
3362                         throw new Exception ("Implement me");
3363                 }
3364
3365         }
3366 }