2001-10-17 Miguel de Icaza <miguel@ximian.com>
[mono.git] / mcs / mcs / expression.cs
1 //
2 // expression.cs: Expression representation for the IL tree.
3 //
4 // Author:
5 //   Miguel de Icaza (miguel@ximian.com)
6 //
7 // (C) 2001 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;
19         using System.Collections;
20         using System.Diagnostics;
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,
36                 Namespace,
37                 Type,
38                 MethodGroup,
39                 PropertyAccess,
40                 EventAccess,
41                 IndexerAccess,
42                 Nothing, 
43         }
44
45         // <summary>
46         //   An interface provided by expressions that can be used as
47         //   LValues and can store the value on the top of the stack on
48         //   their storage
49         // </summary>
50         public interface IStackStore {
51
52                 // <summary>
53                 //   The Store method should store the contents of the top
54                 //   of the stack into the storage that is implemented by
55                 //   the particular implementation of LValue
56                 // </summary>
57                 void Store     (EmitContext ec);
58         }
59
60         // <summary>
61         //   This interface is implemented by variables
62         // </summary>
63         public interface IMemoryLocation {
64                 // <summary>
65                 //   The AddressOf method should generate code that loads
66                 //   the address of the object and leaves it on the stack
67                 // </summary>
68                 void AddressOf (EmitContext ec);
69         }
70
71         // <remarks>
72         //   Base class for expressions
73         // </remarks>
74         public abstract class Expression {
75                 protected ExprClass eclass;
76                 protected Type      type;
77                 
78                 public Type Type {
79                         get {
80                                 return type;
81                         }
82
83                         set {
84                                 type = value;
85                         }
86                 }
87
88                 public ExprClass ExprClass {
89                         get {
90                                 return eclass;
91                         }
92
93                         set {
94                                 eclass = value;
95                         }
96                 }
97
98                 // <summary>
99                 //   Utility wrapper routine for Error, just to beautify the code
100                 // </summary>
101                 static protected void Error (int error, string s)
102                 {
103                         Report.Error (error, s);
104                 }
105
106                 static protected void Error (int error, Location loc, string s)
107                 {
108                         Report.Error (error, loc, s);
109                 }
110                 
111                 // <summary>
112                 //   Utility wrapper routine for Warning, just to beautify the code
113                 // </summary>
114                 static protected void Warning (int warning, string s)
115                 {
116                         Report.Warning (warning, s);
117                 }
118
119                 // <summary>
120                 //   Performs semantic analysis on the Expression
121                 // </summary>
122                 //
123                 // <remarks>
124                 //   The Resolve method is invoked to perform the semantic analysis
125                 //   on the node.
126                 //
127                 //   The return value is an expression (it can be the
128                 //   same expression in some cases) or a new
129                 //   expression that better represents this node.
130                 //   
131                 //   For example, optimizations of Unary (LiteralInt)
132                 //   would return a new LiteralInt with a negated
133                 //   value.
134                 //   
135                 //   If there is an error during semantic analysis,
136                 //   then an error should be reported (using Report)
137                 //   and a null value should be returned.
138                 //   
139                 //   There are two side effects expected from calling
140                 //   Resolve(): the the field variable "eclass" should
141                 //   be set to any value of the enumeration
142                 //   `ExprClass' and the type variable should be set
143                 //   to a valid type (this is the type of the
144                 //   expression).
145                 // </remarks>
146                 
147                 public abstract Expression DoResolve (EmitContext ec);
148
149                 public virtual Expression DoResolveLValue (EmitContext ec, Expression right_side)
150                 {
151                         return DoResolve (ec);
152                 }
153                 
154                 //
155                 // Currently Resolve wraps DoResolve to perform sanity
156                 // checking and assertion checking on what we expect from Resolve
157                 //
158                 public Expression Resolve (EmitContext ec)
159                 {
160                         Expression e = DoResolve (ec);
161
162                         if (e != null){
163                                 if (e is SimpleName)
164                                         return e;
165
166                                 if (e.ExprClass == ExprClass.Invalid)
167                                         throw new Exception ("Expression " + e +
168                                                              " ExprClass is Invalid after resolve");
169
170                                 if (e.ExprClass != ExprClass.MethodGroup)
171                                         if (e.type == null)
172                                                 throw new Exception ("Expression " + e +
173                                                                      " did not set its type after Resolve");
174                         }
175
176                         return e;
177                 }
178
179                 //
180                 // Currently ResolveLValue wraps DoResolveLValue to perform sanity
181                 // checking and assertion checking on what we expect from Resolve
182                 //
183                 public Expression ResolveLValue (EmitContext ec, Expression right_side)
184                 {
185                         Expression e = DoResolveLValue (ec, right_side);
186
187                         if (e != null){
188                                 if (e is SimpleName)
189                                         return e;
190
191                                 if (e.ExprClass == ExprClass.Invalid)
192                                         throw new Exception ("Expression " + e +
193                                                              " ExprClass is Invalid after resolve");
194
195                                 if (e.ExprClass != ExprClass.MethodGroup)
196                                         if (e.type == null)
197                                                 throw new Exception ("Expression " + e +
198                                                                      " did not set its type after Resolve");
199                         }
200
201                         return e;
202                 }
203                 
204                 // <summary>
205                 //   Emits the code for the expression
206                 // </summary>
207                 //
208                 // <remarks>
209                 // 
210                 //   The Emit method is invoked to generate the code
211                 //   for the expression.  
212                 //
213                 // </remarks>
214                 public abstract void Emit (EmitContext ec);
215                 
216                 // <summary>
217                 //   Protected constructor.  Only derivate types should
218                 //   be able to be created
219                 // </summary>
220
221                 protected Expression ()
222                 {
223                         eclass = ExprClass.Invalid;
224                         type = null;
225                 }
226
227                 // <summary>
228                 //   Returns a literalized version of a literal FieldInfo
229                 // </summary>
230                 static Expression Literalize (FieldInfo fi)
231                 {
232                         Type t = fi.FieldType;
233                         object v = fi.GetValue (fi);
234
235                         if (t == TypeManager.int32_type)
236                                 return new IntLiteral ((int) v);
237                         else if (t == TypeManager.uint32_type)
238                                 return new UIntLiteral ((uint) v);
239                         else if (t == TypeManager.int64_type)
240                                 return new LongLiteral ((long) v);
241                         else if (t == TypeManager.uint64_type)
242                                 return new ULongLiteral ((ulong) v);
243                         else if (t == TypeManager.float_type)
244                                 return new FloatLiteral ((float) v);
245                         else if (t == TypeManager.double_type)
246                                 return new DoubleLiteral ((double) v);
247                         else if (t == TypeManager.string_type)
248                                 return new StringLiteral ((string) v);
249                         else if (t == TypeManager.short_type)
250                                 return new IntLiteral ((int) ((short)v));
251                         else if (t == TypeManager.ushort_type)
252                                 return new IntLiteral ((int) ((ushort)v));
253                         else if (t == TypeManager.sbyte_type)
254                                 return new IntLiteral ((int) ((sbyte)v));
255                         else if (t == TypeManager.byte_type)
256                                 return new IntLiteral ((int) ((byte)v));
257                         else if (t == TypeManager.char_type)
258                                 return new IntLiteral ((int) ((char)v));
259                         else
260                                 throw new Exception ("Unknown type for literal (" + v.GetType () +
261                                                      "), details: " + fi);
262                 }
263
264                 // 
265                 // Returns a fully formed expression after a MemberLookup
266                 //
267                 static Expression ExprClassFromMemberInfo (EmitContext ec, MemberInfo mi, Location loc)
268                 {
269                         if (mi is EventInfo){
270                                 return new EventExpr ((EventInfo) mi, loc);
271                         } else if (mi is FieldInfo){
272                                 FieldInfo fi = (FieldInfo) mi;
273
274                                 if (fi.IsLiteral){
275                                         Expression e = Literalize (fi);
276                                         e.Resolve (ec);
277
278                                         return e;
279                                 } else
280                                         return new FieldExpr (fi, loc);
281                         } else if (mi is PropertyInfo){
282                                 return new PropertyExpr ((PropertyInfo) mi, loc);
283                         } else if (mi is Type)
284                                 return new TypeExpr ((Type) mi);
285
286                         return null;
287                 }
288                 
289                 //
290                 // FIXME: Probably implement a cache for (t,name,current_access_set)?
291                 //
292                 // FIXME: We need to cope with access permissions here, or this wont
293                 // work!
294                 //
295                 // This code could use some optimizations, but we need to do some
296                 // measurements.  For example, we could use a delegate to `flag' when
297                 // something can not any longer be a method-group (because it is something
298                 // else).
299                 //
300                 // Return values:
301                 //     If the return value is an Array, then it is an array of
302                 //     MethodBases
303                 //   
304                 //     If the return value is an MemberInfo, it is anything, but a Method
305                 //
306                 //     null on error.
307                 //
308                 // FIXME: When calling MemberLookup inside an `Invocation', we should pass
309                 // the arguments here and have MemberLookup return only the methods that
310                 // match the argument count/type, unlike we are doing now (we delay this
311                 // decision).
312                 //
313                 // This is so we can catch correctly attempts to invoke instance methods
314                 // from a static body (scan for error 120 in ResolveSimpleName).
315                 //
316                 public static Expression MemberLookup (EmitContext ec, Type t, string name,
317                                                        bool same_type, MemberTypes mt,
318                                                        BindingFlags bf, Location loc)
319                 {
320                         if (same_type)
321                                 bf |= BindingFlags.NonPublic;
322
323                         MemberInfo [] mi = ec.TypeContainer.RootContext.TypeManager.FindMembers (
324                                 t, mt, bf, Type.FilterName, name);
325
326                         if (mi == null)
327                                 return null;
328
329                         // FIXME : How does this wierd case arise ?
330                         if (mi.Length == 0)
331                                 return null;
332                         
333                         if (mi.Length == 1 && !(mi [0] is MethodBase))
334                                 return Expression.ExprClassFromMemberInfo (ec, mi [0], loc);
335                         
336                         for (int i = 0; i < mi.Length; i++)
337                                 if (!(mi [i] is MethodBase)){
338                                         Error (-5, "Do not know how to reproduce this case: " + 
339                                                "Methods and non-Method with the same name, " +
340                                                "report this please");
341
342                                         for (i = 0; i < mi.Length; i++){
343                                                 Type tt = mi [i].GetType ();
344
345                                                 Console.WriteLine (i + ": " + mi [i]);
346                                                 while (tt != TypeManager.object_type){
347                                                         Console.WriteLine (tt);
348                                                         tt = tt.BaseType;
349                                                 }
350                                         }
351                                 }
352
353                         return new MethodGroupExpr (mi);
354                 }
355
356                 public const MemberTypes AllMemberTypes =
357                         MemberTypes.Constructor |
358                         MemberTypes.Event       |
359                         MemberTypes.Field       |
360                         MemberTypes.Method      |
361                         MemberTypes.NestedType  |
362                         MemberTypes.Property;
363                 
364                 public const BindingFlags AllBindingsFlags =
365                         BindingFlags.Public |
366                         BindingFlags.Static |
367                         BindingFlags.Instance;
368
369                 public static Expression MemberLookup (EmitContext ec, Type t, string name,
370                                                        bool same_type, Location loc)
371                 {
372                         return MemberLookup (ec, t, name, same_type, AllMemberTypes, AllBindingsFlags, loc);
373                 }
374
375                 static public Expression ImplicitReferenceConversion (Expression expr, Type target_type)
376                 {
377                         Type expr_type = expr.Type;
378
379                         if (target_type == TypeManager.object_type) {
380                                 if (expr_type.IsClass)
381                                         return new EmptyCast (expr, target_type);
382                                 if (expr_type.IsValueType)
383                                         return new BoxedCast (expr);
384                         } else if (expr_type.IsSubclassOf (target_type)) {
385                                 return new EmptyCast (expr, target_type);
386                         } else {
387                                 // from any class-type S to any interface-type T.
388                                 if (expr_type.IsClass && target_type.IsInterface) {
389                                         Type [] interfaces = expr_type.FindInterfaces (Module.FilterTypeName,
390                                                                                        target_type.FullName);
391                                         if (interfaces != null)
392                                                 return new EmptyCast (expr, target_type);
393                                 }       
394
395                                 // from any interface type S to interface-type T.
396                                 // FIXME : Is it right to use IsAssignableFrom ?
397                                 if (expr_type.IsInterface && target_type.IsInterface)
398                                         if (target_type.IsAssignableFrom (expr_type))
399                                                 return new EmptyCast (expr, target_type);
400                                 
401                                 
402                                 // from an array-type S to an array-type of type T
403                                 if (expr_type.IsArray && target_type.IsArray) {
404                                         if (expr_type.GetArrayRank () == target_type.GetArrayRank ()) {
405
406                                                 Type expr_element_type = expr_type.GetElementType ();
407                                                 Type target_element_type = target_type.GetElementType ();
408
409                                                 if (!expr_element_type.IsValueType && !target_element_type.IsValueType)
410                                                         if (StandardConversionExists (expr_element_type,
411                                                                                       target_element_type))
412                                                                 return new EmptyCast (expr, target_type);
413                                         }
414                                 }
415                                 
416                                 
417                                 // from an array-type to System.Array
418                                 if (expr_type.IsArray && target_type.IsAssignableFrom (expr_type))
419                                         return new EmptyCast (expr, target_type);
420                                 
421                                 // from any delegate type to System.Delegate
422                                 if (expr_type.IsSubclassOf (TypeManager.delegate_type) &&
423                                     target_type == TypeManager.delegate_type)
424                                         if (target_type.IsAssignableFrom (expr_type))
425                                                 return new EmptyCast (expr, target_type);
426                                         
427                                 // from any array-type or delegate type into System.ICloneable.
428                                 if (expr_type.IsArray || expr_type.IsSubclassOf (TypeManager.delegate_type))
429                                         if (target_type == TypeManager.icloneable_type)
430                                                 return new EmptyCast (expr, target_type);
431                                 
432                                 // from the null type to any reference-type.
433                                 if (expr is NullLiteral)
434                                         return new EmptyCast (expr, target_type);
435
436                                 return null;
437
438                         }
439                         
440                         return null;
441                 }
442
443                 // <summary>
444                 //   Handles expressions like this: decimal d; d = 1;
445                 //   and changes them into: decimal d; d = new System.Decimal (1);
446                 // </summary>
447                 static Expression InternalTypeConstructor (EmitContext ec, Expression expr, Type target)
448                 {
449                         ArrayList args = new ArrayList ();
450
451                         args.Add (new Argument (expr, Argument.AType.Expression));
452
453                         Expression ne = new New (target.FullName, args,
454                                                  new Location (-1));
455
456                         return ne.Resolve (ec);
457                 }
458
459                 // <summary>
460                 //   Implicit Numeric Conversions.
461                 //
462                 //   expr is the expression to convert, returns a new expression of type
463                 //   target_type or null if an implicit conversion is not possible.
464                 //
465                 // </summary>
466                 static public Expression ImplicitNumericConversion (EmitContext ec, Expression expr,
467                                                                     Type target_type, Location loc)
468                 {
469                         Type expr_type = expr.Type;
470                         
471                         //
472                         // Attempt to do the implicit constant expression conversions
473
474                         if (expr is IntLiteral){
475                                 Expression e;
476                                 
477                                 e = TryImplicitIntConversion (target_type, (IntLiteral) expr);
478                                 if (e != null)
479                                         return e;
480                         } else if (expr is LongLiteral){
481                                 //
482                                 // Try the implicit constant expression conversion
483                                 // from long to ulong, instead of a nice routine,
484                                 // we just inline it
485                                 //
486                                 if (((LongLiteral) expr).Value > 0)
487                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_I8);
488                         }
489                         
490                         if (expr_type == TypeManager.sbyte_type){
491                                 //
492                                 // From sbyte to short, int, long, float, double.
493                                 //
494                                 if (target_type == TypeManager.int32_type)
495                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_I4);
496                                 if (target_type == TypeManager.int64_type)
497                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_I8);
498                                 if (target_type == TypeManager.double_type)
499                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_R8);
500                                 if (target_type == TypeManager.float_type)
501                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_R4);
502                                 if (target_type == TypeManager.short_type)
503                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_I2);
504                                 if (target_type == TypeManager.decimal_type)
505                                         return InternalTypeConstructor (ec, expr, target_type);
506                         } else if (expr_type == TypeManager.byte_type){
507                                 //
508                                 // From byte to short, ushort, int, uint, long, ulong, float, double
509                                 // 
510                                 if ((target_type == TypeManager.short_type) ||
511                                     (target_type == TypeManager.ushort_type) ||
512                                     (target_type == TypeManager.int32_type) ||
513                                     (target_type == TypeManager.uint32_type))
514                                         return new EmptyCast (expr, target_type);
515
516                                 if (target_type == TypeManager.uint64_type)
517                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_U8);
518                                 if (target_type == TypeManager.int64_type)
519                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_I8);
520                                 
521                                 if (target_type == TypeManager.float_type)
522                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_R4);
523                                 if (target_type == TypeManager.double_type)
524                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_R8);
525                                 if (target_type == TypeManager.decimal_type)
526                                         return InternalTypeConstructor (ec, expr, target_type);
527                         } else if (expr_type == TypeManager.short_type){
528                                 //
529                                 // From short to int, long, float, double
530                                 // 
531                                 if (target_type == TypeManager.int32_type)
532                                         return new EmptyCast (expr, target_type);
533                                 if (target_type == TypeManager.int64_type)
534                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_I8);
535                                 if (target_type == TypeManager.double_type)
536                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_R8);
537                                 if (target_type == TypeManager.float_type)
538                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_R4);
539                                 if (target_type == TypeManager.decimal_type)
540                                         return InternalTypeConstructor (ec, expr, target_type);
541                         } else if (expr_type == TypeManager.ushort_type){
542                                 //
543                                 // From ushort to int, uint, long, ulong, float, double
544                                 //
545                                 if (target_type == TypeManager.uint32_type)
546                                         return new EmptyCast (expr, target_type);
547
548                                 if (target_type == TypeManager.uint64_type)
549                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_U8);
550                                 if (target_type == TypeManager.int32_type)
551                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_I4);
552                                 if (target_type == TypeManager.int64_type)
553                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_I8);
554                                 if (target_type == TypeManager.double_type)
555                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_R8);
556                                 if (target_type == TypeManager.float_type)
557                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_R4);
558                                 if (target_type == TypeManager.decimal_type)
559                                         return InternalTypeConstructor (ec, expr, target_type);
560                         } else if (expr_type == TypeManager.int32_type){
561                                 //
562                                 // From int to long, float, double
563                                 //
564                                 if (target_type == TypeManager.int64_type)
565                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_I8);
566                                 if (target_type == TypeManager.double_type)
567                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_R8);
568                                 if (target_type == TypeManager.float_type)
569                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_R4);
570                                 if (target_type == TypeManager.decimal_type)
571                                         return InternalTypeConstructor (ec, expr, target_type);
572                         } else if (expr_type == TypeManager.uint32_type){
573                                 //
574                                 // From uint to long, ulong, float, double
575                                 //
576                                 if (target_type == TypeManager.int64_type)
577                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_U8);
578                                 if (target_type == TypeManager.uint64_type)
579                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_U8);
580                                 if (target_type == TypeManager.double_type)
581                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_R_Un,
582                                                                OpCodes.Conv_R8);
583                                 if (target_type == TypeManager.float_type)
584                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_R_Un,
585                                                                OpCodes.Conv_R4);
586                                 if (target_type == TypeManager.decimal_type)
587                                         return InternalTypeConstructor (ec, expr, target_type);
588                         } else if ((expr_type == TypeManager.uint64_type) ||
589                                    (expr_type == TypeManager.int64_type)){
590                                 //
591                                 // From long/ulong to float, double
592                                 //
593                                 if (target_type == TypeManager.double_type)
594                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_R_Un,
595                                                                OpCodes.Conv_R8);
596                                 if (target_type == TypeManager.float_type)
597                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_R_Un,
598                                                                OpCodes.Conv_R4);        
599                                 if (target_type == TypeManager.decimal_type)
600                                         return InternalTypeConstructor (ec, expr, target_type);
601                         } else if (expr_type == TypeManager.char_type){
602                                 //
603                                 // From char to ushort, int, uint, long, ulong, float, double
604                                 // 
605                                 if ((target_type == TypeManager.ushort_type) ||
606                                     (target_type == TypeManager.int32_type) ||
607                                     (target_type == TypeManager.uint32_type))
608                                         return new EmptyCast (expr, target_type);
609                                 if (target_type == TypeManager.uint64_type)
610                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_U8);
611                                 if (target_type == TypeManager.int64_type)
612                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_I8);
613                                 if (target_type == TypeManager.float_type)
614                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_R4);
615                                 if (target_type == TypeManager.double_type)
616                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_R8);
617                                 if (target_type == TypeManager.decimal_type)
618                                         return InternalTypeConstructor (ec, expr, target_type);
619                         } else if (expr_type == TypeManager.float_type){
620                                 //
621                                 // float to double
622                                 //
623                                 if (target_type == TypeManager.double_type)
624                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_R8);
625                         }
626
627                         return null;
628                 }
629
630                 // <summary>
631                 //  Determines if a standard implicit conversion exists from
632                 //  expr_type to target_type
633                 // </summary>
634                 public static bool StandardConversionExists (Type expr_type, Type target_type)
635                 {
636                         if (expr_type == target_type)
637                                 return true;
638
639                         // First numeric conversions 
640                         
641                         if (expr_type == TypeManager.sbyte_type){
642                                 //
643                                 // From sbyte to short, int, long, float, double.
644                                 //
645                                 if ((target_type == TypeManager.int32_type) || 
646                                     (target_type == TypeManager.int64_type) ||
647                                     (target_type == TypeManager.double_type) ||
648                                     (target_type == TypeManager.float_type)  ||
649                                     (target_type == TypeManager.short_type) ||
650                                     (target_type == TypeManager.decimal_type))
651                                         return true;
652                                 
653                         } else if (expr_type == TypeManager.byte_type){
654                                 //
655                                 // From byte to short, ushort, int, uint, long, ulong, float, double
656                                 // 
657                                 if ((target_type == TypeManager.short_type) ||
658                                     (target_type == TypeManager.ushort_type) ||
659                                     (target_type == TypeManager.int32_type) ||
660                                     (target_type == TypeManager.uint32_type) ||
661                                     (target_type == TypeManager.uint64_type) ||
662                                     (target_type == TypeManager.int64_type) ||
663                                     (target_type == TypeManager.float_type) ||
664                                     (target_type == TypeManager.double_type) ||
665                                     (target_type == TypeManager.decimal_type))
666                                         return true;
667         
668                         } else if (expr_type == TypeManager.short_type){
669                                 //
670                                 // From short to int, long, float, double
671                                 // 
672                                 if ((target_type == TypeManager.int32_type) ||
673                                     (target_type == TypeManager.int64_type) ||
674                                     (target_type == TypeManager.double_type) ||
675                                     (target_type == TypeManager.float_type) ||
676                                     (target_type == TypeManager.decimal_type))
677                                         return true;
678                                         
679                         } else if (expr_type == TypeManager.ushort_type){
680                                 //
681                                 // From ushort to int, uint, long, ulong, float, double
682                                 //
683                                 if ((target_type == TypeManager.uint32_type) ||
684                                     (target_type == TypeManager.uint64_type) ||
685                                     (target_type == TypeManager.int32_type) ||
686                                     (target_type == TypeManager.int64_type) ||
687                                     (target_type == TypeManager.double_type) ||
688                                     (target_type == TypeManager.float_type) ||
689                                     (target_type == TypeManager.decimal_type))
690                                         return true;
691                                     
692                         } else if (expr_type == TypeManager.int32_type){
693                                 //
694                                 // From int to long, float, double
695                                 //
696                                 if ((target_type == TypeManager.int64_type) ||
697                                     (target_type == TypeManager.double_type) ||
698                                     (target_type == TypeManager.float_type) ||
699                                     (target_type == TypeManager.decimal_type))
700                                         return true;
701                                         
702                         } else if (expr_type == TypeManager.uint32_type){
703                                 //
704                                 // From uint to long, ulong, float, double
705                                 //
706                                 if ((target_type == TypeManager.int64_type) ||
707                                     (target_type == TypeManager.uint64_type) ||
708                                     (target_type == TypeManager.double_type) ||
709                                     (target_type == TypeManager.float_type) ||
710                                     (target_type == TypeManager.decimal_type))
711                                         return true;
712                                         
713                         } else if ((expr_type == TypeManager.uint64_type) ||
714                                    (expr_type == TypeManager.int64_type)) {
715                                 //
716                                 // From long/ulong to float, double
717                                 //
718                                 if ((target_type == TypeManager.double_type) ||
719                                     (target_type == TypeManager.float_type) ||
720                                     (target_type == TypeManager.decimal_type))
721                                         return true;
722                                     
723                         } else if (expr_type == TypeManager.char_type){
724                                 //
725                                 // From char to ushort, int, uint, long, ulong, float, double
726                                 // 
727                                 if ((target_type == TypeManager.ushort_type) ||
728                                     (target_type == TypeManager.int32_type) ||
729                                     (target_type == TypeManager.uint32_type) ||
730                                     (target_type == TypeManager.uint64_type) ||
731                                     (target_type == TypeManager.int64_type) ||
732                                     (target_type == TypeManager.float_type) ||
733                                     (target_type == TypeManager.double_type) ||
734                                     (target_type == TypeManager.decimal_type))
735                                         return true;
736
737                         } else if (expr_type == TypeManager.float_type){
738                                 //
739                                 // float to double
740                                 //
741                                 if (target_type == TypeManager.double_type)
742                                         return true;
743                         }       
744                         
745                         // Next reference conversions
746
747                         if (target_type == TypeManager.object_type) {
748                                 if ((expr_type.IsClass) ||
749                                     (expr_type.IsValueType))
750                                         return true;
751                                 
752                         } else if (expr_type.IsSubclassOf (target_type)) {
753                                 return true;
754                                 
755                         } else {
756                                 // from any class-type S to any interface-type T.
757                                 if (expr_type.IsClass && target_type.IsInterface)
758                                         return true;
759                                 
760                                 // from any interface type S to interface-type T.
761                                 // FIXME : Is it right to use IsAssignableFrom ?
762                                 if (expr_type.IsInterface && target_type.IsInterface)
763                                         if (target_type.IsAssignableFrom (expr_type))
764                                                 return true;
765                                 
766                                 // from an array-type S to an array-type of type T
767                                 if (expr_type.IsArray && target_type.IsArray) {
768                                         if (expr_type.GetArrayRank () == target_type.GetArrayRank ()) {
769                                                 
770                                                 Type expr_element_type = expr_type.GetElementType ();
771                                                 Type target_element_type = target_type.GetElementType ();
772                                                 
773                                                 if (!expr_element_type.IsValueType && !target_element_type.IsValueType)
774                                                         if (StandardConversionExists (expr_element_type,
775                                                                                       target_element_type))
776                                                                 return true;
777                                         }
778                                 }
779                                 
780                                 // from an array-type to System.Array
781                                 if (expr_type.IsArray && target_type.IsAssignableFrom (expr_type))
782                                         return true;
783                                 
784                                 // from any delegate type to System.Delegate
785                                 if (expr_type.IsSubclassOf (TypeManager.delegate_type) &&
786                                     target_type == TypeManager.delegate_type)
787                                         if (target_type.IsAssignableFrom (expr_type))
788                                                 return true;
789                                         
790                                 // from any array-type or delegate type into System.ICloneable.
791                                 if (expr_type.IsArray || expr_type.IsSubclassOf (TypeManager.delegate_type))
792                                         if (target_type == TypeManager.icloneable_type)
793                                                 return true;
794                                 
795                                 // from the null type to any reference-type.
796                                 // FIXME : How do we do this ?
797
798                         }
799
800                         return false;
801                 }
802                 
803                 // <summary>
804                 //  Finds "most encompassed type" according to the spec (13.4.2)
805                 //  amongst the methods in the MethodGroupExpr which convert from a
806                 //  type encompassing source_type
807                 // </summary>
808                 static Type FindMostEncompassedType (MethodGroupExpr me, Type source_type)
809                 {
810                         Type best = null;
811                         
812                         for (int i = me.Methods.Length; i > 0; ) {
813                                 i--;
814
815                                 MethodBase mb = me.Methods [i];
816                                 ParameterData pd = Invocation.GetParameterData (mb);
817                                 Type param_type = pd.ParameterType (0);
818
819                                 if (StandardConversionExists (source_type, param_type)) {
820                                         if (best == null)
821                                                 best = param_type;
822                                         
823                                         if (StandardConversionExists (param_type, best))
824                                                 best = param_type;
825                                 }
826                         }
827
828                         return best;
829                 }
830                 
831                 // <summary>
832                 //  Finds "most encompassing type" according to the spec (13.4.2)
833                 //  amongst the methods in the MethodGroupExpr which convert to a
834                 //  type encompassed by target_type
835                 // </summary>
836                 static Type FindMostEncompassingType (MethodGroupExpr me, Type target)
837                 {
838                         Type best = null;
839                         
840                         for (int i = me.Methods.Length; i > 0; ) {
841                                 i--;
842                                 
843                                 MethodInfo mi = (MethodInfo) me.Methods [i];
844                                 Type ret_type = mi.ReturnType;
845                                 
846                                 if (StandardConversionExists (ret_type, target)) {
847                                         if (best == null)
848                                                 best = ret_type;
849
850                                         if (!StandardConversionExists (ret_type, best))
851                                                 best = ret_type;
852                                 }
853                                 
854                         }
855                         
856                         return best;
857
858                 }
859                 
860
861                 // <summary>
862                 //  User-defined Implicit conversions
863                 // </summary>
864                 static public Expression ImplicitUserConversion (EmitContext ec, Expression source,
865                                                                  Type target, Location loc)
866                 {
867                         return UserDefinedConversion (ec, source, target, loc, false);
868                 }
869
870                 // <summary>
871                 //  User-defined Explicit conversions
872                 // </summary>
873                 static public Expression ExplicitUserConversion (EmitContext ec, Expression source,
874                                                                  Type target, Location loc)
875                 {
876                         return UserDefinedConversion (ec, source, target, loc, true);
877                 }
878                 
879                 // <summary>
880                 //   User-defined conversions
881                 // </summary>
882                 static public Expression UserDefinedConversion (EmitContext ec, Expression source,
883                                                                 Type target, Location loc,
884                                                                 bool look_for_explicit)
885                 {
886                         Expression mg1 = null, mg2 = null, mg3 = null, mg4 = null;
887                         Expression mg5 = null, mg6 = null, mg7 = null, mg8 = null;
888                         Expression e;
889                         MethodBase method = null;
890                         Type source_type = source.Type;
891
892                         string op_name;
893                         
894                         // If we have a boolean type, we need to check for the True operator
895
896                         // FIXME : How does the False operator come into the picture ?
897                         // FIXME : This doesn't look complete and very correct !
898                         if (target == TypeManager.bool_type)
899                                 op_name = "op_True";
900                         else
901                                 op_name = "op_Implicit";
902                         
903                         mg1 = MemberLookup (ec, source_type, op_name, false, loc);
904
905                         if (source_type.BaseType != null)
906                                 mg2 = MemberLookup (ec, source_type.BaseType, op_name, false, loc);
907                         
908                         mg3 = MemberLookup (ec, target, op_name, false, loc);
909
910                         if (target.BaseType != null)
911                                 mg4 = MemberLookup (ec, target.BaseType, op_name, false, loc);
912
913                         MethodGroupExpr union1 = Invocation.MakeUnionSet (mg1, mg2);
914                         MethodGroupExpr union2 = Invocation.MakeUnionSet (mg3, mg4);
915
916                         MethodGroupExpr union3 = Invocation.MakeUnionSet (union1, union2);
917
918                         MethodGroupExpr union4 = null;
919
920                         if (look_for_explicit) {
921
922                                 op_name = "op_Explicit";
923                                 
924                                 mg5 = MemberLookup (ec, source_type, op_name, false, loc);
925
926                                 if (source_type.BaseType != null)
927                                         mg6 = MemberLookup (ec, source_type.BaseType, op_name, false, loc);
928                                 
929                                 mg7 = MemberLookup (ec, target, op_name, false, loc);
930                                 
931                                 if (target.BaseType != null)
932                                         mg8 = MemberLookup (ec, target.BaseType, op_name, false, loc);
933                                 
934                                 MethodGroupExpr union5 = Invocation.MakeUnionSet (mg5, mg6);
935                                 MethodGroupExpr union6 = Invocation.MakeUnionSet (mg7, mg8);
936
937                                 union4 = Invocation.MakeUnionSet (union5, union6);
938                         }
939                         
940                         MethodGroupExpr union = Invocation.MakeUnionSet (union3, union4);
941
942                         if (union != null) {
943
944                                 Type most_specific_source, most_specific_target;
945
946                                 most_specific_source = FindMostEncompassedType (union, source_type);
947                                 if (most_specific_source == null)
948                                         return null;
949
950                                 most_specific_target = FindMostEncompassingType (union, target);
951                                 if (most_specific_target == null) 
952                                         return null;
953                                 
954                                 int count = 0;
955                                 
956                                 for (int i = union.Methods.Length; i > 0;) {
957                                         i--;
958
959                                         MethodBase mb = union.Methods [i];
960                                         ParameterData pd = Invocation.GetParameterData (mb);
961                                         MethodInfo mi = (MethodInfo) union.Methods [i];
962
963                                         if (pd.ParameterType (0) == most_specific_source &&
964                                             mi.ReturnType == most_specific_target) {
965                                                 method = mb;
966                                                 count++;
967                                         }
968                                 }
969
970                                 if (method == null || count > 1) {
971                                         Report.Error (-11, loc, "Ambiguous user defined conversion");
972                                         return null;
973                                 }
974                                 
975                                 //
976                                 // This will do the conversion to the best match that we
977                                 // found.  Now we need to perform an implict standard conversion
978                                 // if the best match was not the type that we were requested
979                                 // by target.
980                                 //
981                                 if (look_for_explicit)
982                                         source = ConvertExplicitStandard (ec, source, most_specific_source, loc);
983                                 else
984                                         source = ConvertImplicitStandard (ec, source,
985                                                                           most_specific_source, loc);
986
987                                 if (source == null)
988                                         return null;
989                                 
990                                 e =  new UserCast ((MethodInfo) method, source);
991                                 
992                                 if (e.Type != target){
993                                         if (!look_for_explicit)
994                                                 e = ConvertImplicitStandard (ec, e, target, loc);
995                                         else
996                                                 e = ConvertExplicitStandard (ec, e, target, loc);
997
998                                         return e;
999                                 } else
1000                                         return e;
1001                         }
1002                         
1003                         return null;
1004                 }
1005                 
1006                 // <summary>
1007                 //   Converts implicitly the resolved expression `expr' into the
1008                 //   `target_type'.  It returns a new expression that can be used
1009                 //   in a context that expects a `target_type'. 
1010                 // </summary>
1011                 static public Expression ConvertImplicit (EmitContext ec, Expression expr,
1012                                                           Type target_type, Location loc)
1013                 {
1014                         Type expr_type = expr.Type;
1015                         Expression e;
1016
1017                         if (expr_type == target_type)
1018                                 return expr;
1019
1020                         e = ImplicitNumericConversion (ec, expr, target_type, loc);
1021                         if (e != null)
1022                                 return e;
1023
1024                         e = ImplicitReferenceConversion (expr, target_type);
1025                         if (e != null)
1026                                 return e;
1027
1028                         e = ImplicitUserConversion (ec, expr, target_type, loc);
1029                         if (e != null)
1030                                 return e;
1031
1032                         if (target_type.IsSubclassOf (TypeManager.enum_type) && expr is IntLiteral){
1033                                 IntLiteral i = (IntLiteral) expr;
1034
1035                                 if (i.Value == 0)
1036                                         return new EmptyCast (expr, target_type);
1037                         }
1038
1039                         return null;
1040                 }
1041
1042                 
1043                 // <summary>
1044                 //   Attempts to apply the `Standard Implicit
1045                 //   Conversion' rules to the expression `expr' into
1046                 //   the `target_type'.  It returns a new expression
1047                 //   that can be used in a context that expects a
1048                 //   `target_type'.
1049                 //
1050                 //   This is different from `ConvertImplicit' in that the
1051                 //   user defined implicit conversions are excluded. 
1052                 // </summary>
1053                 static public Expression ConvertImplicitStandard (EmitContext ec, Expression expr,
1054                                                                   Type target_type, Location loc)
1055                 {
1056                         Type expr_type = expr.Type;
1057                         Expression e;
1058
1059                         if (expr_type == target_type)
1060                                 return expr;
1061
1062                         e = ImplicitNumericConversion (ec, expr, target_type, loc);
1063                         if (e != null)
1064                                 return e;
1065
1066                         e = ImplicitReferenceConversion (expr, target_type);
1067                         if (e != null)
1068                                 return e;
1069
1070                         if (target_type.IsSubclassOf (TypeManager.enum_type) && expr is IntLiteral){
1071                                 IntLiteral i = (IntLiteral) expr;
1072
1073                                 if (i.Value == 0)
1074                                         return new EmptyCast (expr, target_type);
1075                         }
1076                         return null;
1077                 }
1078                 // <summary>
1079                 //   Attemps to perform an implict constant conversion of the IntLiteral
1080                 //   into a different data type using casts (See Implicit Constant
1081                 //   Expression Conversions)
1082                 // </summary>
1083                 static protected Expression TryImplicitIntConversion (Type target_type, IntLiteral il)
1084                 {
1085                         int value = il.Value;
1086                         
1087                         if (target_type == TypeManager.sbyte_type){
1088                                 if (value >= SByte.MinValue && value <= SByte.MaxValue)
1089                                         return il;
1090                         } else if (target_type == TypeManager.byte_type){
1091                                 if (Byte.MinValue >= 0 && value <= Byte.MaxValue)
1092                                         return il;
1093                         } else if (target_type == TypeManager.short_type){
1094                                 if (value >= Int16.MinValue && value <= Int16.MaxValue)
1095                                         return il;
1096                         } else if (target_type == TypeManager.ushort_type){
1097                                 if (value >= UInt16.MinValue && value <= UInt16.MaxValue)
1098                                         return il;
1099                         } else if (target_type == TypeManager.uint32_type){
1100                                 //
1101                                 // we can optimize this case: a positive int32
1102                                 // always fits on a uint32
1103                                 //
1104                                 if (value >= 0)
1105                                         return il;
1106                         } else if (target_type == TypeManager.uint64_type){
1107                                 //
1108                                 // we can optimize this case: a positive int32
1109                                 // always fits on a uint64.  But we need an opcode
1110                                 // to do it.
1111                                 //
1112                                 if (value >= 0)
1113                                         return new OpcodeCast (il, target_type, OpCodes.Conv_I8);
1114                         }
1115
1116                         return null;
1117                 }
1118
1119                 // <summary>
1120                 //   Attemptes to implicityly convert `target' into `type', using
1121                 //   ConvertImplicit.  If there is no implicit conversion, then
1122                 //   an error is signaled
1123                 // </summary>
1124                 static public Expression ConvertImplicitRequired (EmitContext ec, Expression target,
1125                                                                   Type type, Location loc)
1126                 {
1127                         Expression e;
1128                         
1129                         e = ConvertImplicit (ec, target, type, loc);
1130                         if (e != null)
1131                                 return e;
1132                         
1133                         string msg = "Can not convert implicitly from `"+
1134                                 TypeManager.CSharpName (target.Type) + "' to `" +
1135                                 TypeManager.CSharpName (type) + "'";
1136
1137                         Error (29, loc, msg);
1138
1139                         return null;
1140                 }
1141
1142                 // <summary>
1143                 //   Performs the explicit numeric conversions
1144                 // </summary>
1145                 static Expression ConvertNumericExplicit (EmitContext ec, Expression expr,
1146                                                           Type target_type)
1147                 {
1148                         Type expr_type = expr.Type;
1149                         
1150                         if (expr_type == TypeManager.sbyte_type){
1151                                 //
1152                                 // From sbyte to byte, ushort, uint, ulong, char
1153                                 //
1154                                 if (target_type == TypeManager.byte_type)
1155                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_U1);
1156                                 if (target_type == TypeManager.ushort_type)
1157                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_U2);
1158                                 if (target_type == TypeManager.uint32_type)
1159                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_U4);
1160                                 if (target_type == TypeManager.uint64_type)
1161                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_I8);
1162                                 if (target_type == TypeManager.char_type)
1163                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_U2);
1164                         } else if (expr_type == TypeManager.byte_type){
1165                                 //
1166                                 // From byte to sbyte and char
1167                                 //
1168                                 if (target_type == TypeManager.sbyte_type)
1169                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_I1);
1170                                 if (target_type == TypeManager.char_type)
1171                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_U2);
1172                         } else if (expr_type == TypeManager.short_type){
1173                                 //
1174                                 // From short to sbyte, byte, ushort, uint, ulong, char
1175                                 //
1176                                 if (target_type == TypeManager.sbyte_type)
1177                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_I1);
1178                                 if (target_type == TypeManager.byte_type)
1179                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_U1);
1180                                 if (target_type == TypeManager.ushort_type)
1181                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_U2);
1182                                 if (target_type == TypeManager.uint32_type)
1183                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_U4);
1184                                 if (target_type == TypeManager.uint64_type)
1185                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_I8);
1186                                 if (target_type == TypeManager.char_type)
1187                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_U2);
1188                         } else if (expr_type == TypeManager.ushort_type){
1189                                 //
1190                                 // From ushort to sbyte, byte, short, char
1191                                 //
1192                                 if (target_type == TypeManager.sbyte_type)
1193                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_I1);
1194                                 if (target_type == TypeManager.byte_type)
1195                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_U1);
1196                                 if (target_type == TypeManager.short_type)
1197                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_I2);
1198                                 if (target_type == TypeManager.char_type)
1199                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_U2);
1200                         } else if (expr_type == TypeManager.int32_type){
1201                                 //
1202                                 // From int to sbyte, byte, short, ushort, uint, ulong, char
1203                                 //
1204                                 if (target_type == TypeManager.sbyte_type)
1205                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_I1);
1206                                 if (target_type == TypeManager.byte_type)
1207                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_U1);
1208                                 if (target_type == TypeManager.short_type)
1209                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_I2);
1210                                 if (target_type == TypeManager.ushort_type)
1211                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_U2);
1212                                 if (target_type == TypeManager.uint32_type)
1213                                         return new EmptyCast (expr, target_type);
1214                                 if (target_type == TypeManager.uint64_type)
1215                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_I8);
1216                                 if (target_type == TypeManager.char_type)
1217                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_U2);
1218                         } else if (expr_type == TypeManager.uint32_type){
1219                                 //
1220                                 // From uint to sbyte, byte, short, ushort, int, char
1221                                 //
1222                                 if (target_type == TypeManager.sbyte_type)
1223                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_I1);
1224                                 if (target_type == TypeManager.byte_type)
1225                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_U1);
1226                                 if (target_type == TypeManager.short_type)
1227                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_I2);
1228                                 if (target_type == TypeManager.ushort_type)
1229                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_U2);
1230                                 if (target_type == TypeManager.int32_type)
1231                                         return new EmptyCast (expr, target_type);
1232                                 if (target_type == TypeManager.char_type)
1233                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_U2);
1234                         } else if (expr_type == TypeManager.int64_type){
1235                                 //
1236                                 // From long to sbyte, byte, short, ushort, int, uint, ulong, char
1237                                 //
1238                                 if (target_type == TypeManager.sbyte_type)
1239                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_I1);
1240                                 if (target_type == TypeManager.byte_type)
1241                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_U1);
1242                                 if (target_type == TypeManager.short_type)
1243                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_I2);
1244                                 if (target_type == TypeManager.ushort_type)
1245                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_U2);
1246                                 if (target_type == TypeManager.int32_type)
1247                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_I4);
1248                                 if (target_type == TypeManager.uint32_type)
1249                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_U4);
1250                                 if (target_type == TypeManager.uint64_type)
1251                                         return new EmptyCast (expr, target_type);
1252                                 if (target_type == TypeManager.char_type)
1253                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_U2);
1254                         } else if (expr_type == TypeManager.uint64_type){
1255                                 //
1256                                 // From ulong to sbyte, byte, short, ushort, int, uint, long, char
1257                                 //
1258                                 if (target_type == TypeManager.sbyte_type)
1259                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_I1);
1260                                 if (target_type == TypeManager.byte_type)
1261                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_U1);
1262                                 if (target_type == TypeManager.short_type)
1263                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_I2);
1264                                 if (target_type == TypeManager.ushort_type)
1265                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_U2);
1266                                 if (target_type == TypeManager.int32_type)
1267                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_I4);
1268                                 if (target_type == TypeManager.uint32_type)
1269                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_U4);
1270                                 if (target_type == TypeManager.int64_type)
1271                                         return new EmptyCast (expr, target_type);
1272                                 if (target_type == TypeManager.char_type)
1273                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_U2);
1274                         } else if (expr_type == TypeManager.char_type){
1275                                 //
1276                                 // From char to sbyte, byte, short
1277                                 //
1278                                 if (target_type == TypeManager.sbyte_type)
1279                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_I1);
1280                                 if (target_type == TypeManager.byte_type)
1281                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_U1);
1282                                 if (target_type == TypeManager.short_type)
1283                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_I2);
1284                         } else if (expr_type == TypeManager.float_type){
1285                                 //
1286                                 // From float to sbyte, byte, short,
1287                                 // ushort, int, uint, long, ulong, char
1288                                 // or decimal
1289                                 //
1290                                 if (target_type == TypeManager.sbyte_type)
1291                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_I1);
1292                                 if (target_type == TypeManager.byte_type)
1293                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_U1);
1294                                 if (target_type == TypeManager.short_type)
1295                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_I2);
1296                                 if (target_type == TypeManager.ushort_type)
1297                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_U2);
1298                                 if (target_type == TypeManager.int32_type)
1299                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_I4);
1300                                 if (target_type == TypeManager.uint32_type)
1301                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_U4);
1302                                 if (target_type == TypeManager.int64_type)
1303                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_I8);
1304                                 if (target_type == TypeManager.uint64_type)
1305                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_U8);
1306                                 if (target_type == TypeManager.char_type)
1307                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_U2);
1308                                 if (target_type == TypeManager.decimal_type)
1309                                         return InternalTypeConstructor (ec, expr, target_type);
1310                         } else if (expr_type == TypeManager.double_type){
1311                                 //
1312                                 // From double to byte, byte, short,
1313                                 // ushort, int, uint, long, ulong,
1314                                 // char, float or decimal
1315                                 //
1316                                 if (target_type == TypeManager.sbyte_type)
1317                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_I1);
1318                                 if (target_type == TypeManager.byte_type)
1319                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_U1);
1320                                 if (target_type == TypeManager.short_type)
1321                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_I2);
1322                                 if (target_type == TypeManager.ushort_type)
1323                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_U2);
1324                                 if (target_type == TypeManager.int32_type)
1325                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_I4);
1326                                 if (target_type == TypeManager.uint32_type)
1327                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_U4);
1328                                 if (target_type == TypeManager.int64_type)
1329                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_I8);
1330                                 if (target_type == TypeManager.uint64_type)
1331                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_U8);
1332                                 if (target_type == TypeManager.char_type)
1333                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_U2);
1334                                 if (target_type == TypeManager.float_type)
1335                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_R4);
1336                                 if (target_type == TypeManager.decimal_type)
1337                                         return InternalTypeConstructor (ec, expr, target_type);
1338                         } 
1339
1340                         // decimal is taken care of by the op_Explicit methods.
1341
1342                         return null;
1343                 }
1344
1345                 // <summary>
1346                 //  Returns whether an explicit reference conversion can be performed
1347                 //  from source_type to target_type
1348                 // </summary>
1349                 static bool ExplicitReferenceConversionExists (Type source_type, Type target_type)
1350                 {
1351                         bool target_is_value_type = target_type.IsValueType;
1352                         
1353                         if (source_type == target_type)
1354                                 return true;
1355                         
1356                         //
1357                         // From object to any reference type
1358                         //
1359                         if (source_type == TypeManager.object_type && !target_is_value_type)
1360                                 return true;
1361                                         
1362                         //
1363                         // From any class S to any class-type T, provided S is a base class of T
1364                         //
1365                         if (target_type.IsSubclassOf (source_type))
1366                                 return true;
1367
1368                         //
1369                         // From any interface type S to any interface T provided S is not derived from T
1370                         //
1371                         if (source_type.IsInterface && target_type.IsInterface){
1372                                 if (!target_type.IsSubclassOf (source_type))
1373                                         return true;
1374                         }
1375                             
1376                         //
1377                         // From any class type S to any interface T, provides S is not sealed
1378                         // and provided S does not implement T.
1379                         //
1380                         if (target_type.IsInterface && !source_type.IsSealed &&
1381                             !target_type.IsAssignableFrom (source_type))
1382                                 return true;
1383
1384                         //
1385                         // From any interface-type S to to any class type T, provided T is not
1386                         // sealed, or provided T implements S.
1387                         //
1388                         if (source_type.IsInterface &&
1389                             (!target_type.IsSealed || source_type.IsAssignableFrom (target_type)))
1390                                 return true;
1391
1392                         // From an array type S with an element type Se to an array type T with an 
1393                         // element type Te provided all the following are true:
1394                         //     * S and T differe only in element type, in other words, S and T
1395                         //       have the same number of dimensions.
1396                         //     * Both Se and Te are reference types
1397                         //     * An explicit referenc conversions exist from Se to Te
1398                         //
1399                         if (source_type.IsArray && target_type.IsArray) {
1400                                 if (source_type.GetArrayRank () == target_type.GetArrayRank ()) {
1401                                         
1402                                         Type source_element_type = source_type.GetElementType ();
1403                                         Type target_element_type = target_type.GetElementType ();
1404                                         
1405                                         if (!source_element_type.IsValueType && !target_element_type.IsValueType)
1406                                                 if (ExplicitReferenceConversionExists (source_element_type,
1407                                                                                        target_element_type))
1408                                                         return true;
1409                                 }
1410                         }
1411                         
1412
1413                         // From System.Array to any array-type
1414                         if (source_type == TypeManager.array_type &&
1415                             target_type.IsSubclassOf (TypeManager.array_type)){
1416                                 return true;
1417                         }
1418
1419                         //
1420                         // From System delegate to any delegate-type
1421                         //
1422                         if (source_type == TypeManager.delegate_type &&
1423                             target_type.IsSubclassOf (TypeManager.delegate_type))
1424                                 return true;
1425
1426                         //
1427                         // From ICloneable to Array or Delegate types
1428                         //
1429                         if (source_type == TypeManager.icloneable_type &&
1430                             (target_type == TypeManager.array_type ||
1431                              target_type == TypeManager.delegate_type))
1432                                 return true;
1433                         
1434                         return false;
1435                 }
1436
1437                 // <summary>
1438                 //   Implements Explicit Reference conversions
1439                 // </summary>
1440                 static Expression ConvertReferenceExplicit (Expression source, Type target_type)
1441                 {
1442                         Type source_type = source.Type;
1443                         bool target_is_value_type = target_type.IsValueType;
1444                         
1445                         //
1446                         // From object to any reference type
1447                         //
1448                         if (source_type == TypeManager.object_type && !target_is_value_type)
1449                                 return new ClassCast (source, target_type);
1450
1451
1452                         //
1453                         // From any class S to any class-type T, provided S is a base class of T
1454                         //
1455                         if (target_type.IsSubclassOf (source_type))
1456                                 return new ClassCast (source, target_type);
1457
1458                         //
1459                         // From any interface type S to any interface T provided S is not derived from T
1460                         //
1461                         if (source_type.IsInterface && target_type.IsInterface){
1462                                 if (!target_type.IsSubclassOf (source_type))
1463                                         return new ClassCast (source, target_type);
1464                         }
1465                             
1466                         //
1467                         // From any class type S to any interface T, provides S is not sealed
1468                         // and provided S does not implement T.
1469                         //
1470                         if (target_type.IsInterface && !source_type.IsSealed &&
1471                             !target_type.IsAssignableFrom (source_type))
1472                                 return new ClassCast (source, target_type);
1473
1474                         //
1475                         // From any interface-type S to to any class type T, provided T is not
1476                         // sealed, or provided T implements S.
1477                         //
1478                         if (source_type.IsInterface &&
1479                             (!target_type.IsSealed || source_type.IsAssignableFrom (target_type)))
1480                                 return new ClassCast (source, target_type);
1481
1482                         // From an array type S with an element type Se to an array type T with an 
1483                         // element type Te provided all the following are true:
1484                         //     * S and T differe only in element type, in other words, S and T
1485                         //       have the same number of dimensions.
1486                         //     * Both Se and Te are reference types
1487                         //     * An explicit referenc conversions exist from Se to Te
1488                         //
1489                         if (source_type.IsArray && target_type.IsArray) {
1490                                 if (source_type.GetArrayRank () == target_type.GetArrayRank ()) {
1491                                         
1492                                         Type source_element_type = source_type.GetElementType ();
1493                                         Type target_element_type = target_type.GetElementType ();
1494                                         
1495                                         if (!source_element_type.IsValueType && !target_element_type.IsValueType)
1496                                                 if (ExplicitReferenceConversionExists (source_element_type,
1497                                                                                        target_element_type))
1498                                                         return new ClassCast (source, target_type);
1499                                 }
1500                         }
1501                         
1502
1503                         // From System.Array to any array-type
1504                         if (source_type == TypeManager.array_type &&
1505                             target_type.IsSubclassOf (TypeManager.array_type)){
1506                                 return new ClassCast (source, target_type);
1507                         }
1508
1509                         //
1510                         // From System delegate to any delegate-type
1511                         //
1512                         if (source_type == TypeManager.delegate_type &&
1513                             target_type.IsSubclassOf (TypeManager.delegate_type))
1514                                 return new ClassCast (source, target_type);
1515
1516                         //
1517                         // From ICloneable to Array or Delegate types
1518                         //
1519                         if (source_type == TypeManager.icloneable_type &&
1520                             (target_type == TypeManager.array_type ||
1521                              target_type == TypeManager.delegate_type))
1522                                 return new ClassCast (source, target_type);
1523                         
1524                         return null;
1525                 }
1526                 
1527                 // <summary>
1528                 //   Performs an explicit conversion of the expression `expr' whose
1529                 //   type is expr.Type to `target_type'.
1530                 // </summary>
1531                 static public Expression ConvertExplicit (EmitContext ec, Expression expr,
1532                                                           Type target_type, Location loc)
1533                 {
1534                         Expression ne = ConvertImplicitStandard (ec, expr, target_type, loc);
1535
1536                         if (ne != null)
1537                                 return ne;
1538
1539                         ne = ConvertNumericExplicit (ec, expr, target_type);
1540                         if (ne != null)
1541                                 return ne;
1542
1543                         ne = ConvertReferenceExplicit (expr, target_type);
1544                         if (ne != null)
1545                                 return ne;
1546
1547                         ne = ExplicitUserConversion (ec, expr, target_type, loc);
1548                         if (ne != null)
1549                                 return ne;
1550
1551                         Report.Error (30, loc, "Cannot convert type '" + TypeManager.CSharpName (expr.Type) + "' to '"
1552                                       + TypeManager.CSharpName (target_type) + "'");
1553                         return null;
1554                 }
1555
1556                 // <summary>
1557                 //   Same as ConverExplicit, only it doesn't include user defined conversions
1558                 // </summary>
1559                 static public Expression ConvertExplicitStandard (EmitContext ec, Expression expr,
1560                                                                   Type target_type, Location l)
1561                 {
1562                         Expression ne = ConvertImplicitStandard (ec, expr, target_type, l);
1563
1564                         if (ne != null)
1565                                 return ne;
1566
1567                         ne = ConvertNumericExplicit (ec, expr, target_type);
1568                         if (ne != null)
1569                                 return ne;
1570
1571                         ne = ConvertReferenceExplicit (expr, target_type);
1572                         if (ne != null)
1573                                 return ne;
1574
1575                         Report.Error (30, l, "Cannot convert type '" +
1576                                       TypeManager.CSharpName (expr.Type) + "' to '" + 
1577                                       TypeManager.CSharpName (target_type) + "'");
1578                         return null;
1579                 }
1580
1581                 static string ExprClassName (ExprClass c)
1582                 {
1583                         switch (c){
1584                         case ExprClass.Invalid:
1585                                 return "Invalid";
1586                         case ExprClass.Value:
1587                                 return "value";
1588                         case ExprClass.Variable:
1589                                 return "variable";
1590                         case ExprClass.Namespace:
1591                                 return "namespace";
1592                         case ExprClass.Type:
1593                                 return "type";
1594                         case ExprClass.MethodGroup:
1595                                 return "method group";
1596                         case ExprClass.PropertyAccess:
1597                                 return "property access";
1598                         case ExprClass.EventAccess:
1599                                 return "event access";
1600                         case ExprClass.IndexerAccess:
1601                                 return "indexer access";
1602                         case ExprClass.Nothing:
1603                                 return "null";
1604                         }
1605                         throw new Exception ("Should not happen");
1606                 }
1607                 
1608                 // <summary>
1609                 //   Reports that we were expecting `expr' to be of class `expected'
1610                 // </summary>
1611                 protected void report118 (Location loc, Expression expr, string expected)
1612                 {
1613                         string kind = "Unknown";
1614                         
1615                         if (expr != null)
1616                                 kind = ExprClassName (expr.ExprClass);
1617
1618                         Error (118, loc, "Expression denotes a '" + kind +
1619                                "' where an " + expected + " was expected");
1620                 }
1621         }
1622
1623         // <summary>
1624         //   This is just a base class for expressions that can
1625         //   appear on statements (invocations, object creation,
1626         //   assignments, post/pre increment and decrement).  The idea
1627         //   being that they would support an extra Emition interface that
1628         //   does not leave a result on the stack.
1629         // </summary>
1630
1631         public abstract class ExpressionStatement : Expression {
1632
1633                 // <summary>
1634                 //   Requests the expression to be emitted in a `statement'
1635                 //   context.  This means that no new value is left on the
1636                 //   stack after invoking this method (constrasted with
1637                 //   Emit that will always leave a value on the stack).
1638                 // </summary>
1639                 public abstract void EmitStatement (EmitContext ec);
1640         }
1641
1642         // <summary>
1643         //   This kind of cast is used to encapsulate the child
1644         //   whose type is child.Type into an expression that is
1645         //   reported to return "return_type".  This is used to encapsulate
1646         //   expressions which have compatible types, but need to be dealt
1647         //   at higher levels with.
1648         //
1649         //   For example, a "byte" expression could be encapsulated in one
1650         //   of these as an "unsigned int".  The type for the expression
1651         //   would be "unsigned int".
1652         //
1653         // </summary>
1654         
1655         public class EmptyCast : Expression {
1656                 protected Expression child;
1657
1658                 public EmptyCast (Expression child, Type return_type)
1659                 {
1660                         ExprClass = child.ExprClass;
1661                         type = return_type;
1662                         this.child = child;
1663                 }
1664
1665                 public override Expression DoResolve (EmitContext ec)
1666                 {
1667                         // This should never be invoked, we are born in fully
1668                         // initialized state.
1669
1670                         return this;
1671                 }
1672
1673                 public override void Emit (EmitContext ec)
1674                 {
1675                         child.Emit (ec);
1676                 }                       
1677         }
1678
1679         // <summary>
1680         //   This kind of cast is used to encapsulate Value Types in objects.
1681         //
1682         //   The effect of it is to box the value type emitted by the previous
1683         //   operation.
1684         // </summary>
1685         public class BoxedCast : EmptyCast {
1686
1687                 public BoxedCast (Expression expr)
1688                         : base (expr, TypeManager.object_type)
1689                 {
1690                 }
1691
1692                 public override Expression DoResolve (EmitContext ec)
1693                 {
1694                         // This should never be invoked, we are born in fully
1695                         // initialized state.
1696
1697                         return this;
1698                 }
1699
1700                 public override void Emit (EmitContext ec)
1701                 {
1702                         base.Emit (ec);
1703                         ec.ig.Emit (OpCodes.Box, child.Type);
1704                 }
1705         }
1706
1707         // <summary>
1708         //   This kind of cast is used to encapsulate a child expression
1709         //   that can be trivially converted to a target type using one or 
1710         //   two opcodes.  The opcodes are passed as arguments.
1711         // </summary>
1712         public class OpcodeCast : EmptyCast {
1713                 OpCode op, op2;
1714                 bool second_valid;
1715                 
1716                 public OpcodeCast (Expression child, Type return_type, OpCode op)
1717                         : base (child, return_type)
1718                         
1719                 {
1720                         this.op = op;
1721                         second_valid = false;
1722                 }
1723
1724                 public OpcodeCast (Expression child, Type return_type, OpCode op, OpCode op2)
1725                         : base (child, return_type)
1726                         
1727                 {
1728                         this.op = op;
1729                         this.op2 = op2;
1730                         second_valid = true;
1731                 }
1732
1733                 public override Expression DoResolve (EmitContext ec)
1734                 {
1735                         // This should never be invoked, we are born in fully
1736                         // initialized state.
1737
1738                         return this;
1739                 }
1740
1741                 public override void Emit (EmitContext ec)
1742                 {
1743                         base.Emit (ec);
1744                         ec.ig.Emit (op);
1745
1746                         if (second_valid)
1747                                 ec.ig.Emit (op2);
1748                 }                       
1749                 
1750         }
1751
1752         // <summary>
1753         //   This kind of cast is used to encapsulate a child and cast it
1754         //   to the class requested
1755         // </summary>
1756         public class ClassCast : EmptyCast {
1757                 public ClassCast (Expression child, Type return_type)
1758                         : base (child, return_type)
1759                         
1760                 {
1761                 }
1762
1763                 public override Expression DoResolve (EmitContext ec)
1764                 {
1765                         // This should never be invoked, we are born in fully
1766                         // initialized state.
1767
1768                         return this;
1769                 }
1770
1771                 public override void Emit (EmitContext ec)
1772                 {
1773                         base.Emit (ec);
1774
1775                         ec.ig.Emit (OpCodes.Castclass, type);
1776                 }                       
1777                 
1778         }
1779         
1780         // <summary>
1781         //   Unary expressions.  
1782         // </summary>
1783         //
1784         // <remarks>
1785         //   Unary implements unary expressions.   It derives from
1786         //   ExpressionStatement becuase the pre/post increment/decrement
1787         //   operators can be used in a statement context.
1788         // </remarks>
1789         public class Unary : ExpressionStatement {
1790                 public enum Operator {
1791                         Addition, Subtraction, Negate, BitComplement,
1792                         Indirection, AddressOf, PreIncrement,
1793                         PreDecrement, PostIncrement, PostDecrement
1794                 }
1795
1796                 Operator   oper;
1797                 Expression expr;
1798                 ArrayList  Arguments;
1799                 MethodBase method;
1800                 Location   loc;
1801                 
1802                 public Unary (Operator op, Expression expr, Location loc)
1803                 {
1804                         this.oper = op;
1805                         this.expr = expr;
1806                         this.loc = loc;
1807                 }
1808
1809                 public Expression Expr {
1810                         get {
1811                                 return expr;
1812                         }
1813
1814                         set {
1815                                 expr = value;
1816                         }
1817                 }
1818
1819                 public Operator Oper {
1820                         get {
1821                                 return oper;
1822                         }
1823
1824                         set {
1825                                 oper = value;
1826                         }
1827                 }
1828
1829                 // <summary>
1830                 //   Returns a stringified representation of the Operator
1831                 // </summary>
1832                 string OperName ()
1833                 {
1834                         switch (oper){
1835                         case Operator.Addition:
1836                                 return "+";
1837                         case Operator.Subtraction:
1838                                 return "-";
1839                         case Operator.Negate:
1840                                 return "!";
1841                         case Operator.BitComplement:
1842                                 return "~";
1843                         case Operator.AddressOf:
1844                                 return "&";
1845                         case Operator.Indirection:
1846                                 return "*";
1847                         case Operator.PreIncrement : case Operator.PostIncrement :
1848                                 return "++";
1849                         case Operator.PreDecrement : case Operator.PostDecrement :
1850                                 return "--";
1851                         }
1852
1853                         return oper.ToString ();
1854                 }
1855
1856                 Expression ForceConversion (EmitContext ec, Expression expr, Type target_type)
1857                 {
1858                         if (expr.Type == target_type)
1859                                 return expr;
1860
1861                         return ConvertImplicit (ec, expr, target_type, new Location (-1));
1862                 }
1863
1864                 void error23 (Type t)
1865                 {
1866                         Report.Error (
1867                                 23, loc, "Operator " + OperName () +
1868                                 " cannot be applied to operand of type `" +
1869                                 TypeManager.CSharpName (t) + "'");
1870                 }
1871
1872                 // <summary>
1873                 //   Returns whether an object of type `t' can be incremented
1874                 //   or decremented with add/sub (ie, basically whether we can
1875                 //   use pre-post incr-decr operations on it, but it is not a
1876                 //   System.Decimal, which we test elsewhere)
1877                 // </summary>
1878                 static bool IsIncrementableNumber (Type t)
1879                 {
1880                         return (t == TypeManager.sbyte_type) ||
1881                                 (t == TypeManager.byte_type) ||
1882                                 (t == TypeManager.short_type) ||
1883                                 (t == TypeManager.ushort_type) ||
1884                                 (t == TypeManager.int32_type) ||
1885                                 (t == TypeManager.uint32_type) ||
1886                                 (t == TypeManager.int64_type) ||
1887                                 (t == TypeManager.uint64_type) ||
1888                                 (t == TypeManager.char_type) ||
1889                                 (t.IsSubclassOf (TypeManager.enum_type)) ||
1890                                 (t == TypeManager.float_type) ||
1891                                 (t == TypeManager.double_type);
1892                 }
1893                         
1894                 Expression ResolveOperator (EmitContext ec)
1895                 {
1896                         Type expr_type = expr.Type;
1897
1898                         //
1899                         // Step 1: Perform Operator Overload location
1900                         //
1901                         Expression mg;
1902                         string op_name;
1903                         
1904                         if (oper == Operator.PostIncrement || oper == Operator.PreIncrement)
1905                                 op_name = "op_Increment";
1906                         else if (oper == Operator.PostDecrement || oper == Operator.PreDecrement)
1907                                 op_name = "op_Decrement";
1908                         else
1909                                 op_name = "op_" + oper;
1910
1911                         mg = MemberLookup (ec, expr_type, op_name, false, loc);
1912                         
1913                         if (mg == null && expr_type.BaseType != null)
1914                                 mg = MemberLookup (ec, expr_type.BaseType, op_name, false, loc);
1915                         
1916                         if (mg != null) {
1917                                 Arguments = new ArrayList ();
1918                                 Arguments.Add (new Argument (expr, Argument.AType.Expression));
1919                                 
1920                                 method = Invocation.OverloadResolve (ec, (MethodGroupExpr) mg,
1921                                                                      Arguments, loc);
1922                                 if (method != null) {
1923                                         MethodInfo mi = (MethodInfo) method;
1924                                         type = mi.ReturnType;
1925                                         return this;
1926                                 } else {
1927                                         error23 (expr_type);
1928                                         return null;
1929                                 }
1930                                         
1931                         }
1932
1933                         //
1934                         // Step 2: Default operations on CLI native types.
1935                         //
1936
1937                         // Only perform numeric promotions on:
1938                         // +, -, ++, --
1939
1940                         if (expr_type == null)
1941                                 return null;
1942                         
1943                         if (oper == Operator.Negate){
1944                                 if (expr_type != TypeManager.bool_type) {
1945                                         error23 (expr.Type);
1946                                         return null;
1947                                 }
1948                                 
1949                                 type = TypeManager.bool_type;
1950                                 return this;
1951                         }
1952
1953                         if (oper == Operator.BitComplement) {
1954                                 if (!((expr_type == TypeManager.int32_type) ||
1955                                       (expr_type == TypeManager.uint32_type) ||
1956                                       (expr_type == TypeManager.int64_type) ||
1957                                       (expr_type == TypeManager.uint64_type) ||
1958                                       (expr_type.IsSubclassOf (TypeManager.enum_type)))){
1959                                         error23 (expr.Type);
1960                                         return null;
1961                                 }
1962                                 type = expr_type;
1963                                 return this;
1964                         }
1965
1966                         if (oper == Operator.Addition) {
1967                                 //
1968                                 // A plus in front of something is just a no-op, so return the child.
1969                                 //
1970                                 return expr;
1971                         }
1972
1973                         //
1974                         // Deals with -literals
1975                         // int     operator- (int x)
1976                         // long    operator- (long x)
1977                         // float   operator- (float f)
1978                         // double  operator- (double d)
1979                         // decimal operator- (decimal d)
1980                         //
1981                         if (oper == Operator.Subtraction){
1982                                 //
1983                                 // Fold a "- Constant" into a negative constant
1984                                 //
1985                         
1986                                 Expression e = null;
1987
1988                                 //
1989                                 // Is this a constant? 
1990                                 //
1991                                 if (expr is IntLiteral)
1992                                         e = new IntLiteral (-((IntLiteral) expr).Value);
1993                                 else if (expr is LongLiteral)
1994                                         e = new LongLiteral (-((LongLiteral) expr).Value);
1995                                 else if (expr is FloatLiteral)
1996                                         e = new FloatLiteral (-((FloatLiteral) expr).Value);
1997                                 else if (expr is DoubleLiteral)
1998                                         e = new DoubleLiteral (-((DoubleLiteral) expr).Value);
1999                                 else if (expr is DecimalLiteral)
2000                                         e = new DecimalLiteral (-((DecimalLiteral) expr).Value);
2001                                 
2002                                 if (e != null){
2003                                         e = e.Resolve (ec);
2004                                         return e;
2005                                 }
2006
2007                                 //
2008                                 // Not a constant we can optimize, perform numeric 
2009                                 // promotions to int, long, double.
2010                                 //
2011                                 //
2012                                 // The following is inneficient, because we call
2013                                 // ConvertImplicit too many times.
2014                                 //
2015                                 // It is also not clear if we should convert to Float
2016                                 // or Double initially.
2017                                 //
2018                                 if (expr_type == TypeManager.uint32_type){
2019                                         //
2020                                         // FIXME: handle exception to this rule that
2021                                         // permits the int value -2147483648 (-2^31) to
2022                                         // bt written as a decimal interger literal
2023                                         //
2024                                         type = TypeManager.int64_type;
2025                                         expr = ConvertImplicit (ec, expr, type, loc);
2026                                         return this;
2027                                 }
2028
2029                                 if (expr_type == TypeManager.uint64_type){
2030                                         //
2031                                         // FIXME: Handle exception of `long value'
2032                                         // -92233720368547758087 (-2^63) to be written as
2033                                         // decimal integer literal.
2034                                         //
2035                                         error23 (expr_type);
2036                                         return null;
2037                                 }
2038
2039                                 e = ConvertImplicit (ec, expr, TypeManager.int32_type, loc);
2040                                 if (e != null){
2041                                         expr = e;
2042                                         type = e.Type;
2043                                         return this;
2044                                 } 
2045
2046                                 e = ConvertImplicit (ec, expr, TypeManager.int64_type, loc);
2047                                 if (e != null){
2048                                         expr = e;
2049                                         type = e.Type;
2050                                         return this;
2051                                 }
2052
2053                                 e = ConvertImplicit (ec, expr, TypeManager.double_type, loc);
2054                                 if (e != null){
2055                                         expr = e;
2056                                         type = e.Type;
2057                                         return this;
2058                                 }
2059
2060                                 error23 (expr_type);
2061                                 return null;
2062                         }
2063
2064                         //
2065                         // The operand of the prefix/postfix increment decrement operators
2066                         // should be an expression that is classified as a variable,
2067                         // a property access or an indexer access
2068                         //
2069                         if (oper == Operator.PreDecrement || oper == Operator.PreIncrement ||
2070                             oper == Operator.PostDecrement || oper == Operator.PostIncrement){
2071                                 if (expr.ExprClass == ExprClass.Variable){
2072                                         if (IsIncrementableNumber (expr_type) ||
2073                                             expr_type == TypeManager.decimal_type){
2074                                                 type = expr_type;
2075                                                 return this;
2076                                         }
2077                                 } else if (expr.ExprClass == ExprClass.IndexerAccess){
2078                                         //
2079                                         // FIXME: Verify that we have both get and set methods
2080                                         //
2081                                         throw new Exception ("Implement me");
2082                                 } else if (expr.ExprClass == ExprClass.PropertyAccess){
2083                                         PropertyExpr pe = (PropertyExpr) expr;
2084                                         
2085                                         if (pe.VerifyAssignable ())
2086                                                 return this;
2087                                         return null;
2088                                 } else {
2089                                         report118 (loc, expr, "variable, indexer or property access");
2090                                 }
2091                         }
2092
2093                         if (oper == Operator.AddressOf){
2094                                 if (expr.ExprClass != ExprClass.Variable){
2095                                         Error (211, "Cannot take the address of non-variables");
2096                                         return null;
2097                                 }
2098                                 type = Type.GetType (expr.Type.ToString () + "*");
2099                         }
2100                         
2101                         Error (187, "No such operator '" + OperName () + "' defined for type '" +
2102                                TypeManager.CSharpName (expr_type) + "'");
2103                         return null;
2104
2105                 }
2106
2107                 public override Expression DoResolve (EmitContext ec)
2108                 {
2109                         expr = expr.Resolve (ec);
2110                         
2111                         if (expr == null)
2112                                 return null;
2113
2114                         eclass = ExprClass.Value;
2115                         return ResolveOperator (ec);
2116                 }
2117
2118                 public override void Emit (EmitContext ec)
2119                 {
2120                         ILGenerator ig = ec.ig;
2121                         Type expr_type = expr.Type;
2122                         ExprClass eclass;
2123                         
2124                         if (method != null) {
2125
2126                                 // Note that operators are static anyway
2127                                 
2128                                 if (Arguments != null) 
2129                                         Invocation.EmitArguments (ec, method, Arguments);
2130
2131                                 //
2132                                 // Post increment/decrement operations need a copy at this
2133                                 // point.
2134                                 //
2135                                 if (oper == Operator.PostDecrement || oper == Operator.PostIncrement)
2136                                         ig.Emit (OpCodes.Dup);
2137                                 
2138
2139                                 ig.Emit (OpCodes.Call, (MethodInfo) method);
2140
2141                                 //
2142                                 // Pre Increment and Decrement operators
2143                                 //
2144                                 if (oper == Operator.PreIncrement || oper == Operator.PreDecrement){
2145                                         ig.Emit (OpCodes.Dup);
2146                                 }
2147                                 
2148                                 //
2149                                 // Increment and Decrement should store the result
2150                                 //
2151                                 if (oper == Operator.PreDecrement || oper == Operator.PreIncrement ||
2152                                     oper == Operator.PostDecrement || oper == Operator.PostIncrement){
2153                                         ((IStackStore) expr).Store (ec);
2154                                 }
2155                                 return;
2156                         }
2157                         
2158                         switch (oper) {
2159                         case Operator.Addition:
2160                                 throw new Exception ("This should be caught by Resolve");
2161                                 
2162                         case Operator.Subtraction:
2163                                 expr.Emit (ec);
2164                                 ig.Emit (OpCodes.Neg);
2165                                 break;
2166                                 
2167                         case Operator.Negate:
2168                                 expr.Emit (ec);
2169                                 ig.Emit (OpCodes.Ldc_I4_0);
2170                                 ig.Emit (OpCodes.Ceq);
2171                                 break;
2172                                 
2173                         case Operator.BitComplement:
2174                                 expr.Emit (ec);
2175                                 ig.Emit (OpCodes.Not);
2176                                 break;
2177                                 
2178                         case Operator.AddressOf:
2179                                 ((IMemoryLocation)expr).AddressOf (ec);
2180                                 break;
2181                                 
2182                         case Operator.Indirection:
2183                                 throw new Exception ("Not implemented yet");
2184                                 
2185                         case Operator.PreIncrement:
2186                         case Operator.PreDecrement:
2187                                 if (expr.ExprClass == ExprClass.Variable){
2188                                         //
2189                                         // Resolve already verified that it is an "incrementable"
2190                                         // 
2191                                         expr.Emit (ec);
2192                                         ig.Emit (OpCodes.Ldc_I4_1);
2193                                         
2194                                         if (oper == Operator.PreDecrement)
2195                                                 ig.Emit (OpCodes.Sub);
2196                                         else
2197                                                 ig.Emit (OpCodes.Add);
2198                                         ig.Emit (OpCodes.Dup);
2199                                         ((IStackStore) expr).Store (ec);
2200                                 } else {
2201                                         throw new Exception ("Handle Indexers and Properties here");
2202                                 }
2203                                 break;
2204                                 
2205                         case Operator.PostIncrement:
2206                         case Operator.PostDecrement:
2207                                 eclass = expr.ExprClass;
2208                                 if (eclass == ExprClass.Variable){
2209                                         //
2210                                         // Resolve already verified that it is an "incrementable"
2211                                         // 
2212                                         expr.Emit (ec);
2213                                         ig.Emit (OpCodes.Dup);
2214                                         ig.Emit (OpCodes.Ldc_I4_1);
2215                                         
2216                                         if (oper == Operator.PostDecrement)
2217                                                 ig.Emit (OpCodes.Sub);
2218                                         else
2219                                                 ig.Emit (OpCodes.Add);
2220                                         ((IStackStore) expr).Store (ec);
2221                                 } else if (eclass == ExprClass.PropertyAccess){
2222                                         throw new Exception ("Handle Properties here");
2223                                 } else if (eclass == ExprClass.IndexerAccess) {
2224                                         throw new Exception ("Handle Indexers here");
2225                                 } else {
2226                                         Console.WriteLine ("Unknown exprclass: " + eclass);
2227                                 }
2228                                 break;
2229                                 
2230                         default:
2231                                 throw new Exception ("This should not happen: Operator = "
2232                                                      + oper.ToString ());
2233                         }
2234                 }
2235                 
2236
2237                 public override void EmitStatement (EmitContext ec)
2238                 {
2239                         //
2240                         // FIXME: we should rewrite this code to generate
2241                         // better code for ++ and -- as we know we wont need
2242                         // the values on the stack
2243                         //
2244                         Emit (ec);
2245                         ec.ig.Emit (OpCodes.Pop);
2246                 }
2247         }
2248         
2249         public class Probe : Expression {
2250                 public readonly string ProbeType;
2251                 public readonly Operator Oper;
2252                 Expression expr;
2253                 Type probe_type;
2254                 
2255                 public enum Operator {
2256                         Is, As
2257                 }
2258                 
2259                 public Probe (Operator oper, Expression expr, string probe_type)
2260                 {
2261                         Oper = oper;
2262                         ProbeType = probe_type;
2263                         this.expr = expr;
2264                 }
2265
2266                 public Expression Expr {
2267                         get {
2268                                 return expr;
2269                         }
2270                 }
2271                 
2272                 public override Expression DoResolve (EmitContext ec)
2273                 {
2274                         probe_type = ec.TypeContainer.LookupType (ProbeType, false);
2275
2276                         if (probe_type == null)
2277                                 return null;
2278
2279                         expr = expr.Resolve (ec);
2280                         
2281                         type = TypeManager.bool_type;
2282                         eclass = ExprClass.Value;
2283
2284                         return this;
2285                 }
2286
2287                 public override void Emit (EmitContext ec)
2288                 {
2289                         ILGenerator ig = ec.ig;
2290                         
2291                         expr.Emit (ec);
2292                         
2293                         if (Oper == Operator.Is){
2294                                 ig.Emit (OpCodes.Isinst, probe_type);
2295                                 ig.Emit (OpCodes.Ldnull);
2296                                 ig.Emit (OpCodes.Cgt_Un);
2297                         } else {
2298                                 ig.Emit (OpCodes.Isinst, probe_type);
2299                         }
2300                 }
2301         }
2302
2303         // <summary>
2304         //   This represents a typecast in the source language.
2305         //
2306         //   FIXME: Cast expressions have an unusual set of parsing
2307         //   rules, we need to figure those out.
2308         // </summary>
2309         public class Cast : Expression {
2310                 string target_type;
2311                 Expression expr;
2312                 Location   loc;
2313                         
2314                 public Cast (string cast_type, Expression expr, Location loc)
2315                 {
2316                         this.target_type = cast_type;
2317                         this.expr = expr;
2318                         this.loc = loc;
2319                 }
2320
2321                 public string TargetType {
2322                         get {
2323                                 return target_type;
2324                         }
2325                 }
2326
2327                 public Expression Expr {
2328                         get {
2329                                 return expr;
2330                         }
2331                         set {
2332                                 expr = value;
2333                         }
2334                 }
2335                 
2336                 public override Expression DoResolve (EmitContext ec)
2337                 {
2338                         expr = expr.Resolve (ec);
2339                         if (expr == null)
2340                                 return null;
2341                         
2342                         type = ec.TypeContainer.LookupType (target_type, false);
2343                         eclass = ExprClass.Value;
2344                         
2345                         if (type == null)
2346                                 return null;
2347
2348                         expr = ConvertExplicit (ec, expr, type, loc);
2349
2350                         return expr;
2351                 }
2352
2353                 public override void Emit (EmitContext ec)
2354                 {
2355                         //
2356                         // This one will never happen
2357                         //
2358                         throw new Exception ("Should not happen");
2359                 }
2360         }
2361
2362         public class Binary : Expression {
2363                 public enum Operator {
2364                         Multiply, Division, Modulus,
2365                         Addition, Subtraction,
2366                         LeftShift, RightShift,
2367                         LessThan, GreaterThan, LessThanOrEqual, GreaterThanOrEqual, 
2368                         Equality, Inequality,
2369                         BitwiseAnd,
2370                         ExclusiveOr,
2371                         BitwiseOr,
2372                         LogicalAnd,
2373                         LogicalOr
2374                 }
2375
2376                 Operator oper;
2377                 Expression left, right;
2378                 MethodBase method;
2379                 ArrayList  Arguments;
2380                 Location   loc;
2381                 
2382
2383                 public Binary (Operator oper, Expression left, Expression right, Location loc)
2384                 {
2385                         this.oper = oper;
2386                         this.left = left;
2387                         this.right = right;
2388                         this.loc = loc;
2389                 }
2390
2391                 public Operator Oper {
2392                         get {
2393                                 return oper;
2394                         }
2395                         set {
2396                                 oper = value;
2397                         }
2398                 }
2399                 
2400                 public Expression Left {
2401                         get {
2402                                 return left;
2403                         }
2404                         set {
2405                                 left = value;
2406                         }
2407                 }
2408
2409                 public Expression Right {
2410                         get {
2411                                 return right;
2412                         }
2413                         set {
2414                                 right = value;
2415                         }
2416                 }
2417
2418
2419                 // <summary>
2420                 //   Returns a stringified representation of the Operator
2421                 // </summary>
2422                 string OperName ()
2423                 {
2424                         switch (oper){
2425                         case Operator.Multiply:
2426                                 return "*";
2427                         case Operator.Division:
2428                                 return "/";
2429                         case Operator.Modulus:
2430                                 return "%";
2431                         case Operator.Addition:
2432                                 return "+";
2433                         case Operator.Subtraction:
2434                                 return "-";
2435                         case Operator.LeftShift:
2436                                 return "<<";
2437                         case Operator.RightShift:
2438                                 return ">>";
2439                         case Operator.LessThan:
2440                                 return "<";
2441                         case Operator.GreaterThan:
2442                                 return ">";
2443                         case Operator.LessThanOrEqual:
2444                                 return "<=";
2445                         case Operator.GreaterThanOrEqual:
2446                                 return ">=";
2447                         case Operator.Equality:
2448                                 return "==";
2449                         case Operator.Inequality:
2450                                 return "!=";
2451                         case Operator.BitwiseAnd:
2452                                 return "&";
2453                         case Operator.BitwiseOr:
2454                                 return "|";
2455                         case Operator.ExclusiveOr:
2456                                 return "^";
2457                         case Operator.LogicalOr:
2458                                 return "||";
2459                         case Operator.LogicalAnd:
2460                                 return "&&";
2461                         }
2462
2463                         return oper.ToString ();
2464                 }
2465
2466                 Expression ForceConversion (EmitContext ec, Expression expr, Type target_type)
2467                 {
2468                         if (expr.Type == target_type)
2469                                 return expr;
2470
2471                         return ConvertImplicit (ec, expr, target_type, new Location (-1));
2472                 }
2473                 
2474                 //
2475                 // Note that handling the case l == Decimal || r == Decimal
2476                 // is taken care of by the Step 1 Operator Overload resolution.
2477                 //
2478                 void DoNumericPromotions (EmitContext ec, Type l, Type r)
2479                 {
2480                         if (l == TypeManager.double_type || r == TypeManager.double_type){
2481                                 //
2482                                 // If either operand is of type double, the other operand is
2483                                 // conveted to type double.
2484                                 //
2485                                 if (r != TypeManager.double_type)
2486                                         right = ConvertImplicit (ec, right, TypeManager.double_type, loc);
2487                                 if (l != TypeManager.double_type)
2488                                         left = ConvertImplicit (ec, left, TypeManager.double_type, loc);
2489                                 
2490                                 type = TypeManager.double_type;
2491                         } else if (l == TypeManager.float_type || r == TypeManager.float_type){
2492                                 //
2493                                 // if either operand is of type float, th eother operand is
2494                                 // converd to type float.
2495                                 //
2496                                 if (r != TypeManager.double_type)
2497                                         right = ConvertImplicit (ec, right, TypeManager.float_type, loc);
2498                                 if (l != TypeManager.double_type)
2499                                         left = ConvertImplicit (ec, left, TypeManager.float_type, loc);
2500                                 type = TypeManager.float_type;
2501                         } else if (l == TypeManager.uint64_type || r == TypeManager.uint64_type){
2502                                 Expression e;
2503                                 Type other;
2504                                 //
2505                                 // If either operand is of type ulong, the other operand is
2506                                 // converted to type ulong.  or an error ocurrs if the other
2507                                 // operand is of type sbyte, short, int or long
2508                                 //
2509                                 
2510                                 if (l == TypeManager.uint64_type){
2511                                         if (r != TypeManager.uint64_type && right is IntLiteral){
2512                                                 e = TryImplicitIntConversion (l, (IntLiteral) right);
2513                                                 if (e != null)
2514                                                         right = e;
2515                                         }
2516                                         other = right.Type;
2517                                 } else {
2518                                         if (left is IntLiteral){
2519                                                 e = TryImplicitIntConversion (r, (IntLiteral) left);
2520                                                 if (e != null)
2521                                                         left = e;
2522                                         }
2523                                         other = left.Type;
2524                                 }
2525
2526                                 if ((other == TypeManager.sbyte_type) ||
2527                                     (other == TypeManager.short_type) ||
2528                                     (other == TypeManager.int32_type) ||
2529                                     (other == TypeManager.int64_type)){
2530                                         string oper = OperName ();
2531                                         
2532                                         Error (34, loc, "Operator `" + OperName ()
2533                                                + "' is ambiguous on operands of type `"
2534                                                + TypeManager.CSharpName (l) + "' "
2535                                                + "and `" + TypeManager.CSharpName (r)
2536                                                + "'");
2537                                 }
2538                                 type = TypeManager.uint64_type;
2539                         } else if (l == TypeManager.int64_type || r == TypeManager.int64_type){
2540                                 //
2541                                 // If either operand is of type long, the other operand is converted
2542                                 // to type long.
2543                                 //
2544                                 if (l != TypeManager.int64_type)
2545                                         left = ConvertImplicit (ec, left, TypeManager.int64_type, loc);
2546                                 if (r != TypeManager.int64_type)
2547                                         right = ConvertImplicit (ec, right, TypeManager.int64_type, loc);
2548
2549                                 type = TypeManager.int64_type;
2550                         } else if (l == TypeManager.uint32_type || r == TypeManager.uint32_type){
2551                                 //
2552                                 // If either operand is of type uint, and the other
2553                                 // operand is of type sbyte, short or int, othe operands are
2554                                 // converted to type long.
2555                                 //
2556                                 Type other = null;
2557                                 
2558                                 if (l == TypeManager.uint32_type)
2559                                         other = r;
2560                                 else if (r == TypeManager.uint32_type)
2561                                         other = l;
2562
2563                                 if ((other == TypeManager.sbyte_type) ||
2564                                     (other == TypeManager.short_type) ||
2565                                     (other == TypeManager.int32_type)){
2566                                         left = ForceConversion (ec, left, TypeManager.int64_type);
2567                                         right = ForceConversion (ec, right, TypeManager.int64_type);
2568                                         type = TypeManager.int64_type;
2569                                 } else {
2570                                         //
2571                                         // if either operand is of type uint, the other
2572                                         // operand is converd to type uint
2573                                         //
2574                                         left = ForceConversion (ec, left, TypeManager.uint32_type);
2575                                         right = ForceConversion (ec, right, TypeManager.uint32_type);
2576                                         type = TypeManager.uint32_type;
2577                                 } 
2578                         } else if (l == TypeManager.decimal_type || r == TypeManager.decimal_type){
2579                                 if (l != TypeManager.decimal_type)
2580                                         left = ConvertImplicit (ec, left, TypeManager.decimal_type, loc);
2581                                 if (r != TypeManager.decimal_type)
2582                                         right = ConvertImplicit (ec, right, TypeManager.decimal_type, loc);
2583
2584                                 type = TypeManager.decimal_type;
2585                         } else {
2586                                 Expression l_tmp, r_tmp;
2587
2588                                 l_tmp = ForceConversion (ec, left, TypeManager.int32_type);
2589                                 if (l_tmp == null) {
2590                                         error19 ();
2591                                         left = l_tmp;
2592                                         return;
2593                                 }
2594                                 
2595                                 r_tmp = ForceConversion (ec, right, TypeManager.int32_type);
2596                                 if (r_tmp == null) {
2597                                         error19 ();
2598                                         right = r_tmp;
2599                                         return;
2600                                 }
2601                                 
2602                                 type = TypeManager.int32_type;
2603                         }
2604                 }
2605
2606                 void error19 ()
2607                 {
2608                         Error (19, loc,
2609                                "Operator " + OperName () + " cannot be applied to operands of type `" +
2610                                TypeManager.CSharpName (left.Type) + "' and `" +
2611                                TypeManager.CSharpName (right.Type) + "'");
2612                                                      
2613                 }
2614                 
2615                 Expression CheckShiftArguments (EmitContext ec)
2616                 {
2617                         Expression e;
2618                         Type l = left.Type;
2619                         Type r = right.Type;
2620
2621                         e = ForceConversion (ec, right, TypeManager.int32_type);
2622                         if (e == null){
2623                                 error19 ();
2624                                 return null;
2625                         }
2626                         right = e;
2627
2628                         if (((e = ConvertImplicit (ec, left, TypeManager.int32_type, loc)) != null) ||
2629                             ((e = ConvertImplicit (ec, left, TypeManager.uint32_type, loc)) != null) ||
2630                             ((e = ConvertImplicit (ec, left, TypeManager.int64_type, loc)) != null) ||
2631                             ((e = ConvertImplicit (ec, left, TypeManager.uint64_type, loc)) != null)){
2632                                 left = e;
2633                                 type = e.Type;
2634
2635                                 return this;
2636                         }
2637                         error19 ();
2638                         return null;
2639                 }
2640                 
2641                 Expression ResolveOperator (EmitContext ec)
2642                 {
2643                         Type l = left.Type;
2644                         Type r = right.Type;
2645
2646                         //
2647                         // Step 1: Perform Operator Overload location
2648                         //
2649                         Expression left_expr, right_expr;
2650                         
2651                         string op = "op_" + oper;
2652
2653                         left_expr = MemberLookup (ec, l, op, false, loc);
2654                         if (left_expr == null && l.BaseType != null)
2655                                 left_expr = MemberLookup (ec, l.BaseType, op, false, loc);
2656                         
2657                         right_expr = MemberLookup (ec, r, op, false, loc);
2658                         if (right_expr == null && r.BaseType != null)
2659                                 right_expr = MemberLookup (ec, r.BaseType, op, false, loc);
2660                         
2661                         MethodGroupExpr union = Invocation.MakeUnionSet (left_expr, right_expr);
2662                         
2663                         if (union != null) {
2664                                 Arguments = new ArrayList ();
2665                                 Arguments.Add (new Argument (left, Argument.AType.Expression));
2666                                 Arguments.Add (new Argument (right, Argument.AType.Expression));
2667                                 
2668                                 method = Invocation.OverloadResolve (ec, union, Arguments, loc);
2669                                 if (method != null) {
2670                                         MethodInfo mi = (MethodInfo) method;
2671                                         type = mi.ReturnType;
2672                                         return this;
2673                                 } else {
2674                                         error19 ();
2675                                         return null;
2676                                 }
2677                         }       
2678
2679                         //
2680                         // Step 2: Default operations on CLI native types.
2681                         //
2682                         
2683                         // Only perform numeric promotions on:
2684                         // +, -, *, /, %, &, |, ^, ==, !=, <, >, <=, >=
2685                         //
2686                         if (oper == Operator.Addition){
2687                                 //
2688                                 // If any of the arguments is a string, cast to string
2689                                 //
2690                                 if (l == TypeManager.string_type){
2691                                         if (r == TypeManager.string_type){
2692                                                 // string + string
2693                                                 method = TypeManager.string_concat_string_string;
2694                                         } else {
2695                                                 // string + object
2696                                                 method = TypeManager.string_concat_object_object;
2697                                                 right = ConvertImplicit (ec, right,
2698                                                                          TypeManager.object_type, loc);
2699                                         }
2700                                         type = TypeManager.string_type;
2701
2702                                         Arguments = new ArrayList ();
2703                                         Arguments.Add (new Argument (left, Argument.AType.Expression));
2704                                         Arguments.Add (new Argument (right, Argument.AType.Expression));
2705
2706                                         return this;
2707                                         
2708                                 } else if (r == TypeManager.string_type){
2709                                         // object + string
2710                                         method = TypeManager.string_concat_object_object;
2711                                         Arguments = new ArrayList ();
2712                                         Arguments.Add (new Argument (left, Argument.AType.Expression));
2713                                         Arguments.Add (new Argument (right, Argument.AType.Expression));
2714
2715                                         left = ConvertImplicit (ec, left, TypeManager.object_type, loc);
2716                                         type = TypeManager.string_type;
2717
2718                                         return this;
2719                                 }
2720
2721                                 //
2722                                 // FIXME: is Delegate operator + (D x, D y) handled?
2723                                 //
2724                         }
2725                         
2726                         if (oper == Operator.LeftShift || oper == Operator.RightShift)
2727                                 return CheckShiftArguments (ec);
2728
2729                         if (oper == Operator.LogicalOr || oper == Operator.LogicalAnd){
2730                                 if (l != TypeManager.bool_type || r != TypeManager.bool_type)
2731                                         error19 ();
2732
2733                                 type = TypeManager.bool_type;
2734                                 return this;
2735                         } 
2736
2737                         //
2738                         // We are dealing with numbers
2739                         //
2740
2741                         DoNumericPromotions (ec, l, r);
2742
2743                         if (left == null || right == null)
2744                                 return null;
2745
2746                         
2747                         if (oper == Operator.BitwiseAnd ||
2748                             oper == Operator.BitwiseOr ||
2749                             oper == Operator.ExclusiveOr){
2750                                 if (!((l == TypeManager.int32_type) ||
2751                                       (l == TypeManager.uint32_type) ||
2752                                       (l == TypeManager.int64_type) ||
2753                                       (l == TypeManager.uint64_type))){
2754                                         error19 ();
2755                                         return null;
2756                                 }
2757                                 type = l;
2758                         }
2759
2760                         if (oper == Operator.Equality ||
2761                             oper == Operator.Inequality ||
2762                             oper == Operator.LessThanOrEqual ||
2763                             oper == Operator.LessThan ||
2764                             oper == Operator.GreaterThanOrEqual ||
2765                             oper == Operator.GreaterThan){
2766                                 type = TypeManager.bool_type;
2767                         }
2768
2769                         return this;
2770                 }
2771                 
2772                 public override Expression DoResolve (EmitContext ec)
2773                 {
2774                         left = left.Resolve (ec);
2775                         right = right.Resolve (ec);
2776
2777                         if (left == null || right == null)
2778                                 return null;
2779
2780                         if (left.Type == null)
2781                                 throw new Exception (
2782                                         "Resolve returned non null, but did not set the type! (" +
2783                                         left + ")");
2784                         if (right.Type == null)
2785                                 throw new Exception (
2786                                         "Resolve returned non null, but did not set the type! (" +
2787                                         right + ")");
2788
2789                         eclass = ExprClass.Value;
2790
2791                         return ResolveOperator (ec);
2792                 }
2793
2794                 public bool IsBranchable ()
2795                 {
2796                         if (oper == Operator.Equality ||
2797                             oper == Operator.Inequality ||
2798                             oper == Operator.LessThan ||
2799                             oper == Operator.GreaterThan ||
2800                             oper == Operator.LessThanOrEqual ||
2801                             oper == Operator.GreaterThanOrEqual){
2802                                 return true;
2803                         } else
2804                                 return false;
2805                 }
2806
2807                 // <summary>
2808                 //   This entry point is used by routines that might want
2809                 //   to emit a brfalse/brtrue after an expression, and instead
2810                 //   they could use a more compact notation.
2811                 //
2812                 //   Typically the code would generate l.emit/r.emit, followed
2813                 //   by the comparission and then a brtrue/brfalse.  The comparissions
2814                 //   are sometimes inneficient (there are not as complete as the branches
2815                 //   look for the hacks in Emit using double ceqs).
2816                 //
2817                 //   So for those cases we provide EmitBranchable that can emit the
2818                 //   branch with the test
2819                 // </summary>
2820                 public void EmitBranchable (EmitContext ec, int target)
2821                 {
2822                         OpCode opcode;
2823                         bool close_target = false;
2824                         
2825                         left.Emit (ec);
2826                         right.Emit (ec);
2827                         
2828                         switch (oper){
2829                         case Operator.Equality:
2830                                 if (close_target)
2831                                         opcode = OpCodes.Beq_S;
2832                                 else
2833                                         opcode = OpCodes.Beq;
2834                                 break;
2835
2836                         case Operator.Inequality:
2837                                 if (close_target)
2838                                         opcode = OpCodes.Bne_Un_S;
2839                                 else
2840                                         opcode = OpCodes.Bne_Un;
2841                                 break;
2842
2843                         case Operator.LessThan:
2844                                 if (close_target)
2845                                         opcode = OpCodes.Blt_S;
2846                                 else
2847                                         opcode = OpCodes.Blt;
2848                                 break;
2849
2850                         case Operator.GreaterThan:
2851                                 if (close_target)
2852                                         opcode = OpCodes.Bgt_S;
2853                                 else
2854                                         opcode = OpCodes.Bgt;
2855                                 break;
2856
2857                         case Operator.LessThanOrEqual:
2858                                 if (close_target)
2859                                         opcode = OpCodes.Ble_S;
2860                                 else
2861                                         opcode = OpCodes.Ble;
2862                                 break;
2863
2864                         case Operator.GreaterThanOrEqual:
2865                                 if (close_target)
2866                                         opcode = OpCodes.Bge_S;
2867                                 else
2868                                         opcode = OpCodes.Ble;
2869                                 break;
2870
2871                         default:
2872                                 throw new Exception ("EmitBranchable called on non-EmitBranchable operator: "
2873                                                      + oper.ToString ());
2874                         }
2875
2876                         ec.ig.Emit (opcode, target);
2877                 }
2878                 
2879                 public override void Emit (EmitContext ec)
2880                 {
2881                         ILGenerator ig = ec.ig;
2882                         Type l = left.Type;
2883                         Type r = right.Type;
2884                         OpCode opcode;
2885
2886                         if (method != null) {
2887
2888                                 // Note that operators are static anyway
2889                                 
2890                                 if (Arguments != null) 
2891                                         Invocation.EmitArguments (ec, method, Arguments);
2892                                 
2893                                 if (method is MethodInfo)
2894                                         ig.Emit (OpCodes.Call, (MethodInfo) method);
2895                                 else
2896                                         ig.Emit (OpCodes.Call, (ConstructorInfo) method);
2897
2898                                 return;
2899                         }
2900                         
2901                         left.Emit (ec);
2902                         right.Emit (ec);
2903
2904                         switch (oper){
2905                         case Operator.Multiply:
2906                                 if (ec.CheckState){
2907                                         if (l == TypeManager.int32_type || l == TypeManager.int64_type)
2908                                                 opcode = OpCodes.Mul_Ovf;
2909                                         else if (l==TypeManager.uint32_type || l==TypeManager.uint64_type)
2910                                                 opcode = OpCodes.Mul_Ovf_Un;
2911                                         else
2912                                                 opcode = OpCodes.Mul;
2913                                 } else
2914                                         opcode = OpCodes.Mul;
2915
2916                                 break;
2917
2918                         case Operator.Division:
2919                                 if (l == TypeManager.uint32_type || l == TypeManager.uint64_type)
2920                                         opcode = OpCodes.Div_Un;
2921                                 else
2922                                         opcode = OpCodes.Div;
2923                                 break;
2924
2925                         case Operator.Modulus:
2926                                 if (l == TypeManager.uint32_type || l == TypeManager.uint64_type)
2927                                         opcode = OpCodes.Rem_Un;
2928                                 else
2929                                         opcode = OpCodes.Rem;
2930                                 break;
2931
2932                         case Operator.Addition:
2933                                 if (ec.CheckState){
2934                                         if (l == TypeManager.int32_type || l == TypeManager.int64_type)
2935                                                 opcode = OpCodes.Add_Ovf;
2936                                         else if (l==TypeManager.uint32_type || l==TypeManager.uint64_type)
2937                                                 opcode = OpCodes.Add_Ovf_Un;
2938                                         else
2939                                                 opcode = OpCodes.Mul;
2940                                 } else
2941                                         opcode = OpCodes.Add;
2942                                 break;
2943
2944                         case Operator.Subtraction:
2945                                 if (ec.CheckState){
2946                                         if (l == TypeManager.int32_type || l == TypeManager.int64_type)
2947                                                 opcode = OpCodes.Sub_Ovf;
2948                                         else if (l==TypeManager.uint32_type || l==TypeManager.uint64_type)
2949                                                 opcode = OpCodes.Sub_Ovf_Un;
2950                                         else
2951                                                 opcode = OpCodes.Sub;
2952                                 } else
2953                                         opcode = OpCodes.Sub;
2954                                 break;
2955
2956                         case Operator.RightShift:
2957                                 opcode = OpCodes.Shr;
2958                                 break;
2959                                 
2960                         case Operator.LeftShift:
2961                                 opcode = OpCodes.Shl;
2962                                 break;
2963
2964                         case Operator.Equality:
2965                                 opcode = OpCodes.Ceq;
2966                                 break;
2967
2968                         case Operator.Inequality:
2969                                 ec.ig.Emit (OpCodes.Ceq);
2970                                 ec.ig.Emit (OpCodes.Ldc_I4_0);
2971                                 
2972                                 opcode = OpCodes.Ceq;
2973                                 break;
2974
2975                         case Operator.LessThan:
2976                                 opcode = OpCodes.Clt;
2977                                 break;
2978
2979                         case Operator.GreaterThan:
2980                                 opcode = OpCodes.Cgt;
2981                                 break;
2982
2983                         case Operator.LessThanOrEqual:
2984                                 ec.ig.Emit (OpCodes.Cgt);
2985                                 ec.ig.Emit (OpCodes.Ldc_I4_0);
2986                                 
2987                                 opcode = OpCodes.Ceq;
2988                                 break;
2989
2990                         case Operator.GreaterThanOrEqual:
2991                                 ec.ig.Emit (OpCodes.Clt);
2992                                 ec.ig.Emit (OpCodes.Ldc_I4_1);
2993                                 
2994                                 opcode = OpCodes.Sub;
2995                                 break;
2996
2997                         case Operator.LogicalOr:
2998                         case Operator.BitwiseOr:
2999                                 opcode = OpCodes.Or;
3000                                 break;
3001
3002                         case Operator.LogicalAnd:
3003                         case Operator.BitwiseAnd:
3004                                 opcode = OpCodes.And;
3005                                 break;
3006
3007                         case Operator.ExclusiveOr:
3008                                 opcode = OpCodes.Xor;
3009                                 break;
3010
3011                         default:
3012                                 throw new Exception ("This should not happen: Operator = "
3013                                                      + oper.ToString ());
3014                         }
3015
3016                         ig.Emit (opcode);
3017                 }
3018         }
3019
3020         public class Conditional : Expression {
3021                 Expression expr, trueExpr, falseExpr;
3022                 Location loc;
3023                 
3024                 public Conditional (Expression expr, Expression trueExpr, Expression falseExpr, Location l)
3025                 {
3026                         this.expr = expr;
3027                         this.trueExpr = trueExpr;
3028                         this.falseExpr = falseExpr;
3029                         this.loc = l;
3030                 }
3031
3032                 public Expression Expr {
3033                         get {
3034                                 return expr;
3035                         }
3036                 }
3037
3038                 public Expression TrueExpr {
3039                         get {
3040                                 return trueExpr;
3041                         }
3042                 }
3043
3044                 public Expression FalseExpr {
3045                         get {
3046                                 return falseExpr;
3047                         }
3048                 }
3049
3050                 public override Expression DoResolve (EmitContext ec)
3051                 {
3052                         expr = expr.Resolve (ec);
3053
3054                         if (expr.Type != TypeManager.bool_type)
3055                                 expr = Expression.ConvertImplicitRequired (
3056                                         ec, expr, TypeManager.bool_type, loc);
3057                         
3058                         trueExpr = trueExpr.Resolve (ec);
3059                         falseExpr = falseExpr.Resolve (ec);
3060
3061                         if (expr == null || trueExpr == null || falseExpr == null)
3062                                 return null;
3063                         
3064                         if (trueExpr.Type == falseExpr.Type)
3065                                 type = trueExpr.Type;
3066                         else {
3067                                 Expression conv;
3068
3069                                 //
3070                                 // First, if an implicit conversion exists from trueExpr
3071                                 // to falseExpr, then the result type is of type falseExpr.Type
3072                                 //
3073                                 conv = ConvertImplicit (ec, trueExpr, falseExpr.Type, loc);
3074                                 if (conv != null){
3075                                         type = falseExpr.Type;
3076                                         trueExpr = conv;
3077                                 } else if ((conv = ConvertImplicit(ec, falseExpr,trueExpr.Type,loc))!= null){
3078                                         type = trueExpr.Type;
3079                                         falseExpr = conv;
3080                                 } else {
3081                                         Error (173, loc, "The type of the conditional expression can " +
3082                                                "not be computed because there is no implicit conversion" +
3083                                                " from `" + TypeManager.CSharpName (trueExpr.Type) + "'" +
3084                                                " and `" + TypeManager.CSharpName (falseExpr.Type) + "'");
3085                                         return null;
3086                                 }
3087                         }
3088
3089                         eclass = ExprClass.Value;
3090                         return this;
3091                 }
3092
3093                 public override void Emit (EmitContext ec)
3094                 {
3095                         ILGenerator ig = ec.ig;
3096                         Label false_target = ig.DefineLabel ();
3097                         Label end_target = ig.DefineLabel ();
3098
3099                         expr.Emit (ec);
3100                         ig.Emit (OpCodes.Brfalse, false_target);
3101                         trueExpr.Emit (ec);
3102                         ig.Emit (OpCodes.Br, end_target);
3103                         ig.MarkLabel (false_target);
3104                         falseExpr.Emit (ec);
3105                         ig.MarkLabel (end_target);
3106                 }
3107         }
3108
3109         //
3110         // SimpleName expressions are initially formed of a single
3111         // word and it only happens at the beginning of the expression.
3112         //
3113         // The expression will try to be bound to a Field, a Method
3114         // group or a Property.  If those fail we pass the name to our
3115         // caller and the SimpleName is compounded to perform a type
3116         // lookup.  The idea behind this process is that we want to avoid
3117         // creating a namespace map from the assemblies, as that requires
3118         // the GetExportedTypes function to be called and a hashtable to
3119         // be constructed which reduces startup time.  If later we find
3120         // that this is slower, we should create a `NamespaceExpr' expression
3121         // that fully participates in the resolution process. 
3122         //
3123         // For example `System.Console.WriteLine' is decomposed into
3124         // MemberAccess (MemberAccess (SimpleName ("System"), "Console"), "WriteLine")
3125         //
3126         // The first SimpleName wont produce a match on its own, so it will
3127         // be turned into:
3128         // MemberAccess (SimpleName ("System.Console"), "WriteLine").
3129         //
3130         // System.Console will produce a TypeExpr match.
3131         //
3132         // The downside of this is that we might be hitting `LookupType' too many
3133         // times with this scheme.
3134         //
3135         public class SimpleName : Expression {
3136                 public readonly string Name;
3137                 public readonly Location Location;
3138                 
3139                 public SimpleName (string name, Location l)
3140                 {
3141                         Name = name;
3142                         Location = l;
3143                 }
3144
3145                 public static void Error120 (Location l, string name)
3146                 {
3147                         Report.Error (
3148                                 120, l,
3149                                 "An object reference is required " +
3150                                 "for the non-static field `"+name+"'");
3151                 }
3152                 
3153                 //
3154                 // Checks whether we are trying to access an instance
3155                 // property, method or field from a static body.
3156                 //
3157                 Expression MemberStaticCheck (Expression e)
3158                 {
3159                         if (e is FieldExpr){
3160                                 FieldInfo fi = ((FieldExpr) e).FieldInfo;
3161                                 
3162                                 if (!fi.IsStatic){
3163                                         Error120 (Location, Name);
3164                                         return null;
3165                                 }
3166                         } else if (e is MethodGroupExpr){
3167                                 MethodGroupExpr mg = (MethodGroupExpr) e;
3168
3169                                 if (!mg.RemoveInstanceMethods ()){
3170                                         Error120 (Location, mg.Methods [0].Name);
3171                                         return null;
3172                                 }
3173                                 return e;
3174                         } else if (e is PropertyExpr){
3175                                 if (!((PropertyExpr) e).IsStatic){
3176                                         Error120 (Location, Name);
3177                                         return null;
3178                                 }
3179                         }
3180
3181                         return e;
3182                 }
3183                 
3184                 //
3185                 // 7.5.2: Simple Names. 
3186                 //
3187                 // Local Variables and Parameters are handled at
3188                 // parse time, so they never occur as SimpleNames.
3189                 //
3190                 public override Expression DoResolve (EmitContext ec)
3191                 {
3192                         Expression e;
3193
3194                         //
3195                         // Stage 1: Performed by the parser (binding to local or parameters).
3196                         //
3197
3198                         //
3199                         // Stage 2: Lookup members
3200                         //
3201                         e = MemberLookup (ec, ec.TypeContainer.TypeBuilder, Name, true, Location);
3202                         if (e == null){
3203                                 //
3204                                 // Stage 3: Lookup symbol in the various namespaces. 
3205                                 // 
3206                                 Type t;
3207                                 
3208                                 if ((t = ec.TypeContainer.LookupType (Name, true)) != null)
3209                                         return new TypeExpr (t);
3210
3211                                 //
3212                                 // Stage 3 part b: Lookup up if we are an alias to a type
3213                                 // or a namespace.
3214                                 //
3215                                 // Since we are cheating: we only do the Alias lookup for
3216                                 // namespaces if the name does not include any dots in it
3217                                 //
3218                                 
3219                                 // IMPLEMENT ME.  Read mcs/mcs/TODO for ideas, or rewrite
3220                                 // using NamespaceExprs (dunno how that fixes the alias
3221                                 // per-file though).
3222                                 
3223                                 // No match, maybe our parent can compose us
3224                                 // into something meaningful.
3225                                 //
3226                                 return this;
3227                         }
3228
3229                         // Step 2, continues here.
3230                         if (e is TypeExpr)
3231                                 return e;
3232
3233                         if (e is FieldExpr){
3234                                 FieldExpr fe = (FieldExpr) e;
3235                                 
3236                                 if (!fe.FieldInfo.IsStatic)
3237                                         fe.InstanceExpression = new This (Location.Null);
3238                         }                               
3239
3240                         if (ec.IsStatic)
3241                                 return MemberStaticCheck (e);
3242                         else
3243                                 return e;
3244                 }
3245
3246                 public override void Emit (EmitContext ec)
3247                 {
3248                         //
3249                         // If this is ever reached, then we failed to
3250                         // find the name as a namespace
3251                         //
3252
3253                         Error (103, Location, "The name `" + Name +
3254                                "' does not exist in the class `" +
3255                                ec.TypeContainer.Name + "'");
3256                 }
3257         }
3258
3259         public class LocalTemporary : Expression, IStackStore, IMemoryLocation {
3260                 LocalBuilder builder;
3261                 
3262                 public LocalTemporary (EmitContext ec, Type t)
3263                 {
3264                         type = t;
3265                         eclass = ExprClass.Value;
3266                         builder = ec.GetTemporaryStorage (t);
3267                 }
3268
3269                 public override Expression DoResolve (EmitContext ec)
3270                 {
3271                         return this;
3272                 }
3273
3274                 public override void Emit (EmitContext ec)
3275                 {
3276                         ec.ig.Emit (OpCodes.Ldloc, builder); 
3277                 }
3278
3279                 public void Store (EmitContext ec)
3280                 {
3281                         ec.ig.Emit (OpCodes.Stloc, builder);
3282                 }
3283
3284                 public void AddressOf (EmitContext ec)
3285                 {
3286                         ec.ig.Emit (OpCodes.Ldloca, builder);
3287                 }
3288         }
3289         
3290         public class LocalVariableReference : Expression, IStackStore, IMemoryLocation {
3291                 public readonly string Name;
3292                 public readonly Block Block;
3293
3294                 VariableInfo variable_info;
3295                 
3296                 public LocalVariableReference (Block block, string name)
3297                 {
3298                         Block = block;
3299                         Name = name;
3300                         eclass = ExprClass.Variable;
3301                 }
3302
3303                 public VariableInfo VariableInfo {
3304                         get {
3305                                 if (variable_info == null)
3306                                         variable_info = Block.GetVariableInfo (Name);
3307                                 return variable_info;
3308                         }
3309                 }
3310                 
3311                 public override Expression DoResolve (EmitContext ec)
3312                 {
3313                         VariableInfo vi = VariableInfo;
3314
3315                         type = vi.VariableType;
3316                         return this;
3317                 }
3318
3319                 public override void Emit (EmitContext ec)
3320                 {
3321                         VariableInfo vi = VariableInfo;
3322                         ILGenerator ig = ec.ig;
3323                         int idx = vi.Idx;
3324
3325                         vi.Used = true;
3326                         
3327                         switch (idx){
3328                         case 0:
3329                                 ig.Emit (OpCodes.Ldloc_0);
3330                                 break;
3331                                 
3332                         case 1:
3333                                 ig.Emit (OpCodes.Ldloc_1);
3334                                 break;
3335
3336                         case 2:
3337                                 ig.Emit (OpCodes.Ldloc_2);
3338                                 break;
3339
3340                         case 3:
3341                                 ig.Emit (OpCodes.Ldloc_3);
3342                                 break;
3343
3344                         default:
3345                                 if (idx <= 255)
3346                                         ig.Emit (OpCodes.Ldloc_S, (byte) idx);
3347                                 else
3348                                         ig.Emit (OpCodes.Ldloc, idx);
3349                                 break;
3350                         }
3351                 }
3352
3353                 public static void Store (ILGenerator ig, int idx)
3354                 {
3355                         switch (idx){
3356                         case 0:
3357                                 ig.Emit (OpCodes.Stloc_0);
3358                                 break;
3359                                 
3360                         case 1:
3361                                 ig.Emit (OpCodes.Stloc_1);
3362                                 break;
3363                                 
3364                         case 2:
3365                                 ig.Emit (OpCodes.Stloc_2);
3366                                 break;
3367                                 
3368                         case 3:
3369                                 ig.Emit (OpCodes.Stloc_3);
3370                                 break;
3371                                 
3372                         default:
3373                                 if (idx <= 255)
3374                                         ig.Emit (OpCodes.Stloc_S, (byte) idx);
3375                                 else
3376                                         ig.Emit (OpCodes.Stloc, idx);
3377                                 break;
3378                         }
3379                 }
3380                 
3381                 public void Store (EmitContext ec)
3382                 {
3383                         ILGenerator ig = ec.ig;
3384                         VariableInfo vi = VariableInfo;
3385
3386                         vi.Assigned = true;
3387
3388                         // Funny seems the above generates optimal code for us, but
3389                         // seems to take too long to generate what we need.
3390                         // ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3391
3392                         Store (ig, vi.Idx);
3393                 }
3394
3395                 public void AddressOf (EmitContext ec)
3396                 {
3397                         VariableInfo vi = VariableInfo;
3398                         int idx = vi.Idx;
3399
3400                         vi.Used = true;
3401                         vi.Assigned = true;
3402                         
3403                         if (idx <= 255)
3404                                 ec.ig.Emit (OpCodes.Ldloca_S, (byte) idx);
3405                         else
3406                                 ec.ig.Emit (OpCodes.Ldloca, idx);
3407                 }
3408         }
3409
3410         public class ParameterReference : Expression, IStackStore, IMemoryLocation {
3411                 public readonly Parameters Pars;
3412                 public readonly String Name;
3413                 public readonly int Idx;
3414                 int arg_idx;
3415                 
3416                 public ParameterReference (Parameters pars, int idx, string name)
3417                 {
3418                         Pars = pars;
3419                         Idx  = idx;
3420                         Name = name;
3421                         eclass = ExprClass.Variable;
3422                 }
3423
3424                 public override Expression DoResolve (EmitContext ec)
3425                 {
3426                         Type [] types = Pars.GetParameterInfo (ec.TypeContainer);
3427
3428                         type = types [Idx];
3429
3430                         arg_idx = Idx;
3431                         if (!ec.IsStatic)
3432                                 arg_idx++;
3433                         
3434                         return this;
3435                 }
3436
3437                 public override void Emit (EmitContext ec)
3438                 {
3439                         if (arg_idx <= 255)
3440                                 ec.ig.Emit (OpCodes.Ldarg_S, (byte) arg_idx);
3441                         else
3442                                 ec.ig.Emit (OpCodes.Ldarg, arg_idx);
3443                 }
3444
3445                 public void Store (EmitContext ec)
3446                 {
3447                         if (arg_idx <= 255)
3448                                 ec.ig.Emit (OpCodes.Starg_S, (byte) arg_idx);
3449                         else
3450                                 ec.ig.Emit (OpCodes.Starg, arg_idx);
3451                         
3452                 }
3453
3454                 public void AddressOf (EmitContext ec)
3455                 {
3456                         if (arg_idx <= 255)
3457                                 ec.ig.Emit (OpCodes.Ldarga_S, (byte) arg_idx);
3458                         else
3459                                 ec.ig.Emit (OpCodes.Ldarga, arg_idx);
3460                 }
3461         }
3462         
3463         // <summary>
3464         //   Used for arguments to New(), Invocation()
3465         // </summary>
3466         public class Argument {
3467                 public enum AType {
3468                         Expression,
3469                         Ref,
3470                         Out
3471                 };
3472
3473                 public readonly AType Type;
3474                 public Expression expr;
3475
3476                 public Argument (Expression expr, AType type)
3477                 {
3478                         this.expr = expr;
3479                         this.Type = type;
3480                 }
3481
3482                 public Expression Expr {
3483                         get {
3484                                 return expr;
3485                         }
3486
3487                         set {
3488                                 expr = value;
3489                         }
3490                 }
3491
3492                 public bool Resolve (EmitContext ec)
3493                 {
3494                         expr = expr.Resolve (ec);
3495
3496                         return expr != null;
3497                 }
3498
3499                 public void Emit (EmitContext ec)
3500                 {
3501                         expr.Emit (ec);
3502                 }
3503         }
3504
3505         // <summary>
3506         //   Invocation of methods or delegates.
3507         // </summary>
3508         public class Invocation : ExpressionStatement {
3509                 public readonly ArrayList Arguments;
3510                 public readonly Location Location;
3511
3512                 Expression expr;
3513                 MethodBase method = null;
3514                         
3515                 static Hashtable method_parameter_cache;
3516
3517                 static Invocation ()
3518                 {
3519                         method_parameter_cache = new Hashtable ();
3520                 }
3521                         
3522                 //
3523                 // arguments is an ArrayList, but we do not want to typecast,
3524                 // as it might be null.
3525                 //
3526                 // FIXME: only allow expr to be a method invocation or a
3527                 // delegate invocation (7.5.5)
3528                 //
3529                 public Invocation (Expression expr, ArrayList arguments, Location l)
3530                 {
3531                         this.expr = expr;
3532                         Arguments = arguments;
3533                         Location = l;
3534                 }
3535
3536                 public Expression Expr {
3537                         get {
3538                                 return expr;
3539                         }
3540                 }
3541
3542                 // <summary>
3543                 //   Returns the Parameters (a ParameterData interface) for the
3544                 //   Method `mb'
3545                 // </summary>
3546                 public static ParameterData GetParameterData (MethodBase mb)
3547                 {
3548                         object pd = method_parameter_cache [mb];
3549
3550                         if (pd != null)
3551                                 return (ParameterData) pd;
3552
3553                         if (mb is MethodBuilder || mb is ConstructorBuilder){
3554                                 MethodCore mc = TypeContainer.LookupMethodByBuilder (mb);
3555
3556                                 InternalParameters ip = mc.ParameterInfo;
3557                                 method_parameter_cache [mb] = ip;
3558
3559                                 return (ParameterData) ip;
3560                         } else {
3561                                 ParameterInfo [] pi = mb.GetParameters ();
3562                                 ReflectionParameters rp = new ReflectionParameters (pi);
3563                                 method_parameter_cache [mb] = rp;
3564
3565                                 return (ParameterData) rp;
3566                         }
3567                 }
3568
3569                 // <summary>
3570                 //   Tells whether a user defined conversion from Type `from' to
3571                 //   Type `to' exists.
3572                 //
3573                 //   FIXME: we could implement a cache here. 
3574                 // </summary>
3575                 static bool ConversionExists (EmitContext ec, Type from, Type to, Location loc)
3576                 {
3577                         // Locate user-defined implicit operators
3578
3579                         Expression mg;
3580                         
3581                         mg = MemberLookup (ec, to, "op_Implicit", false, loc);
3582
3583                         if (mg != null) {
3584                                 MethodGroupExpr me = (MethodGroupExpr) mg;
3585                                 
3586                                 for (int i = me.Methods.Length; i > 0;) {
3587                                         i--;
3588                                         MethodBase mb = me.Methods [i];
3589                                         ParameterData pd = GetParameterData (mb);
3590                                         
3591                                         if (from == pd.ParameterType (0))
3592                                                 return true;
3593                                 }
3594                         }
3595
3596                         mg = MemberLookup (ec, from, "op_Implicit", false, loc);
3597
3598                         if (mg != null) {
3599                                 MethodGroupExpr me = (MethodGroupExpr) mg;
3600
3601                                 for (int i = me.Methods.Length; i > 0;) {
3602                                         i--;
3603                                         MethodBase mb = me.Methods [i];
3604                                         MethodInfo mi = (MethodInfo) mb;
3605                                         
3606                                         if (mi.ReturnType == to)
3607                                                 return true;
3608                                 }
3609                         }
3610                         
3611                         return false;
3612                 }
3613                 
3614                 // <summary>
3615                 //  Determines "better conversion" as specified in 7.4.2.3
3616                 //  Returns : 1 if a->p is better
3617                 //            0 if a->q or neither is better 
3618                 // </summary>
3619                 static int BetterConversion (EmitContext ec, Argument a, Type p, Type q, bool use_standard,
3620                                              Location loc)
3621                 {
3622                         Type argument_type = a.Expr.Type;
3623                         Expression argument_expr = a.Expr;
3624
3625                         if (argument_type == null)
3626                                 throw new Exception ("Expression of type " + a.Expr + " does not resolve its type");
3627
3628                         if (p == q)
3629                                 return 0;
3630                         
3631                         if (argument_type == p)
3632                                 return 1;
3633
3634                         if (argument_type == q)
3635                                 return 0;
3636
3637                         //
3638                         // Now probe whether an implicit constant expression conversion
3639                         // can be used.
3640                         //
3641                         // An implicit constant expression conversion permits the following
3642                         // conversions:
3643                         //
3644                         //    * A constant-expression of type `int' can be converted to type
3645                         //      sbyte, byute, short, ushort, uint, ulong provided the value of
3646                         //      of the expression is withing the range of the destination type.
3647                         //
3648                         //    * A constant-expression of type long can be converted to type
3649                         //      ulong, provided the value of the constant expression is not negative
3650                         //
3651                         // FIXME: Note that this assumes that constant folding has
3652                         // taken place.  We dont do constant folding yet.
3653                         //
3654
3655                         if (argument_expr is IntLiteral){
3656                                 IntLiteral ei = (IntLiteral) argument_expr;
3657                                 int value = ei.Value;
3658                                 
3659                                 if (p == TypeManager.sbyte_type){
3660                                         if (value >= SByte.MinValue && value <= SByte.MaxValue)
3661                                                 return 1;
3662                                 } else if (p == TypeManager.byte_type){
3663                                         if (Byte.MinValue >= 0 && value <= Byte.MaxValue)
3664                                                 return 1;
3665                                 } else if (p == TypeManager.short_type){
3666                                         if (value >= Int16.MinValue && value <= Int16.MaxValue)
3667                                                 return 1;
3668                                 } else if (p == TypeManager.ushort_type){
3669                                         if (value >= UInt16.MinValue && value <= UInt16.MaxValue)
3670                                                 return 1;
3671                                 } else if (p == TypeManager.uint32_type){
3672                                         //
3673                                         // we can optimize this case: a positive int32
3674                                         // always fits on a uint32
3675                                         //
3676                                         if (value >= 0)
3677                                                 return 1;
3678                                 } else if (p == TypeManager.uint64_type){
3679                                         //
3680                                         // we can optimize this case: a positive int32
3681                                         // always fits on a uint64
3682                                         //
3683                                         if (value >= 0)
3684                                                 return 1;
3685                                 }
3686                         } else if (argument_type == TypeManager.int64_type && argument_expr is LongLiteral){
3687                                 LongLiteral ll = (LongLiteral) argument_expr;
3688                                 
3689                                 if (p == TypeManager.uint64_type){
3690                                         if (ll.Value > 0)
3691                                                 return 1;
3692                                 }
3693                         }
3694
3695                         if (q == null) {
3696
3697                                 Expression tmp;
3698
3699                                 if (use_standard)
3700                                         tmp = ConvertImplicitStandard (ec, argument_expr, p, loc);
3701                                 else
3702                                         tmp = ConvertImplicit (ec, argument_expr, p, loc);
3703
3704                                 if (tmp != null)
3705                                         return 1;
3706                                 else
3707                                         return 0;
3708
3709                         }
3710
3711                         if (ConversionExists (ec, p, q, loc) == true &&
3712                             ConversionExists (ec, q, p, loc) == false)
3713                                 return 1;
3714
3715                         if (p == TypeManager.sbyte_type)
3716                                 if (q == TypeManager.byte_type || q == TypeManager.ushort_type ||
3717                                     q == TypeManager.uint32_type || q == TypeManager.uint64_type)
3718                                         return 1;
3719
3720                         if (p == TypeManager.short_type)
3721                                 if (q == TypeManager.ushort_type || q == TypeManager.uint32_type ||
3722                                     q == TypeManager.uint64_type)
3723                                         return 1;
3724
3725                         if (p == TypeManager.int32_type)
3726                                 if (q == TypeManager.uint32_type || q == TypeManager.uint64_type)
3727                                         return 1;
3728
3729                         if (p == TypeManager.int64_type)
3730                                 if (q == TypeManager.uint64_type)
3731                                         return 1;
3732
3733                         return 0;
3734                 }
3735                 
3736                 // <summary>
3737                 //  Determines "Better function" and returns an integer indicating :
3738                 //  0 if candidate ain't better
3739                 //  1 if candidate is better than the current best match
3740                 // </summary>
3741                 static int BetterFunction (EmitContext ec, ArrayList args,
3742                                            MethodBase candidate, MethodBase best,
3743                                            bool use_standard, Location loc)
3744                 {
3745                         ParameterData candidate_pd = GetParameterData (candidate);
3746                         ParameterData best_pd;
3747                         int argument_count;
3748
3749                         if (args == null)
3750                                 argument_count = 0;
3751                         else
3752                                 argument_count = args.Count;
3753
3754                         if (candidate_pd.Count == 0 && argument_count == 0)
3755                                 return 1;
3756
3757                         if (best == null) {
3758                                 if (candidate_pd.Count == argument_count) {
3759                                         int x = 0;
3760                                         for (int j = argument_count; j > 0;) {
3761                                                 j--;
3762                                                 
3763                                                 Argument a = (Argument) args [j];
3764                                                 
3765                                                 x = BetterConversion (
3766                                                         ec, a, candidate_pd.ParameterType (j), null,
3767                                                         use_standard, loc);
3768                                                 
3769                                                 if (x <= 0)
3770                                                         break;
3771                                         }
3772                                         
3773                                         if (x > 0)
3774                                                 return 1;
3775                                         else
3776                                                 return 0;
3777                                         
3778                                 } else
3779                                         return 0;
3780                         }
3781
3782                         best_pd = GetParameterData (best);
3783
3784                         if (candidate_pd.Count == argument_count && best_pd.Count == argument_count) {
3785                                 int rating1 = 0, rating2 = 0;
3786                                 
3787                                 for (int j = argument_count; j > 0;) {
3788                                         j--;
3789                                         int x, y;
3790                                         
3791                                         Argument a = (Argument) args [j];
3792
3793                                         x = BetterConversion (ec, a, candidate_pd.ParameterType (j),
3794                                                               best_pd.ParameterType (j), use_standard, loc);
3795                                         y = BetterConversion (ec, a, best_pd.ParameterType (j),
3796                                                               candidate_pd.ParameterType (j), use_standard,
3797                                                               loc);
3798                                         
3799                                         rating1 += x;
3800                                         rating2 += y;
3801                                 }
3802
3803                                 if (rating1 > rating2)
3804                                         return 1;
3805                                 else
3806                                         return 0;
3807                         } else
3808                                 return 0;
3809                         
3810                 }
3811
3812                 public static string FullMethodDesc (MethodBase mb)
3813                 {
3814                         StringBuilder sb = new StringBuilder (mb.Name);
3815                         ParameterData pd = GetParameterData (mb);
3816
3817                         int count = pd.Count;
3818                         sb.Append (" (");
3819                         
3820                         for (int i = count; i > 0; ) {
3821                                 i--;
3822                                 
3823                                 sb.Append (TypeManager.CSharpName (pd.ParameterType (count - i - 1)));
3824                                 if (i != 0)
3825                                         sb.Append (", ");
3826                         }
3827                         
3828                         sb.Append (")");
3829                         return sb.ToString ();
3830                 }
3831
3832                 public static MethodGroupExpr MakeUnionSet (Expression mg1, Expression mg2)
3833                 {
3834                         MemberInfo [] miset;
3835                         MethodGroupExpr union;
3836                         
3837                         if (mg1 != null && mg2 != null) {
3838                                 
3839                                 MethodGroupExpr left_set = null, right_set = null;
3840                                 int length1 = 0, length2 = 0;
3841                                 
3842                                 left_set = (MethodGroupExpr) mg1;
3843                                 length1 = left_set.Methods.Length;
3844                                 
3845                                 right_set = (MethodGroupExpr) mg2;
3846                                 length2 = right_set.Methods.Length;
3847
3848                                 ArrayList common = new ArrayList ();
3849                                 
3850                                 for (int i = 0; i < left_set.Methods.Length; i++) {
3851                                         for (int j = 0; j < right_set.Methods.Length; j++) {
3852                                                 if (left_set.Methods [i] == right_set.Methods [j]) 
3853                                                         common.Add (left_set.Methods [i]);
3854                                         }
3855                                 }
3856                                 
3857                                 miset = new MemberInfo [length1 + length2 - common.Count];
3858
3859                                 left_set.Methods.CopyTo (miset, 0);
3860
3861                                 int k = 0;
3862                                 
3863                                 for (int j = 0; j < right_set.Methods.Length; j++)
3864                                         if (!common.Contains (right_set.Methods [j]))
3865                                                 miset [length1 + k++] = right_set.Methods [j];
3866                                 
3867                                 union = new MethodGroupExpr (miset);
3868
3869                                 return union;
3870
3871                         } else if (mg1 == null && mg2 != null) {
3872                                 
3873                                 MethodGroupExpr me = (MethodGroupExpr) mg2; 
3874                                 
3875                                 miset = new MemberInfo [me.Methods.Length];
3876                                 me.Methods.CopyTo (miset, 0);
3877
3878                                 union = new MethodGroupExpr (miset);
3879                                 
3880                                 return union;
3881
3882                         } else if (mg2 == null && mg1 != null) {
3883                                 
3884                                 MethodGroupExpr me = (MethodGroupExpr) mg1; 
3885                                 
3886                                 miset = new MemberInfo [me.Methods.Length];
3887                                 me.Methods.CopyTo (miset, 0);
3888
3889                                 union = new MethodGroupExpr (miset);
3890                                 
3891                                 return union;
3892                         }
3893                         
3894                         return null;
3895                 }
3896
3897                 // <summary>
3898                 //   Find the Applicable Function Members (7.4.2.1)
3899                 //
3900                 //   me: Method Group expression with the members to select.
3901                 //       it might contain constructors or methods (or anything
3902                 //       that maps to a method).
3903                 //
3904                 //   Arguments: ArrayList containing resolved Argument objects.
3905                 //
3906                 //   loc: The location if we want an error to be reported, or a Null
3907                 //        location for "probing" purposes.
3908                 //
3909                 //   inside_user_defined: controls whether OverloadResolve should use the 
3910                 //   ConvertImplicit or ConvertImplicitStandard during overload resolution.
3911                 //
3912                 //   Returns: The MethodBase (either a ConstructorInfo or a MethodInfo)
3913                 //            that is the best match of me on Arguments.
3914                 //
3915                 // </summary>
3916                 public static MethodBase OverloadResolve (EmitContext ec, MethodGroupExpr me,
3917                                                           ArrayList Arguments, Location loc,
3918                                                           bool use_standard)
3919                 {
3920                         ArrayList afm = new ArrayList ();
3921                         int best_match_idx = -1;
3922                         MethodBase method = null;
3923                         int argument_count;
3924                         
3925                         for (int i = me.Methods.Length; i > 0; ){
3926                                 i--;
3927                                 MethodBase candidate  = me.Methods [i];
3928                                 int x;
3929
3930                                 x = BetterFunction (ec, Arguments, candidate, method, use_standard, loc);
3931                                 
3932                                 if (x == 0)
3933                                         continue;
3934                                 else {
3935                                         best_match_idx = i;
3936                                         method = me.Methods [best_match_idx];
3937                                 }
3938                         }
3939
3940                         if (Arguments == null)
3941                                 argument_count = 0;
3942                         else
3943                                 argument_count = Arguments.Count;
3944                         
3945                         ParameterData pd;
3946                         
3947                         // Now we see if we can at least find a method with the same number of arguments
3948                         // and then try doing implicit conversion on the arguments
3949                         if (best_match_idx == -1) {
3950                                 
3951                                 for (int i = me.Methods.Length; i > 0;) {
3952                                         i--;
3953                                         MethodBase mb = me.Methods [i];
3954                                         pd = GetParameterData (mb);
3955                                         
3956                                         if (pd.Count == argument_count) {
3957                                                 best_match_idx = i;
3958                                                 method = me.Methods [best_match_idx];
3959                                                 break;
3960                                         } else
3961                                                 continue;
3962                                 }
3963
3964                         }
3965
3966                         if (method == null)
3967                                 return null;
3968
3969                         // And now convert implicitly, each argument to the required type
3970                         
3971                         pd = GetParameterData (method);
3972
3973                         for (int j = argument_count; j > 0;) {
3974                                 j--;
3975                                 Argument a = (Argument) Arguments [j];
3976                                 Expression a_expr = a.Expr;
3977                                 Type parameter_type = pd.ParameterType (j);
3978                                 
3979                                 if (a_expr.Type != parameter_type){
3980                                         Expression conv;
3981
3982                                         if (use_standard)
3983                                                 conv = ConvertImplicitStandard (ec, a_expr, parameter_type,
3984                                                                                 Location.Null);
3985                                         else
3986                                                 conv = ConvertImplicit (ec, a_expr, parameter_type,
3987                                                                         Location.Null);
3988
3989                                         if (conv == null){
3990                                                 if (!Location.IsNull (loc)) {
3991                                                         Error (1502, loc,
3992                                                                "The best overloaded match for method '" + FullMethodDesc (method) +
3993                                                                "' has some invalid arguments");
3994                                                         Error (1503, loc,
3995                                                                "Argument " + (j+1) +
3996                                                                ": Cannot convert from '" + TypeManager.CSharpName (a_expr.Type)
3997                                                                + "' to '" + TypeManager.CSharpName (pd.ParameterType (j)) + "'");
3998                                                 }
3999                                                 return null;
4000                                         }
4001                                         //
4002                                         // Update the argument with the implicit conversion
4003                                         //
4004                                         if (a_expr != conv)
4005                                                 a.Expr = conv;
4006                                 }
4007                         }
4008                         
4009                         return method;
4010                 }
4011
4012                 public static MethodBase OverloadResolve (EmitContext ec, MethodGroupExpr me,
4013                                                           ArrayList Arguments, Location loc)
4014                 {
4015                         return OverloadResolve (ec, me, Arguments, loc, false);
4016                 }
4017                         
4018                 public override Expression DoResolve (EmitContext ec)
4019                 {
4020                         bool IsDelegate = false;
4021                         //
4022                         // First, resolve the expression that is used to
4023                         // trigger the invocation
4024                         //
4025                         this.expr = expr.Resolve (ec);
4026                         if (this.expr == null)
4027                                 return null;
4028
4029                         Type expr_type = null;
4030                         if (!(this.expr is MethodGroupExpr)) {
4031                                 expr_type = this.expr.Type;
4032                                 IsDelegate = TypeManager.IsDelegateType (expr_type);
4033                         }
4034                         
4035                         if (IsDelegate)
4036                                 return (new DelegateInvocation (this.expr, Arguments, Location)).Resolve (ec);
4037                         
4038                         
4039                         if (!(this.expr is MethodGroupExpr)){
4040                                 report118 (Location, this.expr, "method group");
4041                                 return null;
4042                         }
4043
4044                         //
4045                         // Next, evaluate all the expressions in the argument list
4046                         //
4047                         if (Arguments != null){
4048                                 for (int i = Arguments.Count; i > 0;){
4049                                         --i;
4050                                         Argument a = (Argument) Arguments [i];
4051
4052                                         if (!a.Resolve (ec))
4053                                                 return null;
4054                                 }
4055                         }
4056
4057                         method = OverloadResolve (ec, (MethodGroupExpr) this.expr, Arguments,
4058                                                   Location);
4059
4060                         if (method == null){
4061                                 Error (-6, Location,
4062                                        "Could not find any applicable function for this argument list");
4063                                 return null;
4064                         }
4065
4066                         if (method is MethodInfo)
4067                                 type = ((MethodInfo)method).ReturnType;
4068
4069                         eclass = ExprClass.Value;
4070                         return this;
4071                 }
4072
4073                 public static void EmitArguments (EmitContext ec, MethodBase method, ArrayList Arguments)
4074                 {
4075                         int top;
4076
4077                         if (Arguments != null)
4078                                 top = Arguments.Count;
4079                         else
4080                                 top = 0;
4081
4082                         for (int i = 0; i < top; i++){
4083                                 Argument a = (Argument) Arguments [i];
4084
4085                                 a.Emit (ec);
4086                         }
4087                 }
4088
4089                 public static void EmitCall (EmitContext ec,
4090                                              bool is_static, Expression instance_expr,
4091                                              MethodBase method, ArrayList Arguments)
4092                 {
4093                         ILGenerator ig = ec.ig;
4094                         bool struct_call = false;
4095                                 
4096                         if (!is_static){
4097                                 //
4098                                 // If this is ourselves, push "this"
4099                                 //
4100                                 if (instance_expr == null){
4101                                         ig.Emit (OpCodes.Ldarg_0);
4102                                 } else {
4103                                         //
4104                                         // Push the instance expression
4105                                         //
4106                                         if (instance_expr.Type.IsSubclassOf (TypeManager.value_type)){
4107
4108                                                 struct_call = true;
4109
4110                                                 //
4111                                                 // If the expression implements IMemoryLocation, then
4112                                                 // we can optimize and use AddressOf on the
4113                                                 // return.
4114                                                 //
4115                                                 // If not we have to use some temporary storage for
4116                                                 // it.
4117                                                 if (instance_expr is IMemoryLocation)
4118                                                         ((IMemoryLocation) instance_expr).AddressOf (ec);
4119                                                 else {
4120                                                         Type t = instance_expr.Type;
4121                                                         
4122                                                         instance_expr.Emit (ec);
4123                                                         LocalBuilder temp = ec.GetTemporaryStorage (t);
4124                                                         ig.Emit (OpCodes.Stloc, temp);
4125                                                         ig.Emit (OpCodes.Ldloca, temp);
4126                                                 }
4127                                         } else 
4128                                                 instance_expr.Emit (ec);
4129                                 }
4130                         }
4131
4132                         if (Arguments != null)
4133                                 EmitArguments (ec, method, Arguments);
4134
4135                         if (is_static || struct_call){
4136                                 if (method is MethodInfo)
4137                                         ig.Emit (OpCodes.Call, (MethodInfo) method);
4138                                 else
4139                                         ig.Emit (OpCodes.Call, (ConstructorInfo) method);
4140                         } else {
4141                                 if (method is MethodInfo)
4142                                         ig.Emit (OpCodes.Callvirt, (MethodInfo) method);
4143                                 else
4144                                         ig.Emit (OpCodes.Callvirt, (ConstructorInfo) method);
4145                         }
4146                 }
4147                 
4148                 public override void Emit (EmitContext ec)
4149                 {
4150                         MethodGroupExpr mg = (MethodGroupExpr) this.expr;
4151                         EmitCall (ec, method.IsStatic, mg.InstanceExpression, method, Arguments);
4152                 }
4153                 
4154                 public override void EmitStatement (EmitContext ec)
4155                 {
4156                         Emit (ec);
4157
4158                         // 
4159                         // Pop the return value if there is one
4160                         //
4161                         if (method is MethodInfo){
4162                                 if (((MethodInfo)method).ReturnType != TypeManager.void_type)
4163                                         ec.ig.Emit (OpCodes.Pop);
4164                         }
4165                 }
4166         }
4167
4168         public class New : ExpressionStatement {
4169
4170                 public enum NType {
4171                         Object,
4172                         Array
4173                 };
4174
4175                 public readonly NType     NewType;
4176                 public readonly ArrayList Arguments;
4177                 public readonly string    RequestedType;
4178
4179                 // These are for the case when we have an array
4180                 public readonly string    Rank;
4181                 public readonly ArrayList Initializers;
4182
4183                 Location Location;
4184                 MethodBase method = null;
4185
4186                 //
4187                 // If set, the new expression is for a value_target, and
4188                 // we will not leave anything on the stack.
4189                 //
4190                 Expression value_target;
4191                 
4192                 public New (string requested_type, ArrayList arguments, Location loc)
4193                 {
4194                         RequestedType = requested_type;
4195                         Arguments = arguments;
4196                         NewType = NType.Object;
4197                         Location = loc;
4198                 }
4199
4200                 public New (string requested_type, ArrayList exprs, string rank, ArrayList initializers, Location loc)
4201                 {
4202                         RequestedType = requested_type;
4203                         Rank          = rank;
4204                         Initializers  = initializers;
4205                         NewType       = NType.Array;
4206                         Location      = loc;
4207
4208                         Arguments = new ArrayList ();
4209
4210                         foreach (Expression e in exprs)
4211                                 Arguments.Add (new Argument (e, Argument.AType.Expression));
4212                         
4213                 }
4214
4215                 public static string FormLookupType (string base_type, int idx_count, string rank)
4216                 {
4217                         StringBuilder sb = new StringBuilder (base_type);
4218
4219                         sb.Append (rank);
4220
4221                         sb.Append ("[");
4222                         for (int i = 1; i < idx_count; i++)
4223                                 sb.Append (",");
4224                         sb.Append ("]");
4225                         
4226                         return sb.ToString ();
4227                 }
4228                 
4229                 public Expression ValueTypeVariable {
4230                         get {
4231                                 return value_target;
4232                         }
4233
4234                         set {
4235                                 value_target = value;
4236                         }
4237                 }
4238                 
4239                 public override Expression DoResolve (EmitContext ec)
4240                 {
4241                         if (NewType == NType.Object) {
4242
4243                                 type = ec.TypeContainer.LookupType (RequestedType, false);
4244                                 
4245                                 if (type == null)
4246                                         return null;
4247
4248                                 bool IsDelegate = TypeManager.IsDelegateType (type);
4249                                 
4250                                 if (IsDelegate)
4251                                         return (new NewDelegate (type, Arguments, Location)).Resolve (ec);
4252                                 
4253                                 Expression ml;
4254                                 
4255                                 ml = MemberLookup (ec, type, ".ctor", false,
4256                                                    MemberTypes.Constructor, AllBindingsFlags, Location);
4257                                 
4258                                 bool is_struct = false;
4259                                 is_struct = type.IsSubclassOf (TypeManager.value_type);
4260                                 
4261                                 if (! (ml is MethodGroupExpr)){
4262                                         if (!is_struct){
4263                                                 report118 (Location, ml, "method group");
4264                                                 return null;
4265                                         }
4266                                 }
4267                                 
4268                                 if (ml != null) {
4269                                         if (Arguments != null){
4270                                                 for (int i = Arguments.Count; i > 0;){
4271                                                         --i;
4272                                                         Argument a = (Argument) Arguments [i];
4273                                                         
4274                                                         if (!a.Resolve (ec))
4275                                                                 return null;
4276                                                 }
4277                                         }
4278                                         
4279                                         method = Invocation.OverloadResolve (ec, (MethodGroupExpr) ml,
4280                                                                              Arguments, Location);
4281                                 }
4282                                 
4283                                 
4284                                 if (method == null && !is_struct) {
4285                                         Error (-6, Location,
4286                                                "New invocation: Can not find a constructor for " +
4287                                                "this argument list");
4288                                         return null;
4289                                 }
4290                                 
4291                                 eclass = ExprClass.Value;
4292                                 return this;
4293                                 
4294                         }
4295                         
4296                         if (NewType == NType.Array) {
4297                                 throw new Exception ("Finish array creation");
4298                         }
4299                         
4300                         return null;
4301                 }
4302                 
4303                 //
4304                 // This DoEmit can be invoked in two contexts:
4305                 //    * As a mechanism that will leave a value on the stack (new object)
4306                 //    * As one that wont (init struct)
4307                 //
4308                 // You can control whether a value is required on the stack by passing
4309                 // need_value_on_stack.  The code *might* leave a value on the stack
4310                 // so it must be popped manually
4311                 //
4312                 // Returns whether a value is left on the stack
4313                 //
4314                 bool DoEmit (EmitContext ec, bool need_value_on_stack)
4315                 {
4316                         if (method == null){
4317                                 IMemoryLocation ml = (IMemoryLocation) value_target;
4318
4319                                 ml.AddressOf (ec);
4320                         } else {
4321                                 Invocation.EmitArguments (ec, method, Arguments);
4322                                 ec.ig.Emit (OpCodes.Newobj, (ConstructorInfo) method);
4323                                 return true;
4324                         }
4325
4326                         //
4327                         // It must be a value type, sanity check
4328                         //
4329                         if (value_target != null){
4330                                 ec.ig.Emit (OpCodes.Initobj, type);
4331
4332                                 if (need_value_on_stack){
4333                                         value_target.Emit (ec);
4334                                         return true;
4335                                 }
4336                                 return false;
4337                         }
4338
4339                         throw new Exception ("No method and no value type");
4340                 }
4341
4342                 public override void Emit (EmitContext ec)
4343                 {
4344                         DoEmit (ec, true);
4345                 }
4346                 
4347                 public override void EmitStatement (EmitContext ec)
4348                 {
4349                         if (DoEmit (ec, false))
4350                                 ec.ig.Emit (OpCodes.Pop);
4351                 }
4352         }
4353
4354         //
4355         // Represents the `this' construct
4356         //
4357         public class This : Expression, IStackStore, IMemoryLocation {
4358                 Location loc;
4359                 
4360                 public This (Location loc)
4361                 {
4362                         this.loc = loc;
4363                 }
4364
4365                 public override Expression DoResolve (EmitContext ec)
4366                 {
4367                         eclass = ExprClass.Variable;
4368                         type = ec.TypeContainer.TypeBuilder;
4369
4370                         if (ec.IsStatic){
4371                                 Report.Error (26, loc,
4372                                               "Keyword this not valid in static code");
4373                                 return null;
4374                         }
4375                         
4376                         return this;
4377                 }
4378
4379                 public Expression DoResolveLValue (EmitContext ec)
4380                 {
4381                         DoResolve (ec);
4382                         
4383                         if (ec.TypeContainer is Class){
4384                                 Report.Error (1604, loc, "Cannot assign to `this'");
4385                                 return null;
4386                         }
4387
4388                         return this;
4389                 }
4390
4391                 public override void Emit (EmitContext ec)
4392                 {
4393                         ec.ig.Emit (OpCodes.Ldarg_0);
4394                 }
4395
4396                 public void Store (EmitContext ec)
4397                 {
4398                         ec.ig.Emit (OpCodes.Starg, 0);
4399                 }
4400
4401                 public void AddressOf (EmitContext ec)
4402                 {
4403                         ec.ig.Emit (OpCodes.Ldarga_S, (byte) 0);
4404                 }
4405         }
4406
4407         // <summary>
4408         //   Implements the typeof operator
4409         // </summary>
4410         public class TypeOf : Expression {
4411                 public readonly string QueriedType;
4412                 Type typearg;
4413                 
4414                 public TypeOf (string queried_type)
4415                 {
4416                         QueriedType = queried_type;
4417                 }
4418
4419                 public override Expression DoResolve (EmitContext ec)
4420                 {
4421                         typearg = ec.TypeContainer.LookupType (QueriedType, false);
4422
4423                         if (typearg == null)
4424                                 return null;
4425
4426                         type = TypeManager.type_type;
4427                         eclass = ExprClass.Type;
4428                         return this;
4429                 }
4430
4431                 public override void Emit (EmitContext ec)
4432                 {
4433                         ec.ig.Emit (OpCodes.Ldtoken, typearg);
4434                         ec.ig.Emit (OpCodes.Call, TypeManager.system_type_get_type_from_handle);
4435                 }
4436         }
4437
4438         public class SizeOf : Expression {
4439                 public readonly string QueriedType;
4440                 
4441                 public SizeOf (string queried_type)
4442                 {
4443                         this.QueriedType = queried_type;
4444                 }
4445
4446                 public override Expression DoResolve (EmitContext ec)
4447                 {
4448                         // FIXME: Implement;
4449                         throw new Exception ("Unimplemented");
4450                         // return this;
4451                 }
4452
4453                 public override void Emit (EmitContext ec)
4454                 {
4455                         throw new Exception ("Implement me");
4456                 }
4457         }
4458
4459         public class MemberAccess : Expression {
4460                 public readonly string Identifier;
4461                 Expression expr;
4462                 Expression member_lookup;
4463                 Location loc;
4464                 
4465                 public MemberAccess (Expression expr, string id, Location l)
4466                 {
4467                         this.expr = expr;
4468                         Identifier = id;
4469                         loc = l;
4470                 }
4471
4472                 public Expression Expr {
4473                         get {
4474                                 return expr;
4475                         }
4476                 }
4477
4478                 void error176 (Location loc, string name)
4479                 {
4480                         Report.Error (176, loc, "Static member `" +
4481                                       name + "' cannot be accessed " +
4482                                       "with an instance reference, qualify with a " +
4483                                       "type name instead");
4484                 }
4485                 
4486                 public override Expression DoResolve (EmitContext ec)
4487                 {
4488                         expr = expr.Resolve (ec);
4489
4490                         if (expr == null)
4491                                 return null;
4492
4493                         if (expr is SimpleName){
4494                                 SimpleName child_expr = (SimpleName) expr;
4495                                 
4496                                 expr = new SimpleName (child_expr.Name + "." + Identifier, loc);
4497
4498                                 return expr.Resolve (ec);
4499                         }
4500                                         
4501                         member_lookup = MemberLookup (ec, expr.Type, Identifier, false, loc);
4502
4503                         //
4504                         // Method Groups
4505                         //
4506                         if (member_lookup is MethodGroupExpr){
4507                                 MethodGroupExpr mg = (MethodGroupExpr) member_lookup;
4508                                 
4509                                 //
4510                                 // Type.MethodGroup
4511                                 //
4512                                 if (expr is TypeExpr){
4513                                         if (!mg.RemoveInstanceMethods ()){
4514                                                 SimpleName.Error120 (loc, mg.Methods [0].Name); 
4515                                                 return null;
4516                                         }
4517
4518                                         return member_lookup;
4519                                 }
4520
4521                                 //
4522                                 // Instance.MethodGroup
4523                                 //
4524                                 if (!mg.RemoveStaticMethods ()){
4525                                         error176 (loc, mg.Methods [0].Name);
4526                                         return null;
4527                                 }
4528                                 
4529                                 mg.InstanceExpression = expr;
4530                                         
4531                                 return member_lookup;
4532                         }
4533
4534                         if (member_lookup is FieldExpr){
4535                                 FieldExpr fe = (FieldExpr) member_lookup;
4536
4537                                 if (expr is TypeExpr){
4538                                         if (!fe.FieldInfo.IsStatic){
4539                                                 error176 (loc, fe.FieldInfo.Name);
4540                                                 return null;
4541                                         }
4542                                         return member_lookup;
4543                                 } else {
4544                                         if (fe.FieldInfo.IsStatic){
4545                                                 error176 (loc, fe.FieldInfo.Name);
4546                                                 return null;
4547                                         }
4548                                         fe.InstanceExpression = expr;
4549
4550                                         return fe;
4551                                 }
4552                         }
4553
4554                         if (member_lookup is PropertyExpr){
4555                                 PropertyExpr pe = (PropertyExpr) member_lookup;
4556
4557                                 if (expr is TypeExpr){
4558                                         if (!pe.IsStatic){
4559                                                 SimpleName.Error120 (loc, pe.PropertyInfo.Name);
4560                                                 return null;
4561                                         }
4562                                         return pe;
4563                                 } else {
4564                                         if (pe.IsStatic){
4565                                                 error176 (loc, pe.PropertyInfo.Name);
4566                                                 return null;
4567                                         }
4568                                         pe.InstanceExpression = expr;
4569
4570                                         return pe;
4571                                 }
4572                         }
4573                         
4574                         Console.WriteLine ("Support for " + member_lookup + " is not present yet");
4575                         Environment.Exit (0);
4576                         return null;
4577                 }
4578
4579                 public override void Emit (EmitContext ec)
4580                 {
4581                         throw new Exception ("Should not happen I think");
4582                 }
4583
4584         }
4585
4586         // <summary>
4587         //   Fully resolved expression that evaluates to a type
4588         // </summary>
4589         public class TypeExpr : Expression {
4590                 public TypeExpr (Type t)
4591                 {
4592                         Type = t;
4593                         eclass = ExprClass.Type;
4594                 }
4595
4596                 override public Expression DoResolve (EmitContext ec)
4597                 {
4598                         return this;
4599                 }
4600
4601                 override public void Emit (EmitContext ec)
4602                 {
4603                         throw new Exception ("Implement me");
4604                 }
4605         }
4606
4607         // <summary>
4608         //   MethodGroup Expression.
4609         //  
4610         //   This is a fully resolved expression that evaluates to a type
4611         // </summary>
4612         public class MethodGroupExpr : Expression {
4613                 public MethodBase [] Methods;
4614                 Expression instance_expression = null;
4615                 
4616                 public MethodGroupExpr (MemberInfo [] mi)
4617                 {
4618                         Methods = new MethodBase [mi.Length];
4619                         mi.CopyTo (Methods, 0);
4620                         eclass = ExprClass.MethodGroup;
4621                 }
4622
4623                 public MethodGroupExpr (ArrayList l)
4624                 {
4625                         Methods = new MethodBase [l.Count];
4626
4627                         l.CopyTo (Methods, 0);
4628                         eclass = ExprClass.MethodGroup;
4629                 }
4630                 
4631                 //
4632                 // `A method group may have associated an instance expression' 
4633                 // 
4634                 public Expression InstanceExpression {
4635                         get {
4636                                 return instance_expression;
4637                         }
4638
4639                         set {
4640                                 instance_expression = value;
4641                         }
4642                 }
4643                 
4644                 override public Expression DoResolve (EmitContext ec)
4645                 {
4646                         return this;
4647                 }
4648
4649                 override public void Emit (EmitContext ec)
4650                 {
4651                         throw new Exception ("This should never be reached");
4652                 }
4653
4654                 bool RemoveMethods (bool keep_static)
4655                 {
4656                         ArrayList smethods = new ArrayList ();
4657                         int top = Methods.Length;
4658                         int i;
4659                         
4660                         for (i = 0; i < top; i++){
4661                                 MethodBase mb = Methods [i];
4662
4663                                 if (mb.IsStatic == keep_static)
4664                                         smethods.Add (mb);
4665                         }
4666
4667                         if (smethods.Count == 0)
4668                                 return false;
4669
4670                         Methods = new MethodBase [smethods.Count];
4671                         smethods.CopyTo (Methods, 0);
4672
4673                         return true;
4674                 }
4675                 
4676                 // <summary>
4677                 //   Removes any instance methods from the MethodGroup, returns
4678                 //   false if the resulting set is empty.
4679                 // </summary>
4680                 public bool RemoveInstanceMethods ()
4681                 {
4682                         return RemoveMethods (true);
4683                 }
4684
4685                 // <summary>
4686                 //   Removes any static methods from the MethodGroup, returns
4687                 //   false if the resulting set is empty.
4688                 // </summary>
4689                 public bool RemoveStaticMethods ()
4690                 {
4691                         return RemoveMethods (false);
4692                 }
4693         }
4694
4695         // <summary>
4696         //   Fully resolved expression that evaluates to a Field
4697         // </summary>
4698         public class FieldExpr : Expression, IStackStore, IMemoryLocation {
4699                 public readonly FieldInfo FieldInfo;
4700                 public Expression InstanceExpression;
4701                 Location loc;
4702                 
4703                 public FieldExpr (FieldInfo fi, Location l)
4704                 {
4705                         FieldInfo = fi;
4706                         eclass = ExprClass.Variable;
4707                         type = fi.FieldType;
4708                         loc = l;
4709                 }
4710
4711                 override public Expression DoResolve (EmitContext ec)
4712                 {
4713                         if (!FieldInfo.IsStatic){
4714                                 if (InstanceExpression == null){
4715                                         throw new Exception ("non-static FieldExpr without instance var\n" +
4716                                                              "You have to assign the Instance variable\n" +
4717                                                              "Of the FieldExpr to set this\n");
4718                                 }
4719
4720                                 InstanceExpression = InstanceExpression.Resolve (ec);
4721                                 if (InstanceExpression == null)
4722                                         return null;
4723                                 
4724                         }
4725                         return this;
4726                 }
4727
4728                 public Expression DoResolveLValue (EmitContext ec)
4729                 {
4730                         if (!FieldInfo.IsInitOnly)
4731                                 return this;
4732
4733                         //
4734                         // InitOnly fields can only be assigned in constructors
4735                         //
4736
4737                         if (ec.IsConstructor)
4738                                 return this;
4739
4740                         Report.Error (191, loc,
4741                                       "Readonly field can not be assigned outside " +
4742                                       "of constructor or variable initializer");
4743                         
4744                         return null;
4745                 }
4746
4747                 override public void Emit (EmitContext ec)
4748                 {
4749                         ILGenerator ig = ec.ig;
4750
4751                         if (FieldInfo.IsStatic)
4752                                 ig.Emit (OpCodes.Ldsfld, FieldInfo);
4753                         else {
4754                                 InstanceExpression.Emit (ec);
4755                                 
4756                                 ig.Emit (OpCodes.Ldfld, FieldInfo);
4757                         }
4758                 }
4759
4760                 public void Store (EmitContext ec)
4761                 {
4762                         if (FieldInfo.IsStatic)
4763                                 ec.ig.Emit (OpCodes.Stsfld, FieldInfo);
4764                         else
4765                                 ec.ig.Emit (OpCodes.Stfld, FieldInfo);
4766                 }
4767
4768                 public void AddressOf (EmitContext ec)
4769                 {
4770                         if (FieldInfo.IsStatic)
4771                                 ec.ig.Emit (OpCodes.Ldsflda, FieldInfo);
4772                         else {
4773                                 InstanceExpression.Emit (ec);
4774                                 ec.ig.Emit (OpCodes.Ldflda, FieldInfo);
4775                         }
4776                 }
4777         }
4778         
4779         // <summary>
4780         //   Expression that evaluates to a Property.  The Assign class
4781         //   might set the `Value' expression if we are in an assignment.
4782         //
4783         //   This is not an LValue because we need to re-write the expression, we
4784         //   can not take data from the stack and store it.  
4785         // </summary>
4786         public class PropertyExpr : ExpressionStatement {
4787                 public readonly PropertyInfo PropertyInfo;
4788                 public readonly bool IsStatic;
4789                 MethodInfo [] Accessors;
4790                 Location loc;
4791                 
4792                 Expression instance_expr;
4793                 Expression value;
4794                 
4795                 public PropertyExpr (PropertyInfo pi, Location l)
4796                 {
4797                         PropertyInfo = pi;
4798                         eclass = ExprClass.PropertyAccess;
4799                         IsStatic = false;
4800                         loc = l;
4801                         Accessors = TypeManager.GetAccessors (pi);
4802
4803                         if (Accessors != null)
4804                                 for (int i = 0; i < Accessors.Length; i++){
4805                                         if (Accessors [i] != null)
4806                                                 if (Accessors [i].IsStatic)
4807                                                         IsStatic = true;
4808                                 }
4809                         else
4810                                 Accessors = new MethodInfo [2];
4811                         
4812                         type = pi.PropertyType;
4813                 }
4814
4815                 //
4816                 // Controls the Value of the PropertyExpr.  If the value
4817                 // is null, then the property is being used in a `read' mode.
4818                 // otherwise the property is used in assignment mode.
4819                 //
4820                 // The value is set to a fully resolved type by assign.
4821                 //
4822                 public Expression Value {
4823                         get {
4824                                 return value;
4825                         }
4826
4827                         set {
4828                                 this.value = value;
4829                         }
4830                 }
4831
4832                 //
4833                 // The instance expression associated with this expression
4834                 //
4835                 public Expression InstanceExpression {
4836                         set {
4837                                 instance_expr = value;
4838                         }
4839
4840                         get {
4841                                 return instance_expr;
4842                         }
4843                 }
4844
4845                 public bool VerifyAssignable ()
4846                 {
4847                         if (!PropertyInfo.CanWrite){
4848                                 Report.Error (200, loc, 
4849                                               "The property `" + PropertyInfo.Name +
4850                                               "' can not be assigned to, as it has not set accessor");
4851                                 return false;
4852                         }
4853
4854                         return true;
4855                 }
4856
4857                 override public Expression DoResolve (EmitContext ec)
4858                 {
4859                         if (!PropertyInfo.CanRead){
4860                                 Report.Error (154, loc, 
4861                                               "The property `" + PropertyInfo.Name +
4862                                               "' can not be used in " +
4863                                               "this context because it lacks a get accessor");
4864                                 return null;
4865                         }
4866
4867                         return this;
4868                 }
4869
4870                 override public void Emit (EmitContext ec)
4871                 {
4872                         if (value == null)
4873                                 Invocation.EmitCall (ec, IsStatic, instance_expr, Accessors [0], null);
4874                         else {
4875                                 Argument arg = new Argument (value, Argument.AType.Expression);
4876                                 ArrayList args = new ArrayList ();
4877
4878                                 args.Add (arg);
4879                                 Invocation.EmitCall (ec, IsStatic, instance_expr, Accessors [1], args);
4880                         }
4881                 }
4882
4883                 override public void EmitStatement (EmitContext ec)
4884                 {
4885                         Emit (ec);
4886                         if (value == null){
4887                                 ec.ig.Emit (OpCodes.Pop);
4888                         }
4889                 }
4890         }
4891
4892         // <summary>
4893         //   Fully resolved expression that evaluates to a Expression
4894         // </summary>
4895         public class EventExpr : Expression {
4896                 public readonly EventInfo EventInfo;
4897                 Location loc;
4898                 
4899                 public EventExpr (EventInfo ei, Location loc)
4900                 {
4901                         EventInfo = ei;
4902                         this.loc = loc;
4903                         eclass = ExprClass.EventAccess;
4904                 }
4905
4906                 override public Expression DoResolve (EmitContext ec)
4907                 {
4908                         // We are born in resolved state. 
4909                         return this;
4910                 }
4911
4912                 override public void Emit (EmitContext ec)
4913                 {
4914                         throw new Exception ("Implement me");
4915                         // FIXME: Implement.
4916                 }
4917         }
4918         
4919         public class CheckedExpr : Expression {
4920
4921                 public Expression Expr;
4922
4923                 public CheckedExpr (Expression e)
4924                 {
4925                         Expr = e;
4926                 }
4927
4928                 public override Expression DoResolve (EmitContext ec)
4929                 {
4930                         Expr = Expr.Resolve (ec);
4931
4932                         if (Expr == null)
4933                                 return null;
4934
4935                         eclass = Expr.ExprClass;
4936                         type = Expr.Type;
4937                         return this;
4938                 }
4939
4940                 public override void Emit (EmitContext ec)
4941                 {
4942                         bool last_check = ec.CheckState;
4943                         
4944                         ec.CheckState = true;
4945                         Expr.Emit (ec);
4946                         ec.CheckState = last_check;
4947                 }
4948                 
4949         }
4950
4951         public class UnCheckedExpr : Expression {
4952
4953                 public Expression Expr;
4954
4955                 public UnCheckedExpr (Expression e)
4956                 {
4957                         Expr = e;
4958                 }
4959
4960                 public override Expression DoResolve (EmitContext ec)
4961                 {
4962                         Expr = Expr.Resolve (ec);
4963
4964                         if (Expr == null)
4965                                 return null;
4966
4967                         eclass = Expr.ExprClass;
4968                         type = Expr.Type;
4969                         return this;
4970                 }
4971
4972                 public override void Emit (EmitContext ec)
4973                 {
4974                         bool last_check = ec.CheckState;
4975                         
4976                         ec.CheckState = false;
4977                         Expr.Emit (ec);
4978                         ec.CheckState = last_check;
4979                 }
4980                 
4981         }
4982
4983         public class ElementAccess : Expression {
4984                 
4985                 public ArrayList  Arguments;
4986                 public Expression Expr;
4987                 public Location   loc;
4988                 
4989                 public ElementAccess (Expression e, ArrayList e_list, Location l)
4990                 {
4991                         Expr = e;
4992
4993                         Arguments = new ArrayList ();
4994                         foreach (Expression tmp in e_list)
4995                                 Arguments.Add (new Argument (tmp, Argument.AType.Expression));
4996                         
4997                         loc  = l;
4998                 }
4999
5000                 Expression CommonResolve (EmitContext ec)
5001                 {
5002                         Expr = Expr.Resolve (ec);
5003
5004                         if (Expr == null) 
5005                                 return null;
5006
5007                         if (Arguments == null)
5008                                 return null;
5009
5010                         for (int i = Arguments.Count; i > 0;){
5011                                 --i;
5012                                 Argument a = (Argument) Arguments [i];
5013                                 
5014                                 if (!a.Resolve (ec))
5015                                         return null;
5016                         }
5017
5018                         return this;
5019                 }
5020                                 
5021                 public override Expression DoResolve (EmitContext ec)
5022                 {
5023                         Expr = CommonResolve (ec);
5024
5025                         if (Expr == null)
5026                                 return null;
5027                         
5028                         //
5029                         // We perform some simple tests, and then to "split" the emit and store
5030                         // code we create an instance of a different class, and return that.
5031                         //
5032                         // I am experimenting with this pattern.
5033                         //
5034                         if (Expr.Type == TypeManager.array_type)
5035                                 return (new ArrayAccess (this)).Resolve (ec);
5036                         else
5037                                 return (new IndexerAccess (this)).Resolve (ec);
5038                 }
5039
5040                 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
5041                 {
5042                         Expr = CommonResolve (ec);
5043
5044                         if (Expr == null)
5045                                 return null;
5046
5047                         if (Expr.Type == TypeManager.array_type)
5048                                 return (new ArrayAccess (this)).ResolveLValue (ec, right_side);
5049                         else
5050                                 return (new IndexerAccess (this)).ResolveLValue (ec, right_side);
5051                 }
5052                 
5053                 public override void Emit (EmitContext ec)
5054                 {
5055                         throw new Exception ("Should never be reached");
5056                 }
5057         }
5058
5059         public class ArrayAccess : Expression, IStackStore {
5060                 //
5061                 // Points to our "data" repository
5062                 //
5063                 ElementAccess ea;
5064                 
5065                 public ArrayAccess (ElementAccess ea_data)
5066                 {
5067                         ea = ea_data;
5068                         eclass = ExprClass.Variable;
5069
5070                         //
5071                         // FIXME: Figure out the type here
5072                         //
5073                 }
5074
5075                 Expression CommonResolve (EmitContext ec)
5076                 {
5077                         return this;
5078                 }
5079                 
5080                 public override Expression DoResolve (EmitContext ec)
5081                 {
5082                         if (ea.Expr.ExprClass != ExprClass.Variable) {
5083                                 report118 (ea.loc, ea.Expr, "variable");
5084                                 return null;
5085                         }
5086                         
5087                         throw new Exception ("Implement me");
5088                 }
5089
5090                 public void Store (EmitContext ec)
5091                 {
5092                         throw new Exception ("Implement me !");
5093                 }
5094
5095                 public override void Emit (EmitContext ec)
5096                 {
5097                         throw new Exception ("Implement me !");
5098                 }
5099         }
5100
5101         class Indexers {
5102                 public ArrayList getters, setters;
5103                 static Hashtable map;
5104
5105                 static Indexers ()
5106                 {
5107                         map = new Hashtable ();
5108                 }
5109
5110                 Indexers (MemberInfo [] mi)
5111                 {
5112                         foreach (PropertyInfo property in mi){
5113                                 MethodInfo [] accessors;
5114
5115                                 accessors = TypeManager.GetAccessors (property);
5116                                 if (accessors != null){
5117                                         int idx = 0;
5118                                         
5119                                         if (property.CanRead){
5120                                                 if (getters == null)
5121                                                         getters = new ArrayList ();
5122                                                 
5123                                                 getters.Add (accessors [idx++]);
5124                                         }
5125                                         if (property.CanWrite){
5126                                                 if (setters == null)
5127                                                         setters = new ArrayList ();
5128                                                 
5129                                                 setters.Add (accessors [idx++]);
5130                                         }
5131                                 }
5132                         }
5133                 }
5134                 
5135                 static string IndexerPropertyName (Type t)
5136                 {
5137                         System.Attribute attr;
5138
5139                         attr = System.Attribute.GetCustomAttribute (t, TypeManager.default_member_type);
5140
5141                         if (attr != null)
5142                         {
5143                                 DefaultMemberAttribute dma = (DefaultMemberAttribute) attr;
5144                                 
5145                                 return dma.MemberName;
5146                         }
5147
5148                         return "Item";
5149                 }
5150
5151                 static public Indexers GetIndexersForType (Type t, TypeManager tm, Location loc) 
5152                 {
5153                         Indexers ix = (Indexers) map [t];
5154                         string p_name = IndexerPropertyName (t);
5155                         
5156                         if (ix != null)
5157                                 return ix;
5158
5159                         MemberInfo [] mi = tm.FindMembers (
5160                                 t, MemberTypes.Property,
5161                                 BindingFlags.Public | BindingFlags.Instance,
5162                                 Type.FilterName, p_name);
5163
5164                         if (mi == null || mi.Length == 0){
5165                                 Report.Error (21, loc,
5166                                               "Type `" + TypeManager.CSharpName (t) + "' does not have " +
5167                                               "any indexers defined");
5168                                 return null;
5169                         }
5170                         
5171                         ix = new Indexers (mi);
5172                         map [t] = ix;
5173
5174                         return ix;
5175                 }
5176         }
5177         
5178         public class IndexerAccess : Expression {
5179                 //
5180                 // Points to our "data" repository
5181                 //
5182                 ElementAccess ea;
5183                 MethodInfo get, set;
5184                 Indexers ilist;
5185                 ArrayList set_arguments;
5186                 
5187                 public IndexerAccess (ElementAccess ea_data)
5188                 {
5189                         ea = ea_data;
5190                         eclass = ExprClass.Value;
5191                 }
5192
5193                 public bool VerifyAssignable (Expression source)
5194                 {
5195                         throw new Exception ("Implement me!");
5196                 }
5197
5198                 public override Expression DoResolve (EmitContext ec)
5199                 {
5200                         Type indexer_type = ea.Expr.Type;
5201                         
5202                         //
5203                         // Step 1: Query for all `Item' *properties*.  Notice
5204                         // that the actual methods are pointed from here.
5205                         //
5206                         // This is a group of properties, piles of them.  
5207
5208                         if (ilist == null)
5209                                 ilist = Indexers.GetIndexersForType (
5210                                         indexer_type, ec.TypeContainer.RootContext.TypeManager, ea.loc);
5211                         
5212                         if (ilist.getters != null && ilist.getters.Count > 0)
5213                                 get = (MethodInfo) Invocation.OverloadResolve (
5214                                         ec, new MethodGroupExpr (ilist.getters), ea.Arguments, ea.loc);
5215
5216                         if (get == null){
5217                                 Report.Error (154, ea.loc,
5218                                               "indexer can not be used in this context, because " +
5219                                               "it lacks a `get' accessor");
5220                                         return null;
5221                         }
5222                                 
5223                         type = get.ReturnType;
5224                         eclass = ExprClass.Value;
5225                         return this;
5226                 }
5227
5228                 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
5229                 {
5230                         Type indexer_type = ea.Expr.Type;
5231                         Type right_type = right_side.Type;
5232                         
5233                         if (ilist == null)
5234                                 ilist = Indexers.GetIndexersForType (
5235                                         indexer_type, ec.TypeContainer.RootContext.TypeManager, ea.loc);
5236                         
5237                         if (ilist.setters != null && ilist.setters.Count > 0){
5238                                 set_arguments = (ArrayList) ea.Arguments.Clone ();
5239                                 set_arguments.Add (new Argument (right_side, Argument.AType.Expression));
5240
5241                                 set = (MethodInfo) Invocation.OverloadResolve (
5242                                         ec, new MethodGroupExpr (ilist.getters), set_arguments, ea.loc);
5243                         }
5244                         
5245                         if (set == null){
5246                                 Report.Error (200, ea.loc,
5247                                               "indexer X.this [" + TypeManager.CSharpName (right_type) +
5248                                               "] lacks a `set' accessor");
5249                                         return null;
5250                         }
5251                                 
5252                         type = set.ReturnType;
5253                         eclass = ExprClass.Value;
5254                         return this;
5255                 }
5256                 
5257                 public override void Emit (EmitContext ec)
5258                 {
5259                         Invocation.EmitCall (ec, false, ea.Expr, get, ea.Arguments);
5260                 }
5261         }
5262         
5263         public class BaseAccess : Expression {
5264
5265                 public enum BaseAccessType {
5266                         Member,
5267                         Indexer
5268                 };
5269                 
5270                 public readonly BaseAccessType BAType;
5271                 public readonly string         Member;
5272                 public readonly ArrayList      Arguments;
5273
5274                 public BaseAccess (BaseAccessType t, string member, ArrayList args)
5275                 {
5276                         BAType = t;
5277                         Member = member;
5278                         Arguments = args;
5279                         
5280                 }
5281
5282                 public override Expression DoResolve (EmitContext ec)
5283                 {
5284                         // FIXME: Implement;
5285                         throw new Exception ("Unimplemented");
5286                         // return this;
5287                 }
5288
5289                 public override void Emit (EmitContext ec)
5290                 {
5291                         throw new Exception ("Unimplemented");
5292                 }
5293         }
5294
5295         // <summary>
5296         //   This class exists solely to pass the Type around and to be a dummy
5297         //   that can be passed to the conversion functions (this is used by
5298         //   foreach implementation to typecast the object return value from
5299         //   get_Current into the proper type.  All code has been generated and
5300         //   we only care about the side effect conversions to be performed
5301         // </summary>
5302         
5303         public class EmptyExpression : Expression {
5304                 public EmptyExpression ()
5305                 {
5306                         type = TypeManager.object_type;
5307                         eclass = ExprClass.Value;
5308                 }
5309
5310                 public override Expression DoResolve (EmitContext ec)
5311                 {
5312                         return this;
5313                 }
5314
5315                 public override void Emit (EmitContext ec)
5316                 {
5317                         // nothing, as we only exist to not do anything.
5318                 }
5319         }
5320
5321         public class UserCast : Expression {
5322                 MethodBase method;
5323                 Expression source;
5324                 
5325                 public UserCast (MethodInfo method, Expression source)
5326                 {
5327                         this.method = method;
5328                         this.source = source;
5329                         type = method.ReturnType;
5330                         eclass = ExprClass.Value;
5331                 }
5332
5333                 public override Expression DoResolve (EmitContext ec)
5334                 {
5335                         //
5336                         // We are born fully resolved
5337                         //
5338                         return this;
5339                 }
5340
5341                 public override void Emit (EmitContext ec)
5342                 {
5343                         ILGenerator ig = ec.ig;
5344
5345                         source.Emit (ec);
5346                         
5347                         if (method is MethodInfo)
5348                                 ig.Emit (OpCodes.Call, (MethodInfo) method);
5349                         else
5350                                 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
5351
5352                 }
5353
5354         }
5355 }