2001-11-22 Ravi Pratap <ravi@ximian.com>
[mono.git] / mcs / mcs / ecore.cs
1 //
2 // ecore.cs: Core of the Expression representation for the intermediate tree.
3 //
4 // Author:
5 //   Miguel de Icaza (miguel@ximian.com)
6 //
7 // (C) 2001 Ximian, Inc.
8 //
9 //
10
11 namespace Mono.CSharp {
12         using System;
13         using System.Collections;
14         using System.Diagnostics;
15         using System.Reflection;
16         using System.Reflection.Emit;
17         using System.Text;
18
19         /// <remarks>
20         ///   The ExprClass class contains the is used to pass the 
21         ///   classification of an expression (value, variable, namespace,
22         ///   type, method group, property access, event access, indexer access,
23         ///   nothing).
24         /// </remarks>
25         public enum ExprClass : byte {
26                 Invalid,
27                 
28                 Value,
29                 Variable,
30                 Namespace,
31                 Type,
32                 MethodGroup,
33                 PropertyAccess,
34                 EventAccess,
35                 IndexerAccess,
36                 Nothing, 
37         }
38
39         /// <summary>
40         ///   This interface is implemented by variables
41         /// </summary>
42         public interface IMemoryLocation {
43                 /// <summary>
44                 ///   The AddressOf method should generate code that loads
45                 ///   the address of the object and leaves it on the stack
46                 /// </summary>
47                 void AddressOf (EmitContext ec);
48         }
49
50         /// <remarks>
51         ///   Base class for expressions
52         /// </remarks>
53         public abstract class Expression {
54                 protected ExprClass eclass;
55                 protected Type      type;
56                 
57                 public Type Type {
58                         get {
59                                 return type;
60                         }
61
62                         set {
63                                 type = value;
64                         }
65                 }
66
67                 public ExprClass ExprClass {
68                         get {
69                                 return eclass;
70                         }
71
72                         set {
73                                 eclass = value;
74                         }
75                 }
76
77                 /// <summary>
78                 ///   Utility wrapper routine for Error, just to beautify the code
79                 /// </summary>
80                 static protected void Error (int error, string s)
81                 {
82                         Report.Error (error, s);
83                 }
84
85                 static protected void Error (int error, Location loc, string s)
86                 {
87                         Report.Error (error, loc, s);
88                 }
89                 
90                 /// <summary>
91                 ///   Utility wrapper routine for Warning, just to beautify the code
92                 /// </summary>
93                 static protected void Warning (int warning, string s)
94                 {
95                         Report.Warning (warning, s);
96                 }
97
98                 static public void error30 (Location loc, Type source, Type target)
99                 {
100                         Report.Error (30, loc, "Cannot convert type '" +
101                                       TypeManager.CSharpName (source) + "' to '" +
102                                       TypeManager.CSharpName (target) + "'");
103                 }
104
105                 /// <summary>
106                 ///   Performs semantic analysis on the Expression
107                 /// </summary>
108                 ///
109                 /// <remarks>
110                 ///   The Resolve method is invoked to perform the semantic analysis
111                 ///   on the node.
112                 ///
113                 ///   The return value is an expression (it can be the
114                 ///   same expression in some cases) or a new
115                 ///   expression that better represents this node.
116                 ///   
117                 ///   For example, optimizations of Unary (LiteralInt)
118                 ///   would return a new LiteralInt with a negated
119                 ///   value.
120                 ///   
121                 ///   If there is an error during semantic analysis,
122                 ///   then an error should be reported (using Report)
123                 ///   and a null value should be returned.
124                 ///   
125                 ///   There are two side effects expected from calling
126                 ///   Resolve(): the the field variable "eclass" should
127                 ///   be set to any value of the enumeration
128                 ///   `ExprClass' and the type variable should be set
129                 ///   to a valid type (this is the type of the
130                 ///   expression).
131                 /// </remarks>
132                 public abstract Expression DoResolve (EmitContext ec);
133
134                 public virtual Expression DoResolveLValue (EmitContext ec, Expression right_side)
135                 {
136                         return DoResolve (ec);
137                 }
138                 
139                 /// <summary>
140                 ///   Resolves an expression and performs semantic analysis on it.
141                 /// </summary>
142                 ///
143                 /// <remarks>
144                 ///   Currently Resolve wraps DoResolve to perform sanity
145                 ///   checking and assertion checking on what we expect from Resolve.
146                 /// </remarks>
147                 public Expression Resolve (EmitContext ec)
148                 {
149                         Expression e = DoResolve (ec);
150
151                         if (e != null){
152                                 if (e is SimpleName){
153                                         SimpleName s = (SimpleName) e;
154                                         
155                                         Report.Error (
156                                                 103, s.Location,
157                                                 "The name `" + s.Name + "' could not be found in `" +
158                                                 ec.TypeContainer.Name + "'");
159                                         return null;
160                                 }
161                                 
162                                 if (e.ExprClass == ExprClass.Invalid)
163                                         throw new Exception ("Expression " + e +
164                                                              " ExprClass is Invalid after resolve");
165
166                                 if (e.ExprClass != ExprClass.MethodGroup)
167                                         if (e.type == null)
168                                                 throw new Exception ("Expression " + e +
169                                                                      " did not set its type after Resolve");
170                         }
171
172                         return e;
173                 }
174
175                 /// <summary>
176                 ///   Performs expression resolution and semantic analysis, but
177                 ///   allows SimpleNames to be returned.
178                 /// </summary>
179                 ///
180                 /// <remarks>
181                 ///   This is used by MemberAccess to construct long names that can not be
182                 ///   partially resolved (namespace-qualified names for example).
183                 /// </remarks>
184                 public Expression ResolveWithSimpleName (EmitContext ec)
185                 {
186                         Expression e = DoResolve (ec);
187
188                         if (e != null){
189                                 if (e is SimpleName)
190                                         return e;
191
192                                 if (e.ExprClass == ExprClass.Invalid)
193                                         throw new Exception ("Expression " + e +
194                                                              " ExprClass is Invalid after resolve");
195
196                                 if (e.ExprClass != ExprClass.MethodGroup)
197                                         if (e.type == null)
198                                                 throw new Exception ("Expression " + e +
199                                                                      " did not set its type after Resolve");
200                         }
201
202                         return e;
203                 }
204                 
205                 /// <summary>
206                 ///   Resolves an expression for LValue assignment
207                 /// </summary>
208                 ///
209                 /// <remarks>
210                 ///   Currently ResolveLValue wraps DoResolveLValue to perform sanity
211                 ///   checking and assertion checking on what we expect from Resolve
212                 /// </remarks>
213                 public Expression ResolveLValue (EmitContext ec, Expression right_side)
214                 {
215                         Expression e = DoResolveLValue (ec, right_side);
216
217                         if (e != null){
218                                 if (e is SimpleName){
219                                         SimpleName s = (SimpleName) e;
220                                         
221                                         Report.Error (
222                                                 103, s.Location,
223                                                 "The name `" + s.Name + "' could not be found in `" +
224                                                 ec.TypeContainer.Name + "'");
225                                         return null;
226                                 }
227
228                                 if (e.ExprClass == ExprClass.Invalid)
229                                         throw new Exception ("Expression " + e +
230                                                              " ExprClass is Invalid after resolve");
231
232                                 if (e.ExprClass != ExprClass.MethodGroup)
233                                         if (e.type == null)
234                                                 throw new Exception ("Expression " + e +
235                                                                      " did not set its type after Resolve");
236                         }
237
238                         return e;
239                 }
240                 
241                 /// <summary>
242                 ///   Emits the code for the expression
243                 /// </summary>
244                 ///
245                 /// <remarks>
246                 ///   The Emit method is invoked to generate the code
247                 ///   for the expression.  
248                 /// </remarks>
249                 public abstract void Emit (EmitContext ec);
250
251                 /// <summary>
252                 ///   This method should perform a reduction of the expression.  This should
253                 ///   never return null.
254                 /// </summary>
255                 public virtual Expression Reduce (EmitContext ec)
256                 {
257                         return this;
258                 }
259
260                 /// <summary>
261                 ///   Protected constructor.  Only derivate types should
262                 ///   be able to be created
263                 /// </summary>
264
265                 protected Expression ()
266                 {
267                         eclass = ExprClass.Invalid;
268                         type = null;
269                 }
270
271                 /// <summary>
272                 ///   Returns a literalized version of a literal FieldInfo
273                 /// </summary>
274                 public static Expression Literalize (object v, Type t)
275                 {
276                         if (t == TypeManager.int32_type)
277                                 return new IntLiteral ((int) v);
278                         else if (t == TypeManager.uint32_type)
279                                 return new UIntLiteral ((uint) v);
280                         else if (t == TypeManager.int64_type)
281                                 return new LongLiteral ((long) v);
282                         else if (t == TypeManager.uint64_type)
283                                 return new ULongLiteral ((ulong) v);
284                         else if (t == TypeManager.float_type)
285                                 return new FloatLiteral ((float) v);
286                         else if (t == TypeManager.double_type)
287                                 return new DoubleLiteral ((double) v);
288                         else if (t == TypeManager.string_type)
289                                 return new StringLiteral ((string) v);
290                         else if (t == TypeManager.short_type)
291                                 return new IntLiteral ((int) ((short)v));
292                         else if (t == TypeManager.ushort_type)
293                                 return new IntLiteral ((int) ((ushort)v));
294                         else if (t == TypeManager.sbyte_type)
295                                 return new IntLiteral ((int) ((sbyte)v));
296                         else if (t == TypeManager.byte_type)
297                                 return new IntLiteral ((int) ((byte)v));
298                         else if (t == TypeManager.char_type)
299                                 return new IntLiteral ((int) ((char)v));
300                         else
301                                 throw new Exception ("Unknown type for literal (" + t +
302                                                      "), details: " + v);
303                 }
304
305                 /// <summary>
306                 ///   Returns a fully formed expression after a MemberLookup
307                 /// </summary>
308                 static Expression ExprClassFromMemberInfo (EmitContext ec, MemberInfo mi, Location loc)
309                 {
310                         if (mi is EventInfo)
311                                 return new EventExpr ((EventInfo) mi, loc);
312                         else if (mi is FieldInfo)
313                                 return new FieldExpr ((FieldInfo) mi, loc);
314                         else if (mi is PropertyInfo)
315                                 return new PropertyExpr ((PropertyInfo) mi, loc);
316                         else if (mi is Type)
317                                 return new TypeExpr ((Type) mi);
318
319                         return null;
320                 }
321
322                 //
323                 // FIXME: Probably implement a cache for (t,name,current_access_set)?
324                 //
325                 // FIXME: We need to cope with access permissions here, or this wont
326                 // work!
327                 //
328                 // This code could use some optimizations, but we need to do some
329                 // measurements.  For example, we could use a delegate to `flag' when
330                 // something can not any longer be a method-group (because it is something
331                 // else).
332                 //
333                 // Return values:
334                 //     If the return value is an Array, then it is an array of
335                 //     MethodBases
336                 //   
337                 //     If the return value is an MemberInfo, it is anything, but a Method
338                 //
339                 //     null on error.
340                 //
341                 // FIXME: When calling MemberLookup inside an `Invocation', we should pass
342                 // the arguments here and have MemberLookup return only the methods that
343                 // match the argument count/type, unlike we are doing now (we delay this
344                 // decision).
345                 //
346                 // This is so we can catch correctly attempts to invoke instance methods
347                 // from a static body (scan for error 120 in ResolveSimpleName).
348                 //
349                 public static Expression MemberLookup (EmitContext ec, Type t, string name,
350                                                        bool same_type, MemberTypes mt,
351                                                        BindingFlags bf, Location loc)
352                 {
353                         if (same_type)
354                                 bf |= BindingFlags.NonPublic;
355
356                         MemberInfo [] mi = ec.TypeContainer.RootContext.TypeManager.FindMembers (
357                                 t, mt, bf, Type.FilterName, name);
358
359                         if (mi == null)
360                                 return null;
361
362                         // Empty array ...
363                         if (mi.Length == 0) 
364                                 return null;
365
366                         
367                         if (mi.Length == 1 && !(mi [0] is MethodBase))
368                                 return Expression.ExprClassFromMemberInfo (ec, mi [0], loc);
369                         
370                         for (int i = 0; i < mi.Length; i++)
371                                 if (!(mi [i] is MethodBase)){
372                                         Error (-5, "Do not know how to reproduce this case: " + 
373                                                "Methods and non-Method with the same name, " +
374                                                "report this please");
375
376                                         for (i = 0; i < mi.Length; i++){
377                                                 Type tt = mi [i].GetType ();
378
379                                                 Console.WriteLine (i + ": " + mi [i]);
380                                                 while (tt != TypeManager.object_type){
381                                                         Console.WriteLine (tt);
382                                                         tt = tt.BaseType;
383                                                 }
384                                         }
385                                 }
386
387                         return new MethodGroupExpr (mi);
388                 }
389
390                 public const MemberTypes AllMemberTypes =
391                         MemberTypes.Constructor |
392                         MemberTypes.Event       |
393                         MemberTypes.Field       |
394                         MemberTypes.Method      |
395                         MemberTypes.NestedType  |
396                         MemberTypes.Property;
397                 
398                 public const BindingFlags AllBindingsFlags =
399                         BindingFlags.Public |
400                         BindingFlags.Static |
401                         BindingFlags.Instance;
402
403                 public static Expression MemberLookup (EmitContext ec, Type t, string name,
404                                                        bool same_type, Location loc)
405                 {
406                         return MemberLookup (ec, t, name, same_type, AllMemberTypes, AllBindingsFlags, loc);
407                 }
408
409                 static public Expression ImplicitReferenceConversion (Expression expr, Type target_type)
410                 {
411                         Type expr_type = expr.Type;
412
413                         if (target_type == TypeManager.object_type) {
414                                 if (expr_type.IsClass)
415                                         return new EmptyCast (expr, target_type);
416                                 if (expr_type.IsValueType)
417                                         return new BoxedCast (expr);
418                         } else if (expr_type.IsSubclassOf (target_type)) {
419                                 return new EmptyCast (expr, target_type);
420                         } else {
421                                 // from any class-type S to any interface-type T.
422                                 if (expr_type.IsClass && target_type.IsInterface) {
423
424                                         if (TypeManager.ImplementsInterface (expr_type, target_type))
425                                                 return new EmptyCast (expr, target_type);
426                                         else
427                                                 return null;
428                                 }
429
430                                 // from any interface type S to interface-type T.
431                                 if (expr_type.IsInterface && target_type.IsInterface) {
432
433                                         if (TypeManager.ImplementsInterface (expr_type, target_type))
434                                                 return new EmptyCast (expr, target_type);
435                                         else
436                                                 return null;
437                                 }
438                                 
439                                 // from an array-type S to an array-type of type T
440                                 if (expr_type.IsArray && target_type.IsArray) {
441                                         if (expr_type.GetArrayRank () == target_type.GetArrayRank ()) {
442
443                                                 Type expr_element_type = expr_type.GetElementType ();
444                                                 Type target_element_type = target_type.GetElementType ();
445
446                                                 if (!expr_element_type.IsValueType && !target_element_type.IsValueType)
447                                                         if (StandardConversionExists (expr_element_type,
448                                                                                       target_element_type))
449                                                                 return new EmptyCast (expr, target_type);
450                                         }
451                                 }
452                                 
453                                 
454                                 // from an array-type to System.Array
455                                 if (expr_type.IsArray && target_type == TypeManager.array_type)
456                                         return new EmptyCast (expr, target_type);
457                                 
458                                 // from any delegate type to System.Delegate
459                                 if (expr_type.IsSubclassOf (TypeManager.delegate_type) &&
460                                     target_type == TypeManager.delegate_type)
461                                         return new EmptyCast (expr, target_type);
462                                         
463                                 // from any array-type or delegate type into System.ICloneable.
464                                 if (expr_type.IsArray || expr_type.IsSubclassOf (TypeManager.delegate_type))
465                                         if (target_type == TypeManager.icloneable_type)
466                                                 return new EmptyCast (expr, target_type);
467                                 
468                                 // from the null type to any reference-type.
469                                 if (expr is NullLiteral)
470                                         return new EmptyCast (expr, target_type);
471
472                                 return null;
473
474                         }
475                         
476                         return null;
477                 }
478
479                 /// <summary>
480                 ///   Handles expressions like this: decimal d; d = 1;
481                 ///   and changes them into: decimal d; d = new System.Decimal (1);
482                 /// </summary>
483                 static Expression InternalTypeConstructor (EmitContext ec, Expression expr, Type target)
484                 {
485                         ArrayList args = new ArrayList ();
486
487                         args.Add (new Argument (expr, Argument.AType.Expression));
488
489                         Expression ne = new New (target.FullName, args,
490                                                  new Location (-1));
491
492                         return ne.Resolve (ec);
493                 }
494
495                 /// <summary>
496                 ///   Implicit Numeric Conversions.
497                 ///
498                 ///   expr is the expression to convert, returns a new expression of type
499                 ///   target_type or null if an implicit conversion is not possible.
500                 /// </summary>
501                 static public Expression ImplicitNumericConversion (EmitContext ec, Expression expr,
502                                                                     Type target_type, Location loc)
503                 {
504                         Type expr_type = expr.Type;
505                         
506                         //
507                         // Attempt to do the implicit constant expression conversions
508
509                         if (expr is IntLiteral){
510                                 Expression e;
511                                 
512                                 e = TryImplicitIntConversion (target_type, (IntLiteral) expr);
513
514                                 if (e != null)
515                                         return e;
516                         } else if (expr is LongLiteral && target_type == TypeManager.uint64_type){
517                                 //
518                                 // Try the implicit constant expression conversion
519                                 // from long to ulong, instead of a nice routine,
520                                 // we just inline it
521                                 //
522                                 if (((LongLiteral) expr).Value > 0)
523                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_I8);
524                         }
525                         
526                         if (expr_type == TypeManager.sbyte_type){
527                                 //
528                                 // From sbyte to short, int, long, float, double.
529                                 //
530                                 if (target_type == TypeManager.int32_type)
531                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_I4);
532                                 if (target_type == TypeManager.int64_type)
533                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_I8);
534                                 if (target_type == TypeManager.double_type)
535                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_R8);
536                                 if (target_type == TypeManager.float_type)
537                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_R4);
538                                 if (target_type == TypeManager.short_type)
539                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_I2);
540                                 if (target_type == TypeManager.decimal_type)
541                                         return InternalTypeConstructor (ec, expr, target_type);
542                         } else if (expr_type == TypeManager.byte_type){
543                                 //
544                                 // From byte to short, ushort, int, uint, long, ulong, float, double
545                                 // 
546                                 if ((target_type == TypeManager.short_type) ||
547                                     (target_type == TypeManager.ushort_type) ||
548                                     (target_type == TypeManager.int32_type) ||
549                                     (target_type == TypeManager.uint32_type))
550                                         return new EmptyCast (expr, target_type);
551
552                                 if (target_type == TypeManager.uint64_type)
553                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_U8);
554                                 if (target_type == TypeManager.int64_type)
555                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_I8);
556                                 
557                                 if (target_type == TypeManager.float_type)
558                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_R4);
559                                 if (target_type == TypeManager.double_type)
560                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_R8);
561                                 if (target_type == TypeManager.decimal_type)
562                                         return InternalTypeConstructor (ec, expr, target_type);
563                         } else if (expr_type == TypeManager.short_type){
564                                 //
565                                 // From short to int, long, float, double
566                                 // 
567                                 if (target_type == TypeManager.int32_type)
568                                         return new EmptyCast (expr, target_type);
569                                 if (target_type == TypeManager.int64_type)
570                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_I8);
571                                 if (target_type == TypeManager.double_type)
572                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_R8);
573                                 if (target_type == TypeManager.float_type)
574                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_R4);
575                                 if (target_type == TypeManager.decimal_type)
576                                         return InternalTypeConstructor (ec, expr, target_type);
577                         } else if (expr_type == TypeManager.ushort_type){
578                                 //
579                                 // From ushort to int, uint, long, ulong, float, double
580                                 //
581                                 if (target_type == TypeManager.uint32_type)
582                                         return new EmptyCast (expr, target_type);
583
584                                 if (target_type == TypeManager.uint64_type)
585                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_U8);
586                                 if (target_type == TypeManager.int32_type)
587                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_I4);
588                                 if (target_type == TypeManager.int64_type)
589                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_I8);
590                                 if (target_type == TypeManager.double_type)
591                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_R8);
592                                 if (target_type == TypeManager.float_type)
593                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_R4);
594                                 if (target_type == TypeManager.decimal_type)
595                                         return InternalTypeConstructor (ec, expr, target_type);
596                         } else if (expr_type == TypeManager.int32_type){
597                                 //
598                                 // From int to long, float, double
599                                 //
600                                 if (target_type == TypeManager.int64_type)
601                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_I8);
602                                 if (target_type == TypeManager.double_type)
603                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_R8);
604                                 if (target_type == TypeManager.float_type)
605                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_R4);
606                                 if (target_type == TypeManager.decimal_type)
607                                         return InternalTypeConstructor (ec, expr, target_type);
608                         } else if (expr_type == TypeManager.uint32_type){
609                                 //
610                                 // From uint to long, ulong, float, double
611                                 //
612                                 if (target_type == TypeManager.int64_type)
613                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_U8);
614                                 if (target_type == TypeManager.uint64_type)
615                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_U8);
616                                 if (target_type == TypeManager.double_type)
617                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_R_Un,
618                                                                OpCodes.Conv_R8);
619                                 if (target_type == TypeManager.float_type)
620                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_R_Un,
621                                                                OpCodes.Conv_R4);
622                                 if (target_type == TypeManager.decimal_type)
623                                         return InternalTypeConstructor (ec, expr, target_type);
624                         } else if ((expr_type == TypeManager.uint64_type) ||
625                                    (expr_type == TypeManager.int64_type)){
626                                 //
627                                 // From long/ulong to float, double
628                                 //
629                                 if (target_type == TypeManager.double_type)
630                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_R_Un,
631                                                                OpCodes.Conv_R8);
632                                 if (target_type == TypeManager.float_type)
633                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_R_Un,
634                                                                OpCodes.Conv_R4);        
635                                 if (target_type == TypeManager.decimal_type)
636                                         return InternalTypeConstructor (ec, expr, target_type);
637                         } else if (expr_type == TypeManager.char_type){
638                                 //
639                                 // From char to ushort, int, uint, long, ulong, float, double
640                                 // 
641                                 if ((target_type == TypeManager.ushort_type) ||
642                                     (target_type == TypeManager.int32_type) ||
643                                     (target_type == TypeManager.uint32_type))
644                                         return new EmptyCast (expr, target_type);
645                                 if (target_type == TypeManager.uint64_type)
646                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_U8);
647                                 if (target_type == TypeManager.int64_type)
648                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_I8);
649                                 if (target_type == TypeManager.float_type)
650                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_R4);
651                                 if (target_type == TypeManager.double_type)
652                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_R8);
653                                 if (target_type == TypeManager.decimal_type)
654                                         return InternalTypeConstructor (ec, expr, target_type);
655                         } else if (expr_type == TypeManager.float_type){
656                                 //
657                                 // float to double
658                                 //
659                                 if (target_type == TypeManager.double_type)
660                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_R8);
661                         }
662
663                         return null;
664                 }
665
666                 /// <summary>
667                 ///  Determines if a standard implicit conversion exists from
668                 ///  expr_type to target_type
669                 /// </summary>
670                 public static bool StandardConversionExists (Type expr_type, Type target_type)
671                 {
672                         if (expr_type == target_type)
673                                 return true;
674
675                         // First numeric conversions 
676                         
677                         if (expr_type == TypeManager.sbyte_type){
678                                 //
679                                 // From sbyte to short, int, long, float, double.
680                                 //
681                                 if ((target_type == TypeManager.int32_type) || 
682                                     (target_type == TypeManager.int64_type) ||
683                                     (target_type == TypeManager.double_type) ||
684                                     (target_type == TypeManager.float_type)  ||
685                                     (target_type == TypeManager.short_type) ||
686                                     (target_type == TypeManager.decimal_type))
687                                         return true;
688                                 
689                         } else if (expr_type == TypeManager.byte_type){
690                                 //
691                                 // From byte to short, ushort, int, uint, long, ulong, float, double
692                                 // 
693                                 if ((target_type == TypeManager.short_type) ||
694                                     (target_type == TypeManager.ushort_type) ||
695                                     (target_type == TypeManager.int32_type) ||
696                                     (target_type == TypeManager.uint32_type) ||
697                                     (target_type == TypeManager.uint64_type) ||
698                                     (target_type == TypeManager.int64_type) ||
699                                     (target_type == TypeManager.float_type) ||
700                                     (target_type == TypeManager.double_type) ||
701                                     (target_type == TypeManager.decimal_type))
702                                         return true;
703         
704                         } else if (expr_type == TypeManager.short_type){
705                                 //
706                                 // From short to int, long, float, double
707                                 // 
708                                 if ((target_type == TypeManager.int32_type) ||
709                                     (target_type == TypeManager.int64_type) ||
710                                     (target_type == TypeManager.double_type) ||
711                                     (target_type == TypeManager.float_type) ||
712                                     (target_type == TypeManager.decimal_type))
713                                         return true;
714                                         
715                         } else if (expr_type == TypeManager.ushort_type){
716                                 //
717                                 // From ushort to int, uint, long, ulong, float, double
718                                 //
719                                 if ((target_type == TypeManager.uint32_type) ||
720                                     (target_type == TypeManager.uint64_type) ||
721                                     (target_type == TypeManager.int32_type) ||
722                                     (target_type == TypeManager.int64_type) ||
723                                     (target_type == TypeManager.double_type) ||
724                                     (target_type == TypeManager.float_type) ||
725                                     (target_type == TypeManager.decimal_type))
726                                         return true;
727                                     
728                         } else if (expr_type == TypeManager.int32_type){
729                                 //
730                                 // From int to long, float, double
731                                 //
732                                 if ((target_type == TypeManager.int64_type) ||
733                                     (target_type == TypeManager.double_type) ||
734                                     (target_type == TypeManager.float_type) ||
735                                     (target_type == TypeManager.decimal_type))
736                                         return true;
737                                         
738                         } else if (expr_type == TypeManager.uint32_type){
739                                 //
740                                 // From uint to long, ulong, float, double
741                                 //
742                                 if ((target_type == TypeManager.int64_type) ||
743                                     (target_type == TypeManager.uint64_type) ||
744                                     (target_type == TypeManager.double_type) ||
745                                     (target_type == TypeManager.float_type) ||
746                                     (target_type == TypeManager.decimal_type))
747                                         return true;
748                                         
749                         } else if ((expr_type == TypeManager.uint64_type) ||
750                                    (expr_type == TypeManager.int64_type)) {
751                                 //
752                                 // From long/ulong to float, double
753                                 //
754                                 if ((target_type == TypeManager.double_type) ||
755                                     (target_type == TypeManager.float_type) ||
756                                     (target_type == TypeManager.decimal_type))
757                                         return true;
758                                     
759                         } else if (expr_type == TypeManager.char_type){
760                                 //
761                                 // From char to ushort, int, uint, long, ulong, float, double
762                                 // 
763                                 if ((target_type == TypeManager.ushort_type) ||
764                                     (target_type == TypeManager.int32_type) ||
765                                     (target_type == TypeManager.uint32_type) ||
766                                     (target_type == TypeManager.uint64_type) ||
767                                     (target_type == TypeManager.int64_type) ||
768                                     (target_type == TypeManager.float_type) ||
769                                     (target_type == TypeManager.double_type) ||
770                                     (target_type == TypeManager.decimal_type))
771                                         return true;
772
773                         } else if (expr_type == TypeManager.float_type){
774                                 //
775                                 // float to double
776                                 //
777                                 if (target_type == TypeManager.double_type)
778                                         return true;
779                         }       
780                         
781                         // Next reference conversions
782
783                         if (target_type == TypeManager.object_type) {
784                                 if ((expr_type.IsClass) ||
785                                     (expr_type.IsValueType))
786                                         return true;
787                                 
788                         } else if (expr_type.IsSubclassOf (target_type)) {
789                                 return true;
790                                 
791                         } else {
792                                 // from any class-type S to any interface-type T.
793                                 if (expr_type.IsClass && target_type.IsInterface)
794                                         return true;
795                                 
796                                 // from any interface type S to interface-type T.
797                                 // FIXME : Is it right to use IsAssignableFrom ?
798                                 if (expr_type.IsInterface && target_type.IsInterface)
799                                         if (target_type.IsAssignableFrom (expr_type))
800                                                 return true;
801                                 
802                                 // from an array-type S to an array-type of type T
803                                 if (expr_type.IsArray && target_type.IsArray) {
804                                         if (expr_type.GetArrayRank () == target_type.GetArrayRank ()) {
805                                                 
806                                                 Type expr_element_type = expr_type.GetElementType ();
807                                                 Type target_element_type = target_type.GetElementType ();
808                                                 
809                                                 if (!expr_element_type.IsValueType && !target_element_type.IsValueType)
810                                                         if (StandardConversionExists (expr_element_type,
811                                                                                       target_element_type))
812                                                                 return true;
813                                         }
814                                 }
815                                 
816                                 // from an array-type to System.Array
817                                 if (expr_type.IsArray && target_type.IsAssignableFrom (expr_type))
818                                         return true;
819                                 
820                                 // from any delegate type to System.Delegate
821                                 if (expr_type.IsSubclassOf (TypeManager.delegate_type) &&
822                                     target_type == TypeManager.delegate_type)
823                                         if (target_type.IsAssignableFrom (expr_type))
824                                                 return true;
825                                         
826                                 // from any array-type or delegate type into System.ICloneable.
827                                 if (expr_type.IsArray || expr_type.IsSubclassOf (TypeManager.delegate_type))
828                                         if (target_type == TypeManager.icloneable_type)
829                                                 return true;
830                                 
831                                 // from the null type to any reference-type.
832                                 // FIXME : How do we do this ?
833
834                         }
835
836                         return false;
837                 }
838                 
839                 /// <summary>
840                 ///  Finds "most encompassed type" according to the spec (13.4.2)
841                 ///  amongst the methods in the MethodGroupExpr which convert from a
842                 ///  type encompassing source_type
843                 /// </summary>
844                 static Type FindMostEncompassedType (MethodGroupExpr me, Type source_type)
845                 {
846                         Type best = null;
847                         
848                         for (int i = me.Methods.Length; i > 0; ) {
849                                 i--;
850
851                                 MethodBase mb = me.Methods [i];
852                                 ParameterData pd = Invocation.GetParameterData (mb);
853                                 Type param_type = pd.ParameterType (0);
854
855                                 if (StandardConversionExists (source_type, param_type)) {
856                                         if (best == null)
857                                                 best = param_type;
858                                         
859                                         if (StandardConversionExists (param_type, best))
860                                                 best = param_type;
861                                 }
862                         }
863
864                         return best;
865                 }
866                 
867                 /// <summary>
868                 ///  Finds "most encompassing type" according to the spec (13.4.2)
869                 ///  amongst the methods in the MethodGroupExpr which convert to a
870                 ///  type encompassed by target_type
871                 /// </summary>
872                 static Type FindMostEncompassingType (MethodGroupExpr me, Type target)
873                 {
874                         Type best = null;
875                         
876                         for (int i = me.Methods.Length; i > 0; ) {
877                                 i--;
878                                 
879                                 MethodInfo mi = (MethodInfo) me.Methods [i];
880                                 Type ret_type = mi.ReturnType;
881                                 
882                                 if (StandardConversionExists (ret_type, target)) {
883                                         if (best == null)
884                                                 best = ret_type;
885
886                                         if (!StandardConversionExists (ret_type, best))
887                                                 best = ret_type;
888                                 }
889                                 
890                         }
891                         
892                         return best;
893
894                 }
895                 
896
897                 /// <summary>
898                 ///  User-defined Implicit conversions
899                 /// </summary>
900                 static public Expression ImplicitUserConversion (EmitContext ec, Expression source,
901                                                                  Type target, Location loc)
902                 {
903                         return UserDefinedConversion (ec, source, target, loc, false);
904                 }
905
906                 /// <summary>
907                 ///  User-defined Explicit conversions
908                 /// </summary>
909                 static public Expression ExplicitUserConversion (EmitContext ec, Expression source,
910                                                                  Type target, Location loc)
911                 {
912                         return UserDefinedConversion (ec, source, target, loc, true);
913                 }
914                 
915                 /// <summary>
916                 ///   User-defined conversions
917                 /// </summary>
918                 static public Expression UserDefinedConversion (EmitContext ec, Expression source,
919                                                                 Type target, Location loc,
920                                                                 bool look_for_explicit)
921                 {
922                         Expression mg1 = null, mg2 = null, mg3 = null, mg4 = null;
923                         Expression mg5 = null, mg6 = null, mg7 = null, mg8 = null;
924                         Expression e;
925                         MethodBase method = null;
926                         Type source_type = source.Type;
927
928                         string op_name;
929                         
930                         // If we have a boolean type, we need to check for the True operator
931
932                         // FIXME : How does the False operator come into the picture ?
933                         // FIXME : This doesn't look complete and very correct !
934                         if (target == TypeManager.bool_type)
935                                 op_name = "op_True";
936                         else
937                                 op_name = "op_Implicit";
938                         
939                         mg1 = MemberLookup (ec, source_type, op_name, false, loc);
940
941                         if (source_type.BaseType != null)
942                                 mg2 = MemberLookup (ec, source_type.BaseType, op_name, false, loc);
943                         
944                         mg3 = MemberLookup (ec, target, op_name, false, loc);
945
946                         if (target.BaseType != null)
947                                 mg4 = MemberLookup (ec, target.BaseType, op_name, false, loc);
948
949                         MethodGroupExpr union1 = Invocation.MakeUnionSet (mg1, mg2);
950                         MethodGroupExpr union2 = Invocation.MakeUnionSet (mg3, mg4);
951
952                         MethodGroupExpr union3 = Invocation.MakeUnionSet (union1, union2);
953
954                         MethodGroupExpr union4 = null;
955
956                         if (look_for_explicit) {
957
958                                 op_name = "op_Explicit";
959                                 
960                                 mg5 = MemberLookup (ec, source_type, op_name, false, loc);
961
962                                 if (source_type.BaseType != null)
963                                         mg6 = MemberLookup (ec, source_type.BaseType, op_name, false, loc);
964                                 
965                                 mg7 = MemberLookup (ec, target, op_name, false, loc);
966                                 
967                                 if (target.BaseType != null)
968                                         mg8 = MemberLookup (ec, target.BaseType, op_name, false, loc);
969                                 
970                                 MethodGroupExpr union5 = Invocation.MakeUnionSet (mg5, mg6);
971                                 MethodGroupExpr union6 = Invocation.MakeUnionSet (mg7, mg8);
972
973                                 union4 = Invocation.MakeUnionSet (union5, union6);
974                         }
975                         
976                         MethodGroupExpr union = Invocation.MakeUnionSet (union3, union4);
977
978                         if (union != null) {
979
980                                 Type most_specific_source, most_specific_target;
981
982                                 most_specific_source = FindMostEncompassedType (union, source_type);
983                                 if (most_specific_source == null)
984                                         return null;
985
986                                 most_specific_target = FindMostEncompassingType (union, target);
987                                 if (most_specific_target == null) 
988                                         return null;
989                                 
990                                 int count = 0;
991                                 
992                                 for (int i = union.Methods.Length; i > 0;) {
993                                         i--;
994
995                                         MethodBase mb = union.Methods [i];
996                                         ParameterData pd = Invocation.GetParameterData (mb);
997                                         MethodInfo mi = (MethodInfo) union.Methods [i];
998
999                                         if (pd.ParameterType (0) == most_specific_source &&
1000                                             mi.ReturnType == most_specific_target) {
1001                                                 method = mb;
1002                                                 count++;
1003                                         }
1004                                 }
1005
1006                                 if (method == null || count > 1) {
1007                                         Report.Error (-11, loc, "Ambiguous user defined conversion");
1008                                         return null;
1009                                 }
1010                                 
1011                                 //
1012                                 // This will do the conversion to the best match that we
1013                                 // found.  Now we need to perform an implict standard conversion
1014                                 // if the best match was not the type that we were requested
1015                                 // by target.
1016                                 //
1017                                 if (look_for_explicit)
1018                                         source = ConvertExplicitStandard (ec, source, most_specific_source, loc);
1019                                 else
1020                                         source = ConvertImplicitStandard (ec, source,
1021                                                                           most_specific_source, loc);
1022
1023                                 if (source == null)
1024                                         return null;
1025                                 
1026                                 e =  new UserCast ((MethodInfo) method, source);
1027                                 
1028                                 if (e.Type != target){
1029                                         if (!look_for_explicit)
1030                                                 e = ConvertImplicitStandard (ec, e, target, loc);
1031                                         else
1032                                                 e = ConvertExplicitStandard (ec, e, target, loc);
1033
1034                                         return e;
1035                                 } else
1036                                         return e;
1037                         }
1038                         
1039                         return null;
1040                 }
1041                 
1042                 /// <summary>
1043                 ///   Converts implicitly the resolved expression `expr' into the
1044                 ///   `target_type'.  It returns a new expression that can be used
1045                 ///   in a context that expects a `target_type'. 
1046                 /// </summary>
1047                 static public Expression ConvertImplicit (EmitContext ec, Expression expr,
1048                                                           Type target_type, Location loc)
1049                 {
1050                         Type expr_type = expr.Type;
1051                         Expression e;
1052
1053                         if (expr_type == target_type)
1054                                 return expr;
1055
1056                         if (target_type == null)
1057                                 throw new Exception ("Target type is null");
1058
1059                         e = ImplicitNumericConversion (ec, expr, target_type, loc);
1060                         if (e != null)
1061                                 return e;
1062
1063                         e = ImplicitReferenceConversion (expr, target_type);
1064                         if (e != null)
1065                                 return e;
1066
1067                         e = ImplicitUserConversion (ec, expr, target_type, loc);
1068                         if (e != null)
1069                                 return e;
1070
1071                         if (target_type.IsSubclassOf (TypeManager.enum_type) && expr is IntLiteral){
1072                                 IntLiteral i = (IntLiteral) expr;
1073
1074                                 if (i.Value == 0)
1075                                         return new EmptyCast (expr, target_type);
1076                         }
1077
1078                         return null;
1079                 }
1080
1081                 
1082                 /// <summary>
1083                 ///   Attempts to apply the `Standard Implicit
1084                 ///   Conversion' rules to the expression `expr' into
1085                 ///   the `target_type'.  It returns a new expression
1086                 ///   that can be used in a context that expects a
1087                 ///   `target_type'.
1088                 ///
1089                 ///   This is different from `ConvertImplicit' in that the
1090                 ///   user defined implicit conversions are excluded. 
1091                 /// </summary>
1092                 static public Expression ConvertImplicitStandard (EmitContext ec, Expression expr,
1093                                                                   Type target_type, Location loc)
1094                 {
1095                         Type expr_type = expr.Type;
1096                         Expression e;
1097
1098                         if (expr_type == target_type)
1099                                 return expr;
1100
1101                         e = ImplicitNumericConversion (ec, expr, target_type, loc);
1102                         if (e != null)
1103                                 return e;
1104
1105                         e = ImplicitReferenceConversion (expr, target_type);
1106                         if (e != null)
1107                                 return e;
1108
1109                         if (target_type.IsSubclassOf (TypeManager.enum_type) && expr is IntLiteral){
1110                                 IntLiteral i = (IntLiteral) expr;
1111
1112                                 if (i.Value == 0)
1113                                         return new EmptyCast (expr, target_type);
1114                         }
1115                         return null;
1116                 }
1117
1118                 /// <summary>
1119                 ///   Attemps to perform an implict constant conversion of the IntLiteral
1120                 ///   into a different data type using casts (See Implicit Constant
1121                 ///   Expression Conversions)
1122                 /// </summary>
1123                 static protected Expression TryImplicitIntConversion (Type target_type, IntLiteral il)
1124                 {
1125                         int value = il.Value;
1126                         
1127                         if (target_type == TypeManager.sbyte_type){
1128                                 if (value >= SByte.MinValue && value <= SByte.MaxValue)
1129                                         return new EmptyCast (il, target_type);
1130                         } else if (target_type == TypeManager.byte_type){
1131                                 if (Byte.MinValue >= 0 && value <= Byte.MaxValue)
1132                                         return new EmptyCast (il, target_type);
1133                         } else if (target_type == TypeManager.short_type){
1134                                 if (value >= Int16.MinValue && value <= Int16.MaxValue)
1135                                         return new EmptyCast (il, target_type);
1136                         } else if (target_type == TypeManager.ushort_type){
1137                                 if (value >= UInt16.MinValue && value <= UInt16.MaxValue)
1138                                         return new EmptyCast (il, target_type);
1139                         } else if (target_type == TypeManager.uint32_type){
1140                                 //
1141                                 // we can optimize this case: a positive int32
1142                                 // always fits on a uint32
1143                                 //
1144                                 if (value >= 0)
1145                                         return new EmptyCast (il, target_type);
1146                         } else if (target_type == TypeManager.uint64_type){
1147                                 //
1148                                 // we can optimize this case: a positive int32
1149                                 // always fits on a uint64.  But we need an opcode
1150                                 // to do it.
1151                                 //
1152                                 if (value >= 0)
1153                                         return new OpcodeCast (il, target_type, OpCodes.Conv_I8);
1154                         }
1155
1156                         return null;
1157                 }
1158
1159                 /// <summary>
1160                 ///   Attemptes to implicityly convert `target' into `type', using
1161                 ///   ConvertImplicit.  If there is no implicit conversion, then
1162                 ///   an error is signaled
1163                 /// </summary>
1164                 static public Expression ConvertImplicitRequired (EmitContext ec, Expression source,
1165                                                                   Type target_type, Location loc)
1166                 {
1167                         Expression e;
1168                         
1169                         e = ConvertImplicit (ec, source, target_type, loc);
1170                         if (e != null)
1171                                 return e;
1172                         
1173                         string msg = "Cannot convert implicitly from `"+
1174                                 TypeManager.CSharpName (source.Type) + "' to `" +
1175                                 TypeManager.CSharpName (target_type) + "'";
1176
1177                         Error (29, loc, msg);
1178
1179                         return null;
1180                 }
1181
1182                 /// <summary>
1183                 ///   Performs the explicit numeric conversions
1184                 /// </summary>
1185                 static Expression ConvertNumericExplicit (EmitContext ec, Expression expr,
1186                                                           Type target_type)
1187                 {
1188                         Type expr_type = expr.Type;
1189                         
1190                         if (expr_type == TypeManager.sbyte_type){
1191                                 //
1192                                 // From sbyte to byte, ushort, uint, ulong, char
1193                                 //
1194                                 if (target_type == TypeManager.byte_type)
1195                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_U1);
1196                                 if (target_type == TypeManager.ushort_type)
1197                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_U2);
1198                                 if (target_type == TypeManager.uint32_type)
1199                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_U4);
1200                                 if (target_type == TypeManager.uint64_type)
1201                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_I8);
1202                                 if (target_type == TypeManager.char_type)
1203                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_U2);
1204                         } else if (expr_type == TypeManager.byte_type){
1205                                 //
1206                                 // From byte to sbyte and char
1207                                 //
1208                                 if (target_type == TypeManager.sbyte_type)
1209                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_I1);
1210                                 if (target_type == TypeManager.char_type)
1211                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_U2);
1212                         } else if (expr_type == TypeManager.short_type){
1213                                 //
1214                                 // From short to sbyte, byte, ushort, uint, ulong, char
1215                                 //
1216                                 if (target_type == TypeManager.sbyte_type)
1217                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_I1);
1218                                 if (target_type == TypeManager.byte_type)
1219                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_U1);
1220                                 if (target_type == TypeManager.ushort_type)
1221                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_U2);
1222                                 if (target_type == TypeManager.uint32_type)
1223                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_U4);
1224                                 if (target_type == TypeManager.uint64_type)
1225                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_I8);
1226                                 if (target_type == TypeManager.char_type)
1227                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_U2);
1228                         } else if (expr_type == TypeManager.ushort_type){
1229                                 //
1230                                 // From ushort to sbyte, byte, short, char
1231                                 //
1232                                 if (target_type == TypeManager.sbyte_type)
1233                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_I1);
1234                                 if (target_type == TypeManager.byte_type)
1235                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_U1);
1236                                 if (target_type == TypeManager.short_type)
1237                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_I2);
1238                                 if (target_type == TypeManager.char_type)
1239                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_U2);
1240                         } else if (expr_type == TypeManager.int32_type){
1241                                 //
1242                                 // From int to sbyte, byte, short, ushort, uint, ulong, char
1243                                 //
1244                                 if (target_type == TypeManager.sbyte_type)
1245                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_I1);
1246                                 if (target_type == TypeManager.byte_type)
1247                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_U1);
1248                                 if (target_type == TypeManager.short_type)
1249                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_I2);
1250                                 if (target_type == TypeManager.ushort_type)
1251                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_U2);
1252                                 if (target_type == TypeManager.uint32_type)
1253                                         return new EmptyCast (expr, target_type);
1254                                 if (target_type == TypeManager.uint64_type)
1255                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_I8);
1256                                 if (target_type == TypeManager.char_type)
1257                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_U2);
1258                         } else if (expr_type == TypeManager.uint32_type){
1259                                 //
1260                                 // From uint to sbyte, byte, short, ushort, int, char
1261                                 //
1262                                 if (target_type == TypeManager.sbyte_type)
1263                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_I1);
1264                                 if (target_type == TypeManager.byte_type)
1265                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_U1);
1266                                 if (target_type == TypeManager.short_type)
1267                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_I2);
1268                                 if (target_type == TypeManager.ushort_type)
1269                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_U2);
1270                                 if (target_type == TypeManager.int32_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.int64_type){
1275                                 //
1276                                 // From long to sbyte, byte, short, ushort, int, uint, ulong, char
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                                 if (target_type == TypeManager.ushort_type)
1285                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_U2);
1286                                 if (target_type == TypeManager.int32_type)
1287                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_I4);
1288                                 if (target_type == TypeManager.uint32_type)
1289                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_U4);
1290                                 if (target_type == TypeManager.uint64_type)
1291                                         return new EmptyCast (expr, target_type);
1292                                 if (target_type == TypeManager.char_type)
1293                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_U2);
1294                         } else if (expr_type == TypeManager.uint64_type){
1295                                 //
1296                                 // From ulong to sbyte, byte, short, ushort, int, uint, long, char
1297                                 //
1298                                 if (target_type == TypeManager.sbyte_type)
1299                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_I1);
1300                                 if (target_type == TypeManager.byte_type)
1301                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_U1);
1302                                 if (target_type == TypeManager.short_type)
1303                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_I2);
1304                                 if (target_type == TypeManager.ushort_type)
1305                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_U2);
1306                                 if (target_type == TypeManager.int32_type)
1307                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_I4);
1308                                 if (target_type == TypeManager.uint32_type)
1309                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_U4);
1310                                 if (target_type == TypeManager.int64_type)
1311                                         return new EmptyCast (expr, target_type);
1312                                 if (target_type == TypeManager.char_type)
1313                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_U2);
1314                         } else if (expr_type == TypeManager.char_type){
1315                                 //
1316                                 // From char to sbyte, byte, short
1317                                 //
1318                                 if (target_type == TypeManager.sbyte_type)
1319                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_I1);
1320                                 if (target_type == TypeManager.byte_type)
1321                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_U1);
1322                                 if (target_type == TypeManager.short_type)
1323                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_I2);
1324                         } else if (expr_type == TypeManager.float_type){
1325                                 //
1326                                 // From float to sbyte, byte, short,
1327                                 // ushort, int, uint, long, ulong, char
1328                                 // or decimal
1329                                 //
1330                                 if (target_type == TypeManager.sbyte_type)
1331                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_I1);
1332                                 if (target_type == TypeManager.byte_type)
1333                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_U1);
1334                                 if (target_type == TypeManager.short_type)
1335                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_I2);
1336                                 if (target_type == TypeManager.ushort_type)
1337                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_U2);
1338                                 if (target_type == TypeManager.int32_type)
1339                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_I4);
1340                                 if (target_type == TypeManager.uint32_type)
1341                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_U4);
1342                                 if (target_type == TypeManager.int64_type)
1343                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_I8);
1344                                 if (target_type == TypeManager.uint64_type)
1345                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_U8);
1346                                 if (target_type == TypeManager.char_type)
1347                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_U2);
1348                                 if (target_type == TypeManager.decimal_type)
1349                                         return InternalTypeConstructor (ec, expr, target_type);
1350                         } else if (expr_type == TypeManager.double_type){
1351                                 //
1352                                 // From double to byte, byte, short,
1353                                 // ushort, int, uint, long, ulong,
1354                                 // char, float or decimal
1355                                 //
1356                                 if (target_type == TypeManager.sbyte_type)
1357                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_I1);
1358                                 if (target_type == TypeManager.byte_type)
1359                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_U1);
1360                                 if (target_type == TypeManager.short_type)
1361                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_I2);
1362                                 if (target_type == TypeManager.ushort_type)
1363                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_U2);
1364                                 if (target_type == TypeManager.int32_type)
1365                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_I4);
1366                                 if (target_type == TypeManager.uint32_type)
1367                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_U4);
1368                                 if (target_type == TypeManager.int64_type)
1369                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_I8);
1370                                 if (target_type == TypeManager.uint64_type)
1371                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_U8);
1372                                 if (target_type == TypeManager.char_type)
1373                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_U2);
1374                                 if (target_type == TypeManager.float_type)
1375                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_R4);
1376                                 if (target_type == TypeManager.decimal_type)
1377                                         return InternalTypeConstructor (ec, expr, target_type);
1378                         } 
1379
1380                         // decimal is taken care of by the op_Explicit methods.
1381
1382                         return null;
1383                 }
1384
1385                 /// <summary>
1386                 ///  Returns whether an explicit reference conversion can be performed
1387                 ///  from source_type to target_type
1388                 /// </summary>
1389                 static bool ExplicitReferenceConversionExists (Type source_type, Type target_type)
1390                 {
1391                         bool target_is_value_type = target_type.IsValueType;
1392                         
1393                         if (source_type == target_type)
1394                                 return true;
1395                         
1396                         //
1397                         // From object to any reference type
1398                         //
1399                         if (source_type == TypeManager.object_type && !target_is_value_type)
1400                                 return true;
1401                                         
1402                         //
1403                         // From any class S to any class-type T, provided S is a base class of T
1404                         //
1405                         if (target_type.IsSubclassOf (source_type))
1406                                 return true;
1407
1408                         //
1409                         // From any interface type S to any interface T provided S is not derived from T
1410                         //
1411                         if (source_type.IsInterface && target_type.IsInterface){
1412                                 if (!target_type.IsSubclassOf (source_type))
1413                                         return true;
1414                         }
1415                             
1416                         //
1417                         // From any class type S to any interface T, provides S is not sealed
1418                         // and provided S does not implement T.
1419                         //
1420                         if (target_type.IsInterface && !source_type.IsSealed &&
1421                             !target_type.IsAssignableFrom (source_type))
1422                                 return true;
1423
1424                         //
1425                         // From any interface-type S to to any class type T, provided T is not
1426                         // sealed, or provided T implements S.
1427                         //
1428                         if (source_type.IsInterface &&
1429                             (!target_type.IsSealed || source_type.IsAssignableFrom (target_type)))
1430                                 return true;
1431
1432                         // From an array type S with an element type Se to an array type T with an 
1433                         // element type Te provided all the following are true:
1434                         //     * S and T differe only in element type, in other words, S and T
1435                         //       have the same number of dimensions.
1436                         //     * Both Se and Te are reference types
1437                         //     * An explicit referenc conversions exist from Se to Te
1438                         //
1439                         if (source_type.IsArray && target_type.IsArray) {
1440                                 if (source_type.GetArrayRank () == target_type.GetArrayRank ()) {
1441                                         
1442                                         Type source_element_type = source_type.GetElementType ();
1443                                         Type target_element_type = target_type.GetElementType ();
1444                                         
1445                                         if (!source_element_type.IsValueType && !target_element_type.IsValueType)
1446                                                 if (ExplicitReferenceConversionExists (source_element_type,
1447                                                                                        target_element_type))
1448                                                         return true;
1449                                 }
1450                         }
1451                         
1452
1453                         // From System.Array to any array-type
1454                         if (source_type == TypeManager.array_type &&
1455                             target_type.IsSubclassOf (TypeManager.array_type)){
1456                                 return true;
1457                         }
1458
1459                         //
1460                         // From System delegate to any delegate-type
1461                         //
1462                         if (source_type == TypeManager.delegate_type &&
1463                             target_type.IsSubclassOf (TypeManager.delegate_type))
1464                                 return true;
1465
1466                         //
1467                         // From ICloneable to Array or Delegate types
1468                         //
1469                         if (source_type == TypeManager.icloneable_type &&
1470                             (target_type == TypeManager.array_type ||
1471                              target_type == TypeManager.delegate_type))
1472                                 return true;
1473                         
1474                         return false;
1475                 }
1476
1477                 /// <summary>
1478                 ///   Implements Explicit Reference conversions
1479                 /// </summary>
1480                 static Expression ConvertReferenceExplicit (Expression source, Type target_type)
1481                 {
1482                         Type source_type = source.Type;
1483                         bool target_is_value_type = target_type.IsValueType;
1484                         
1485                         //
1486                         // From object to any reference type
1487                         //
1488                         if (source_type == TypeManager.object_type && !target_is_value_type)
1489                                 return new ClassCast (source, target_type);
1490
1491
1492                         //
1493                         // From any class S to any class-type T, provided S is a base class of T
1494                         //
1495                         if (target_type.IsSubclassOf (source_type))
1496                                 return new ClassCast (source, target_type);
1497
1498                         //
1499                         // From any interface type S to any interface T provided S is not derived from T
1500                         //
1501                         if (source_type.IsInterface && target_type.IsInterface){
1502
1503                                 Type [] ifaces = source_type.GetInterfaces ();
1504
1505                                 if (TypeManager.ImplementsInterface (source_type, target_type))
1506                                         return null;
1507                                 else
1508                                         return new ClassCast (source, target_type);
1509                         }
1510                             
1511                         //
1512                         // From any class type S to any interface T, provides S is not sealed
1513                         // and provided S does not implement T.
1514                         //
1515                         if (target_type.IsInterface && !source_type.IsSealed) {
1516                                 
1517                                 if (TypeManager.ImplementsInterface (source_type, target_type))
1518                                         return null;
1519                                 else
1520                                         return new ClassCast (source, target_type);
1521                                 
1522                         }
1523
1524                         //
1525                         // From any interface-type S to to any class type T, provided T is not
1526                         // sealed, or provided T implements S.
1527                         //
1528                         if (source_type.IsInterface) {
1529
1530                                 if (target_type.IsSealed)
1531                                         return null;
1532                                 
1533                                 if (TypeManager.ImplementsInterface (target_type, source_type))
1534                                         return new ClassCast (source, target_type);
1535                                 else
1536                                         return null;
1537                         }
1538                         
1539                         // From an array type S with an element type Se to an array type T with an 
1540                         // element type Te provided all the following are true:
1541                         //     * S and T differe only in element type, in other words, S and T
1542                         //       have the same number of dimensions.
1543                         //     * Both Se and Te are reference types
1544                         //     * An explicit referenc conversions exist from Se to Te
1545                         //
1546                         if (source_type.IsArray && target_type.IsArray) {
1547                                 if (source_type.GetArrayRank () == target_type.GetArrayRank ()) {
1548                                         
1549                                         Type source_element_type = source_type.GetElementType ();
1550                                         Type target_element_type = target_type.GetElementType ();
1551                                         
1552                                         if (!source_element_type.IsValueType && !target_element_type.IsValueType)
1553                                                 if (ExplicitReferenceConversionExists (source_element_type,
1554                                                                                        target_element_type))
1555                                                         return new ClassCast (source, target_type);
1556                                 }
1557                         }
1558                         
1559
1560                         // From System.Array to any array-type
1561                         if (source_type == TypeManager.array_type &&
1562                             target_type.IsSubclassOf (TypeManager.array_type)){
1563                                 return new ClassCast (source, target_type);
1564                         }
1565
1566                         //
1567                         // From System delegate to any delegate-type
1568                         //
1569                         if (source_type == TypeManager.delegate_type &&
1570                             target_type.IsSubclassOf (TypeManager.delegate_type))
1571                                 return new ClassCast (source, target_type);
1572
1573                         //
1574                         // From ICloneable to Array or Delegate types
1575                         //
1576                         if (source_type == TypeManager.icloneable_type &&
1577                             (target_type == TypeManager.array_type ||
1578                              target_type == TypeManager.delegate_type))
1579                                 return new ClassCast (source, target_type);
1580                         
1581                         return null;
1582                 }
1583                 
1584                 /// <summary>
1585                 ///   Performs an explicit conversion of the expression `expr' whose
1586                 ///   type is expr.Type to `target_type'.
1587                 /// </summary>
1588                 static public Expression ConvertExplicit (EmitContext ec, Expression expr,
1589                                                           Type target_type, Location loc)
1590                 {
1591                         Type expr_type = expr.Type;
1592                         Expression ne = ConvertImplicitStandard (ec, expr, target_type, loc);
1593
1594                         if (ne != null)
1595                                 return ne;
1596
1597                         ne = ConvertNumericExplicit (ec, expr, target_type);
1598                         if (ne != null)
1599                                 return ne;
1600
1601                         //
1602                         // Unboxing conversion.
1603                         //
1604                         if (expr_type == TypeManager.object_type && target_type.IsValueType)
1605                                 return new UnboxCast (expr, target_type);
1606
1607                         //
1608                         // Enum types
1609                         //
1610                         if (expr is EnumLiteral) {
1611                                 Expression e = ((EnumLiteral) expr).Child;
1612                                 
1613                                 return ConvertImplicit (ec, e, target_type, loc);
1614                         }
1615                         
1616                         ne = ConvertReferenceExplicit (expr, target_type);
1617                         if (ne != null)
1618                                 return ne;
1619
1620                         ne = ExplicitUserConversion (ec, expr, target_type, loc);
1621                         if (ne != null)
1622                                 return ne;
1623
1624                         error30 (loc, expr_type, target_type);
1625                         return null;
1626                 }
1627
1628                 /// <summary>
1629                 ///   Same as ConverExplicit, only it doesn't include user defined conversions
1630                 /// </summary>
1631                 static public Expression ConvertExplicitStandard (EmitContext ec, Expression expr,
1632                                                                   Type target_type, Location l)
1633                 {
1634                         Expression ne = ConvertImplicitStandard (ec, expr, target_type, l);
1635
1636                         if (ne != null)
1637                                 return ne;
1638
1639                         ne = ConvertNumericExplicit (ec, expr, target_type);
1640                         if (ne != null)
1641                                 return ne;
1642
1643                         ne = ConvertReferenceExplicit (expr, target_type);
1644                         if (ne != null)
1645                                 return ne;
1646
1647                         error30 (l, expr.Type, target_type);
1648                         return null;
1649                 }
1650
1651                 static string ExprClassName (ExprClass c)
1652                 {
1653                         switch (c){
1654                         case ExprClass.Invalid:
1655                                 return "Invalid";
1656                         case ExprClass.Value:
1657                                 return "value";
1658                         case ExprClass.Variable:
1659                                 return "variable";
1660                         case ExprClass.Namespace:
1661                                 return "namespace";
1662                         case ExprClass.Type:
1663                                 return "type";
1664                         case ExprClass.MethodGroup:
1665                                 return "method group";
1666                         case ExprClass.PropertyAccess:
1667                                 return "property access";
1668                         case ExprClass.EventAccess:
1669                                 return "event access";
1670                         case ExprClass.IndexerAccess:
1671                                 return "indexer access";
1672                         case ExprClass.Nothing:
1673                                 return "null";
1674                         }
1675                         throw new Exception ("Should not happen");
1676                 }
1677                 
1678                 /// <summary>
1679                 ///   Reports that we were expecting `expr' to be of class `expected'
1680                 /// </summary>
1681                 protected void report118 (Location loc, Expression expr, string expected)
1682                 {
1683                         string kind = "Unknown";
1684                         
1685                         if (expr != null)
1686                                 kind = ExprClassName (expr.ExprClass);
1687
1688                         Error (118, loc, "Expression denotes a '" + kind +
1689                                "' where an " + expected + " was expected");
1690                 }
1691
1692                 /// <summary>
1693                 ///   This function tries to reduce the expression performing
1694                 ///   constant folding and common subexpression elimination
1695                 /// </summary>
1696                 static public Expression Reduce (EmitContext ec, Expression e)
1697                 {
1698                         //Console.WriteLine ("Calling reduce");
1699                         return e.Reduce (ec);
1700                 }
1701         }
1702
1703         /// <summary>
1704         ///   This is just a base class for expressions that can
1705         ///   appear on statements (invocations, object creation,
1706         ///   assignments, post/pre increment and decrement).  The idea
1707         ///   being that they would support an extra Emition interface that
1708         ///   does not leave a result on the stack.
1709         /// </summary>
1710         public abstract class ExpressionStatement : Expression {
1711
1712                 /// <summary>
1713                 ///   Requests the expression to be emitted in a `statement'
1714                 ///   context.  This means that no new value is left on the
1715                 ///   stack after invoking this method (constrasted with
1716                 ///   Emit that will always leave a value on the stack).
1717                 /// </summary>
1718                 public abstract void EmitStatement (EmitContext ec);
1719         }
1720
1721         /// <summary>
1722         ///   This kind of cast is used to encapsulate the child
1723         ///   whose type is child.Type into an expression that is
1724         ///   reported to return "return_type".  This is used to encapsulate
1725         ///   expressions which have compatible types, but need to be dealt
1726         ///   at higher levels with.
1727         ///
1728         ///   For example, a "byte" expression could be encapsulated in one
1729         ///   of these as an "unsigned int".  The type for the expression
1730         ///   would be "unsigned int".
1731         ///
1732         /// </summary>
1733         public class EmptyCast : Expression {
1734                 protected Expression child;
1735
1736                 public EmptyCast (Expression child, Type return_type)
1737                 {
1738                         ExprClass = child.ExprClass;
1739                         type = return_type;
1740                         this.child = child;
1741                 }
1742
1743                 public override Expression DoResolve (EmitContext ec)
1744                 {
1745                         // This should never be invoked, we are born in fully
1746                         // initialized state.
1747
1748                         return this;
1749                 }
1750
1751                 public override void Emit (EmitContext ec)
1752                 {
1753                         child.Emit (ec);
1754                 }
1755
1756         }
1757
1758         /// <summary>
1759         ///  This class is used to wrap literals which belong inside Enums
1760         /// </summary>
1761         public class EnumLiteral : Literal {
1762                 public Expression Child;
1763
1764                 public EnumLiteral (Expression child, Type enum_type)
1765                 {
1766                         ExprClass = child.ExprClass;
1767                         this.Child = child;
1768                         type = enum_type;
1769                 }
1770                 
1771                 public override Expression DoResolve (EmitContext ec)
1772                 {
1773                         // This should never be invoked, we are born in fully
1774                         // initialized state.
1775
1776                         return this;
1777                 }
1778
1779                 public override void Emit (EmitContext ec)
1780                 {
1781                         Child.Emit (ec);
1782                 }
1783
1784                 public override object GetValue ()
1785                 {
1786                         return ((Literal) Child).GetValue ();
1787                 }
1788
1789                 public override string AsString ()
1790                 {
1791                         return ((Literal) Child).AsString ();
1792                 }
1793         }
1794
1795         /// <summary>
1796         ///   This kind of cast is used to encapsulate Value Types in objects.
1797         ///
1798         ///   The effect of it is to box the value type emitted by the previous
1799         ///   operation.
1800         /// </summary>
1801         public class BoxedCast : EmptyCast {
1802
1803                 public BoxedCast (Expression expr)
1804                         : base (expr, TypeManager.object_type)
1805                 {
1806                 }
1807
1808                 public override Expression DoResolve (EmitContext ec)
1809                 {
1810                         // This should never be invoked, we are born in fully
1811                         // initialized state.
1812
1813                         return this;
1814                 }
1815
1816                 public override void Emit (EmitContext ec)
1817                 {
1818                         base.Emit (ec);
1819                         ec.ig.Emit (OpCodes.Box, child.Type);
1820                 }
1821         }
1822
1823         public class UnboxCast : EmptyCast {
1824                 public UnboxCast (Expression expr, Type return_type)
1825                         : base (expr, return_type)
1826                 {
1827                 }
1828
1829                 public override Expression DoResolve (EmitContext ec)
1830                 {
1831                         // This should never be invoked, we are born in fully
1832                         // initialized state.
1833
1834                         return this;
1835                 }
1836
1837                 public override void Emit (EmitContext ec)
1838                 {
1839                         Type t = type;
1840                         ILGenerator ig = ec.ig;
1841                         
1842                         base.Emit (ec);
1843                         ig.Emit (OpCodes.Unbox, t);
1844
1845                         //
1846                         // Load the object from the pointer
1847                         //
1848                         if (t == TypeManager.int32_type)
1849                                 ig.Emit (OpCodes.Ldind_I4);
1850                         else if (t == TypeManager.uint32_type)
1851                                 ig.Emit (OpCodes.Ldind_U4);
1852                         else if (t == TypeManager.short_type)
1853                                 ig.Emit (OpCodes.Ldind_I2);
1854                         else if (t == TypeManager.ushort_type)
1855                                 ig.Emit (OpCodes.Ldind_U2);
1856                         else if (t == TypeManager.char_type)
1857                                 ig.Emit (OpCodes.Ldind_U2);
1858                         else if (t == TypeManager.byte_type)
1859                                 ig.Emit (OpCodes.Ldind_U1);
1860                         else if (t == TypeManager.sbyte_type)
1861                                 ig.Emit (OpCodes.Ldind_I1);
1862                         else if (t == TypeManager.uint64_type)
1863                                 ig.Emit (OpCodes.Ldind_I8);
1864                         else if (t == TypeManager.int64_type)
1865                                 ig.Emit (OpCodes.Ldind_I8);
1866                         else if (t == TypeManager.float_type)
1867                                 ig.Emit (OpCodes.Ldind_R4);
1868                         else if (t == TypeManager.double_type)
1869                                 ig.Emit (OpCodes.Ldind_R8);
1870                         else if (t == TypeManager.bool_type)
1871                                 ig.Emit (OpCodes.Ldind_I1);
1872                         else if (t == TypeManager.intptr_type)
1873                                 ig.Emit (OpCodes.Ldind_I);
1874                         else 
1875                                 ig.Emit (OpCodes.Ldobj, t);
1876                 }
1877         }
1878         
1879         /// <summary>
1880         ///   This kind of cast is used to encapsulate a child expression
1881         ///   that can be trivially converted to a target type using one or 
1882         ///   two opcodes.  The opcodes are passed as arguments.
1883         /// </summary>
1884         public class OpcodeCast : EmptyCast {
1885                 OpCode op, op2;
1886                 bool second_valid;
1887                 
1888                 public OpcodeCast (Expression child, Type return_type, OpCode op)
1889                         : base (child, return_type)
1890                         
1891                 {
1892                         this.op = op;
1893                         second_valid = false;
1894                 }
1895
1896                 public OpcodeCast (Expression child, Type return_type, OpCode op, OpCode op2)
1897                         : base (child, return_type)
1898                         
1899                 {
1900                         this.op = op;
1901                         this.op2 = op2;
1902                         second_valid = true;
1903                 }
1904
1905                 public override Expression DoResolve (EmitContext ec)
1906                 {
1907                         // This should never be invoked, we are born in fully
1908                         // initialized state.
1909
1910                         return this;
1911                 }
1912
1913                 public override void Emit (EmitContext ec)
1914                 {
1915                         base.Emit (ec);
1916                         ec.ig.Emit (op);
1917
1918                         if (second_valid)
1919                                 ec.ig.Emit (op2);
1920                 }                       
1921                 
1922         }
1923
1924         /// <summary>
1925         ///   This kind of cast is used to encapsulate a child and cast it
1926         ///   to the class requested
1927         /// </summary>
1928         public class ClassCast : EmptyCast {
1929                 public ClassCast (Expression child, Type return_type)
1930                         : base (child, return_type)
1931                         
1932                 {
1933                 }
1934
1935                 public override Expression DoResolve (EmitContext ec)
1936                 {
1937                         // This should never be invoked, we are born in fully
1938                         // initialized state.
1939
1940                         return this;
1941                 }
1942
1943                 public override void Emit (EmitContext ec)
1944                 {
1945                         base.Emit (ec);
1946
1947                         ec.ig.Emit (OpCodes.Castclass, type);
1948                 }                       
1949                 
1950         }
1951         
1952         /// <summary>
1953         ///   SimpleName expressions are initially formed of a single
1954         ///   word and it only happens at the beginning of the expression.
1955         /// </summary>
1956         ///
1957         /// <remarks>
1958         ///   The expression will try to be bound to a Field, a Method
1959         ///   group or a Property.  If those fail we pass the name to our
1960         ///   caller and the SimpleName is compounded to perform a type
1961         ///   lookup.  The idea behind this process is that we want to avoid
1962         ///   creating a namespace map from the assemblies, as that requires
1963         ///   the GetExportedTypes function to be called and a hashtable to
1964         ///   be constructed which reduces startup time.  If later we find
1965         ///   that this is slower, we should create a `NamespaceExpr' expression
1966         ///   that fully participates in the resolution process. 
1967         ///   
1968         ///   For example `System.Console.WriteLine' is decomposed into
1969         ///   MemberAccess (MemberAccess (SimpleName ("System"), "Console"), "WriteLine")
1970         ///   
1971         ///   The first SimpleName wont produce a match on its own, so it will
1972         ///   be turned into:
1973         ///   MemberAccess (SimpleName ("System.Console"), "WriteLine").
1974         ///   
1975         ///   System.Console will produce a TypeExpr match.
1976         ///   
1977         ///   The downside of this is that we might be hitting `LookupType' too many
1978         ///   times with this scheme.
1979         /// </remarks>
1980         public class SimpleName : Expression {
1981                 public readonly string Name;
1982                 public readonly Location Location;
1983                 
1984                 public SimpleName (string name, Location l)
1985                 {
1986                         Name = name;
1987                         Location = l;
1988                 }
1989
1990                 public static void Error120 (Location l, string name)
1991                 {
1992                         Report.Error (
1993                                 120, l,
1994                                 "An object reference is required " +
1995                                 "for the non-static field `"+name+"'");
1996                 }
1997                 
1998                 //
1999                 // Checks whether we are trying to access an instance
2000                 // property, method or field from a static body.
2001                 //
2002                 Expression MemberStaticCheck (Expression e)
2003                 {
2004                         if (e is FieldExpr){
2005                                 FieldInfo fi = ((FieldExpr) e).FieldInfo;
2006                                 
2007                                 if (!fi.IsStatic){
2008                                         Error120 (Location, Name);
2009                                         return null;
2010                                 }
2011                         } else if (e is MethodGroupExpr){
2012                                 MethodGroupExpr mg = (MethodGroupExpr) e;
2013
2014                                 if (!mg.RemoveInstanceMethods ()){
2015                                         Error120 (Location, mg.Methods [0].Name);
2016                                         return null;
2017                                 }
2018                                 return e;
2019                         } else if (e is PropertyExpr){
2020                                 if (!((PropertyExpr) e).IsStatic){
2021                                         Error120 (Location, Name);
2022                                         return null;
2023                                 }
2024                         }
2025
2026                         return e;
2027                 }
2028                 
2029                 // <remarks>
2030                 //   7.5.2: Simple Names. 
2031                 //
2032                 //   Local Variables and Parameters are handled at
2033                 //   parse time, so they never occur as SimpleNames.
2034                 // </remarks>
2035                 public override Expression DoResolve (EmitContext ec)
2036                 {
2037                         Expression e;
2038
2039                         //
2040                         // Stage 1: Performed by the parser (binding to local or parameters).
2041                         //
2042
2043                         //
2044                         // Stage 2: Lookup members
2045                         //
2046                         e = MemberLookup (ec, ec.TypeContainer.TypeBuilder, Name, true, Location);
2047                         if (e == null){
2048                                 //
2049                                 // Stage 3: Lookup symbol in the various namespaces. 
2050                                 // 
2051                                 Type t;
2052                                 
2053                                 if ((t = ec.TypeContainer.LookupType (Name, true)) != null)
2054                                         return new TypeExpr (t);
2055
2056                                 //
2057                                 // Stage 3 part b: Lookup up if we are an alias to a type
2058                                 // or a namespace.
2059                                 //
2060                                 // Since we are cheating: we only do the Alias lookup for
2061                                 // namespaces if the name does not include any dots in it
2062                                 //
2063                                 
2064                                 // IMPLEMENT ME.  Read mcs/mcs/TODO for ideas, or rewrite
2065                                 // using NamespaceExprs (dunno how that fixes the alias
2066                                 // per-file though).
2067                                 
2068                                 // No match, maybe our parent can compose us
2069                                 // into something meaningful.
2070                                 //
2071                                 return this;
2072                         }
2073
2074                         // Step 2, continues here.
2075                         if (e is TypeExpr)
2076                                 return e;
2077
2078                         if (e is FieldExpr){
2079                                 FieldExpr fe = (FieldExpr) e;
2080                                 
2081                                 if (!fe.FieldInfo.IsStatic)
2082                                         fe.InstanceExpression = new This (Location.Null);
2083                         }                               
2084
2085                         if (ec.IsStatic)
2086                                 return MemberStaticCheck (e);
2087                         else
2088                                 return e;
2089                 }
2090
2091                 public override void Emit (EmitContext ec)
2092                 {
2093                         //
2094                         // If this is ever reached, then we failed to
2095                         // find the name as a namespace
2096                         //
2097
2098                         Error (103, Location, "The name `" + Name +
2099                                "' does not exist in the class `" +
2100                                ec.TypeContainer.Name + "'");
2101                 }
2102         }
2103         
2104         /// <summary>
2105         ///   Fully resolved expression that evaluates to a type
2106         /// </summary>
2107         public class TypeExpr : Expression {
2108                 public TypeExpr (Type t)
2109                 {
2110                         Type = t;
2111                         eclass = ExprClass.Type;
2112                 }
2113
2114                 override public Expression DoResolve (EmitContext ec)
2115                 {
2116                         return this;
2117                 }
2118
2119                 override public void Emit (EmitContext ec)
2120                 {
2121                         throw new Exception ("Implement me");
2122                 }
2123         }
2124
2125         /// <summary>
2126         ///   MethodGroup Expression.
2127         ///  
2128         ///   This is a fully resolved expression that evaluates to a type
2129         /// </summary>
2130         public class MethodGroupExpr : Expression {
2131                 public MethodBase [] Methods;
2132                 Expression instance_expression = null;
2133                 
2134                 public MethodGroupExpr (MemberInfo [] mi)
2135                 {
2136                         Methods = new MethodBase [mi.Length];
2137                         mi.CopyTo (Methods, 0);
2138                         eclass = ExprClass.MethodGroup;
2139                 }
2140
2141                 public MethodGroupExpr (ArrayList l)
2142                 {
2143                         Methods = new MethodBase [l.Count];
2144
2145                         l.CopyTo (Methods, 0);
2146                         eclass = ExprClass.MethodGroup;
2147                 }
2148                 
2149                 //
2150                 // `A method group may have associated an instance expression' 
2151                 // 
2152                 public Expression InstanceExpression {
2153                         get {
2154                                 return instance_expression;
2155                         }
2156
2157                         set {
2158                                 instance_expression = value;
2159                         }
2160                 }
2161                 
2162                 override public Expression DoResolve (EmitContext ec)
2163                 {
2164                         return this;
2165                 }
2166
2167                 override public void Emit (EmitContext ec)
2168                 {
2169                         throw new Exception ("This should never be reached");
2170                 }
2171
2172                 bool RemoveMethods (bool keep_static)
2173                 {
2174                         ArrayList smethods = new ArrayList ();
2175                         int top = Methods.Length;
2176                         int i;
2177                         
2178                         for (i = 0; i < top; i++){
2179                                 MethodBase mb = Methods [i];
2180
2181                                 if (mb.IsStatic == keep_static)
2182                                         smethods.Add (mb);
2183                         }
2184
2185                         if (smethods.Count == 0)
2186                                 return false;
2187
2188                         Methods = new MethodBase [smethods.Count];
2189                         smethods.CopyTo (Methods, 0);
2190
2191                         return true;
2192                 }
2193                 
2194                 /// <summary>
2195                 ///   Removes any instance methods from the MethodGroup, returns
2196                 ///   false if the resulting set is empty.
2197                 /// </summary>
2198                 public bool RemoveInstanceMethods ()
2199                 {
2200                         return RemoveMethods (true);
2201                 }
2202
2203                 /// <summary>
2204                 ///   Removes any static methods from the MethodGroup, returns
2205                 ///   false if the resulting set is empty.
2206                 /// </summary>
2207                 public bool RemoveStaticMethods ()
2208                 {
2209                         return RemoveMethods (false);
2210                 }
2211         }
2212
2213         /// <summary>
2214         ///   Fully resolved expression that evaluates to a Field
2215         /// </summary>
2216         public class FieldExpr : Expression, IAssignMethod, IMemoryLocation {
2217                 public readonly FieldInfo FieldInfo;
2218                 public Expression InstanceExpression;
2219                 Location loc;
2220                 
2221                 public FieldExpr (FieldInfo fi, Location l)
2222                 {
2223                         FieldInfo = fi;
2224                         eclass = ExprClass.Variable;
2225                         type = fi.FieldType;
2226                         loc = l;
2227                 }
2228
2229                 override public Expression DoResolve (EmitContext ec)
2230                 {
2231                         if (!FieldInfo.IsStatic){
2232                                 if (InstanceExpression == null){
2233                                         throw new Exception ("non-static FieldExpr without instance var\n" +
2234                                                              "You have to assign the Instance variable\n" +
2235                                                              "Of the FieldExpr to set this\n");
2236                                 }
2237
2238                                 InstanceExpression = InstanceExpression.Resolve (ec);
2239                                 if (InstanceExpression == null)
2240                                         return null;
2241                                 
2242                         }
2243                         return this;
2244                 }
2245
2246                 public Expression DoResolveLValue (EmitContext ec)
2247                 {
2248                         if (!FieldInfo.IsInitOnly)
2249                                 return this;
2250
2251                         //
2252                         // InitOnly fields can only be assigned in constructors
2253                         //
2254
2255                         if (ec.IsConstructor)
2256                                 return this;
2257
2258                         Report.Error (191, loc,
2259                                       "Readonly field can not be assigned outside " +
2260                                       "of constructor or variable initializer");
2261                         
2262                         return null;
2263                 }
2264
2265                 override public void Emit (EmitContext ec)
2266                 {
2267                         ILGenerator ig = ec.ig;
2268
2269                         if (FieldInfo.IsStatic)
2270                                 ig.Emit (OpCodes.Ldsfld, FieldInfo);
2271                         else {
2272                                 InstanceExpression.Emit (ec);
2273                                 
2274                                 ig.Emit (OpCodes.Ldfld, FieldInfo);
2275                         }
2276                 }
2277
2278                 public void EmitAssign (EmitContext ec, Expression source)
2279                 {
2280                         bool is_static = FieldInfo.IsStatic;
2281
2282                         if (!is_static)
2283                                 InstanceExpression.Emit (ec);
2284                         source.Emit (ec);
2285                         
2286                         if (is_static)
2287                                 ec.ig.Emit (OpCodes.Stsfld, FieldInfo);
2288                         else
2289                                 ec.ig.Emit (OpCodes.Stfld, FieldInfo);
2290                         
2291                 }
2292                 
2293                 public void AddressOf (EmitContext ec)
2294                 {
2295                         if (FieldInfo.IsStatic)
2296                                 ec.ig.Emit (OpCodes.Ldsflda, FieldInfo);
2297                         else {
2298                                 InstanceExpression.Emit (ec);
2299                                 ec.ig.Emit (OpCodes.Ldflda, FieldInfo);
2300                         }
2301                 }
2302         }
2303         
2304         /// <summary>
2305         ///   Expression that evaluates to a Property.  The Assign class
2306         ///   might set the `Value' expression if we are in an assignment.
2307         ///
2308         ///   This is not an LValue because we need to re-write the expression, we
2309         ///   can not take data from the stack and store it.  
2310         /// </summary>
2311         public class PropertyExpr : ExpressionStatement, IAssignMethod {
2312                 public readonly PropertyInfo PropertyInfo;
2313                 public readonly bool IsStatic;
2314                 MethodInfo [] Accessors;
2315                 Location loc;
2316                 
2317                 Expression instance_expr;
2318                 
2319                 public PropertyExpr (PropertyInfo pi, Location l)
2320                 {
2321                         PropertyInfo = pi;
2322                         eclass = ExprClass.PropertyAccess;
2323                         IsStatic = false;
2324                         loc = l;
2325                         Accessors = TypeManager.GetAccessors (pi);
2326
2327                         if (Accessors != null)
2328                                 for (int i = 0; i < Accessors.Length; i++){
2329                                         if (Accessors [i] != null)
2330                                                 if (Accessors [i].IsStatic)
2331                                                         IsStatic = true;
2332                                 }
2333                         else
2334                                 Accessors = new MethodInfo [2];
2335                         
2336                         type = pi.PropertyType;
2337                 }
2338
2339                 //
2340                 // The instance expression associated with this expression
2341                 //
2342                 public Expression InstanceExpression {
2343                         set {
2344                                 instance_expr = value;
2345                         }
2346
2347                         get {
2348                                 return instance_expr;
2349                         }
2350                 }
2351
2352                 public bool VerifyAssignable ()
2353                 {
2354                         if (!PropertyInfo.CanWrite){
2355                                 Report.Error (200, loc, 
2356                                               "The property `" + PropertyInfo.Name +
2357                                               "' can not be assigned to, as it has not set accessor");
2358                                 return false;
2359                         }
2360
2361                         return true;
2362                 }
2363
2364                 override public Expression DoResolve (EmitContext ec)
2365                 {
2366                         if (!PropertyInfo.CanRead){
2367                                 Report.Error (154, loc, 
2368                                               "The property `" + PropertyInfo.Name +
2369                                               "' can not be used in " +
2370                                               "this context because it lacks a get accessor");
2371                                 return null;
2372                         }
2373
2374                         return this;
2375                 }
2376
2377                 override public void Emit (EmitContext ec)
2378                 {
2379                         Invocation.EmitCall (ec, IsStatic, instance_expr, Accessors [0], null);
2380                         
2381                 }
2382
2383                 //
2384                 // Implements the IAssignMethod interface for assignments
2385                 //
2386                 public void EmitAssign (EmitContext ec, Expression source)
2387                 {
2388                         Argument arg = new Argument (source, Argument.AType.Expression);
2389                         ArrayList args = new ArrayList ();
2390
2391                         args.Add (arg);
2392                         Invocation.EmitCall (ec, IsStatic, instance_expr, Accessors [1], args);
2393                 }
2394
2395                 override public void EmitStatement (EmitContext ec)
2396                 {
2397                         Emit (ec);
2398                         ec.ig.Emit (OpCodes.Pop);
2399                 }
2400         }
2401
2402         /// <summary>
2403         ///   Fully resolved expression that evaluates to a Expression
2404         /// </summary>
2405         public class EventExpr : Expression {
2406                 public readonly EventInfo EventInfo;
2407                 Location loc;
2408                 
2409                 public EventExpr (EventInfo ei, Location loc)
2410                 {
2411                         EventInfo = ei;
2412                         this.loc = loc;
2413                         eclass = ExprClass.EventAccess;
2414                 }
2415
2416                 override public Expression DoResolve (EmitContext ec)
2417                 {
2418                         // We are born in resolved state. 
2419                         return this;
2420                 }
2421
2422                 override public void Emit (EmitContext ec)
2423                 {
2424                         throw new Exception ("Implement me");
2425                         // FIXME: Implement.
2426                 }
2427         }
2428         
2429 }