2002-05-06 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         //
40         // This is just as a hint to AddressOf of what will be done with the
41         // address.
42         [Flags]
43         public enum AddressOp {
44                 Store = 1,
45                 Load  = 2,
46                 LoadStore = 3
47         };
48         
49         /// <summary>
50         ///   This interface is implemented by variables
51         /// </summary>
52         public interface IMemoryLocation {
53                 /// <summary>
54                 ///   The AddressOf method should generate code that loads
55                 ///   the address of the object and leaves it on the stack.
56                 ///
57                 ///   The `mode' argument is used to notify the expression
58                 ///   of whether this will be used to read from the address or
59                 ///   write to the address.
60                 ///
61                 ///   This is just a hint that can be used to provide good error
62                 ///   reporting, and should have no other side effects. 
63                 /// </summary>
64                 void AddressOf (EmitContext ec, AddressOp mode);
65         }
66
67         /// <remarks>
68         ///   Base class for expressions
69         /// </remarks>
70         public abstract class Expression {
71                 public ExprClass eclass;
72                 protected Type      type;
73                 
74                 public Type Type {
75                         get {
76                                 return type;
77                         }
78
79                         set {
80                                 type = value;
81                         }
82                 }
83
84                 /// <summary>
85                 ///   Utility wrapper routine for Error, just to beautify the code
86                 /// </summary>
87                 static protected void Error (int error, string s)
88                 {
89                         Report.Error (error, s);
90                 }
91
92                 static protected void Error (int error, Location loc, string s)
93                 {
94                         Report.Error (error, loc, s);
95                 }
96                 
97                 /// <summary>
98                 ///   Utility wrapper routine for Warning, just to beautify the code
99                 /// </summary>
100                 static protected void Warning (int warning, string s)
101                 {
102                         Report.Warning (warning, s);
103                 }
104
105                 static public void Error_CannotConvertType (Location loc, Type source, Type target)
106                 {
107                         Report.Error (30, loc, "Cannot convert type '" +
108                                       TypeManager.CSharpName (source) + "' to '" +
109                                       TypeManager.CSharpName (target) + "'");
110                 }
111
112                 /// <summary>
113                 ///   Performs semantic analysis on the Expression
114                 /// </summary>
115                 ///
116                 /// <remarks>
117                 ///   The Resolve method is invoked to perform the semantic analysis
118                 ///   on the node.
119                 ///
120                 ///   The return value is an expression (it can be the
121                 ///   same expression in some cases) or a new
122                 ///   expression that better represents this node.
123                 ///   
124                 ///   For example, optimizations of Unary (LiteralInt)
125                 ///   would return a new LiteralInt with a negated
126                 ///   value.
127                 ///   
128                 ///   If there is an error during semantic analysis,
129                 ///   then an error should be reported (using Report)
130                 ///   and a null value should be returned.
131                 ///   
132                 ///   There are two side effects expected from calling
133                 ///   Resolve(): the the field variable "eclass" should
134                 ///   be set to any value of the enumeration
135                 ///   `ExprClass' and the type variable should be set
136                 ///   to a valid type (this is the type of the
137                 ///   expression).
138                 /// </remarks>
139                 public abstract Expression DoResolve (EmitContext ec);
140
141                 public virtual Expression DoResolveLValue (EmitContext ec, Expression right_side)
142                 {
143                         return DoResolve (ec);
144                 }
145                 
146                 /// <summary>
147                 ///   Resolves an expression and performs semantic analysis on it.
148                 /// </summary>
149                 ///
150                 /// <remarks>
151                 ///   Currently Resolve wraps DoResolve to perform sanity
152                 ///   checking and assertion checking on what we expect from Resolve.
153                 /// </remarks>
154                 public Expression Resolve (EmitContext ec)
155                 {
156                         Expression e = DoResolve (ec);
157
158                         if (e != null){
159
160                                 if (e is SimpleName){
161                                         SimpleName s = (SimpleName) e;
162
163                                         Report.Error (
164                                                       103, s.Location,
165                                                       "The name `" + s.Name + "' could not be found in `" +
166                                                       ec.DeclSpace.Name + "'");
167                                         return null;
168                                 }
169                                 
170                                 if (e.eclass == ExprClass.Invalid)
171                                         throw new Exception ("Expression " + e.GetType () +
172                                                              " ExprClass is Invalid after resolve");
173
174                                 if (e.eclass != ExprClass.MethodGroup)
175                                         if (e.type == null)
176                                                 throw new Exception (
177                                                         "Expression " + e.GetType () +
178                                                         " did not set its type after Resolve\n" +
179                                                         "called from: " + this.GetType ());
180                         }
181
182                         return e;
183                 }
184
185                 /// <summary>
186                 ///   Performs expression resolution and semantic analysis, but
187                 ///   allows SimpleNames to be returned.
188                 /// </summary>
189                 ///
190                 /// <remarks>
191                 ///   This is used by MemberAccess to construct long names that can not be
192                 ///   partially resolved (namespace-qualified names for example).
193                 /// </remarks>
194                 public Expression ResolveWithSimpleName (EmitContext ec)
195                 {
196                         Expression e;
197
198                         if (this is SimpleName)
199                                 e = ((SimpleName) this).DoResolveAllowStatic (ec);
200                         else 
201                                 e = DoResolve (ec);
202
203                         if (e != null){
204                                 if (e is SimpleName)
205                                         return e;
206
207                                 if (e.eclass == ExprClass.Invalid)
208                                         throw new Exception ("Expression " + e +
209                                                              " ExprClass is Invalid after resolve");
210
211                                 if (e.eclass != ExprClass.MethodGroup)
212                                         if (e.type == null)
213                                                 throw new Exception ("Expression " + e +
214                                                                      " did not set its type after Resolve");
215                         }
216
217                         return e;
218                 }
219                 
220                 /// <summary>
221                 ///   Resolves an expression for LValue assignment
222                 /// </summary>
223                 ///
224                 /// <remarks>
225                 ///   Currently ResolveLValue wraps DoResolveLValue to perform sanity
226                 ///   checking and assertion checking on what we expect from Resolve
227                 /// </remarks>
228                 public Expression ResolveLValue (EmitContext ec, Expression right_side)
229                 {
230                         Expression e = DoResolveLValue (ec, right_side);
231
232                         if (e != null){
233                                 if (e is SimpleName){
234                                         SimpleName s = (SimpleName) e;
235
236                                         Report.Error (
237                                                 103, s.Location,
238                                                 "The name `" + s.Name + "' could not be found in `" +
239                                                 ec.DeclSpace.Name + "'");
240                                         return null;
241                                 }
242
243                                 if (e.eclass == ExprClass.Invalid)
244                                         throw new Exception ("Expression " + e +
245                                                              " ExprClass is Invalid after resolve");
246
247                                 if (e.eclass != ExprClass.MethodGroup)
248                                         if (e.type == null)
249                                                 throw new Exception ("Expression " + e +
250                                                                      " did not set its type after Resolve");
251                         }
252
253                         return e;
254                 }
255                 
256                 /// <summary>
257                 ///   Emits the code for the expression
258                 /// </summary>
259                 ///
260                 /// <remarks>
261                 ///   The Emit method is invoked to generate the code
262                 ///   for the expression.  
263                 /// </remarks>
264                 public abstract void Emit (EmitContext ec);
265
266                 /// <summary>
267                 ///   Protected constructor.  Only derivate types should
268                 ///   be able to be created
269                 /// </summary>
270
271                 protected Expression ()
272                 {
273                         eclass = ExprClass.Invalid;
274                         type = null;
275                 }
276
277                 /// <summary>
278                 ///   Returns a literalized version of a literal FieldInfo
279                 /// </summary>
280                 ///
281                 /// <remarks>
282                 ///   The possible return values are:
283                 ///      IntConstant, UIntConstant
284                 ///      LongLiteral, ULongConstant
285                 ///      FloatConstant, DoubleConstant
286                 ///      StringConstant
287                 ///
288                 ///   The value returned is already resolved.
289                 /// </remarks>
290                 public static Constant Constantify (object v, Type t)
291                 {
292                         if (t == TypeManager.int32_type)
293                                 return new IntConstant ((int) v);
294                         else if (t == TypeManager.uint32_type)
295                                 return new UIntConstant ((uint) v);
296                         else if (t == TypeManager.int64_type)
297                                 return new LongConstant ((long) v);
298                         else if (t == TypeManager.uint64_type)
299                                 return new ULongConstant ((ulong) v);
300                         else if (t == TypeManager.float_type)
301                                 return new FloatConstant ((float) v);
302                         else if (t == TypeManager.double_type)
303                                 return new DoubleConstant ((double) v);
304                         else if (t == TypeManager.string_type)
305                                 return new StringConstant ((string) v);
306                         else if (t == TypeManager.short_type)
307                                 return new ShortConstant ((short)v);
308                         else if (t == TypeManager.ushort_type)
309                                 return new UShortConstant ((ushort)v);
310                         else if (t == TypeManager.sbyte_type)
311                                 return new SByteConstant (((sbyte)v));
312                         else if (t == TypeManager.byte_type)
313                                 return new ByteConstant ((byte)v);
314                         else if (t == TypeManager.char_type)
315                                 return new CharConstant ((char)v);
316                         else if (TypeManager.IsEnumType (t)){
317                                 Expression e = Constantify (v, v.GetType ());
318
319                                 return new EnumConstant ((Constant) e, t);
320                         } else
321                                 throw new Exception ("Unknown type for constant (" + t +
322                                                      "), details: " + v);
323                 }
324
325                 /// <summary>
326                 ///   Returns a fully formed expression after a MemberLookup
327                 /// </summary>
328                 public static Expression ExprClassFromMemberInfo (EmitContext ec, MemberInfo mi, Location loc)
329                 {
330                         if (mi is EventInfo)
331                                 return new EventExpr ((EventInfo) mi, loc);
332                         else if (mi is FieldInfo)
333                                 return new FieldExpr ((FieldInfo) mi, loc);
334                         else if (mi is PropertyInfo)
335                                 return new PropertyExpr ((PropertyInfo) mi, loc);
336                         else if (mi is Type){
337                                 return new TypeExpr ((System.Type) mi);
338                         }
339
340                         return null;
341                 }
342
343                 //
344                 // FIXME: Probably implement a cache for (t,name,current_access_set)?
345                 //
346                 // This code could use some optimizations, but we need to do some
347                 // measurements.  For example, we could use a delegate to `flag' when
348                 // something can not any longer be a method-group (because it is something
349                 // else).
350                 //
351                 // Return values:
352                 //     If the return value is an Array, then it is an array of
353                 //     MethodBases
354                 //   
355                 //     If the return value is an MemberInfo, it is anything, but a Method
356                 //
357                 //     null on error.
358                 //
359                 // FIXME: When calling MemberLookup inside an `Invocation', we should pass
360                 // the arguments here and have MemberLookup return only the methods that
361                 // match the argument count/type, unlike we are doing now (we delay this
362                 // decision).
363                 //
364                 // This is so we can catch correctly attempts to invoke instance methods
365                 // from a static body (scan for error 120 in ResolveSimpleName).
366                 //
367                 //
368                 // FIXME: Potential optimization, have a static ArrayList
369                 //
370
371                 public static Expression MemberLookup (EmitContext ec, Type t, string name,
372                                                        MemberTypes mt, BindingFlags bf, Location loc)
373                 {
374                         MemberInfo [] mi = TypeManager.MemberLookup (ec.ContainerType, t, mt, bf, name);
375
376                         if (mi == null)
377                                 return null;
378
379                         int count = mi.Length;
380
381                         if (count > 1)
382                                 return new MethodGroupExpr (mi, loc);
383
384                         if (mi [0] is MethodBase)
385                                 return new MethodGroupExpr (mi, loc);
386
387                         return ExprClassFromMemberInfo (ec, mi [0], loc);
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 AllBindingFlags =
399                         BindingFlags.Public |
400                         BindingFlags.Static |
401                         BindingFlags.Instance;
402
403                 public static Expression MemberLookup (EmitContext ec, Type t, string name, Location loc)
404                 {
405                         return MemberLookup (ec, t, name, AllMemberTypes, AllBindingFlags, loc);
406                 }
407
408                 public static Expression MethodLookup (EmitContext ec, Type t, string name, Location loc)
409                 {
410                         return MemberLookup (ec, t, name, MemberTypes.Method, AllBindingFlags, loc);
411                 }
412
413                 /// <summary>
414                 ///   This is a wrapper for MemberLookup that is not used to "probe", but
415                 ///   to find a final definition.  If the final definition is not found, we
416                 ///   look for private members and display a useful debugging message if we
417                 ///   find it.
418                 /// </summary>
419                 public static Expression MemberLookupFinal (EmitContext ec, Type t, string name, 
420                                                             Location loc)
421                 {
422                         Expression e;
423
424                         e = MemberLookup (ec, t, name, AllMemberTypes, AllBindingFlags, loc);
425
426                         if (e != null)
427                                 return e;
428                         
429                         e = MemberLookup (ec, t, name, AllMemberTypes,
430                                           AllBindingFlags | BindingFlags.NonPublic, loc);
431                         if (e == null){
432                                 Report.Error (
433                                         117, loc, "`" + t + "' does not contain a definition " +
434                                         "for `" + name + "'");
435                         } else {
436                                 Report.Error (
437                                         122, loc, "`" + t + "." + name +
438                                         "' is inaccessible due to its protection level");
439                         }
440                         
441                         return null;
442                 }
443                 
444                 static EmptyExpression MyEmptyExpr;
445                 static public Expression ImplicitReferenceConversion (Expression expr, Type target_type)
446                 {
447                         Type expr_type = expr.Type;
448
449                         if (expr_type == null && expr.eclass == ExprClass.MethodGroup){
450                                 // if we are a method group, emit a warning
451
452                                 expr.Emit (null);
453                         }
454                         
455                         if (target_type == TypeManager.object_type) {
456                                 //
457                                 // A pointer type cannot be converted to object
458                                 // 
459                                 if (expr_type.IsPointer)
460                                         return null;
461
462                                 if (expr_type.IsValueType)
463                                         return new BoxedCast (expr);
464                                 if (expr_type.IsClass || expr_type.IsInterface)
465                                         return new EmptyCast (expr, target_type);
466                         } else if (expr_type.IsSubclassOf (target_type)) {
467                                 return new EmptyCast (expr, target_type);
468                         } else {
469
470                                 // This code is kind of mirrored inside StandardConversionExists
471                                 // with the small distinction that we only probe there
472                                 //
473                                 // Always ensure that the code here and there is in sync
474                                 
475                                 // from the null type to any reference-type.
476                                 if (expr is NullLiteral && !target_type.IsValueType)
477                                         return new EmptyCast (expr, target_type);
478
479                                 // from any class-type S to any interface-type T.
480                                 if (expr_type.IsClass && target_type.IsInterface) {
481                                         if (TypeManager.ImplementsInterface (expr_type, target_type))
482                                                 return new EmptyCast (expr, target_type);
483                                         else
484                                                 return null;
485                                 }
486
487                                 // from any interface type S to interface-type T.
488                                 if (expr_type.IsInterface && target_type.IsInterface) {
489
490                                         if (TypeManager.ImplementsInterface (expr_type, target_type))
491                                                 return new EmptyCast (expr, target_type);
492                                         else
493                                                 return null;
494                                 }
495                                 
496                                 // from an array-type S to an array-type of type T
497                                 if (expr_type.IsArray && target_type.IsArray) {
498                                         if (expr_type.GetArrayRank () == target_type.GetArrayRank ()) {
499
500                                                 Type expr_element_type = expr_type.GetElementType ();
501
502                                                 if (MyEmptyExpr == null)
503                                                         MyEmptyExpr = new EmptyExpression ();
504                                                 
505                                                 MyEmptyExpr.SetType (expr_element_type);
506                                                 Type target_element_type = target_type.GetElementType ();
507
508                                                 if (!expr_element_type.IsValueType && !target_element_type.IsValueType)
509                                                         if (StandardConversionExists (MyEmptyExpr,
510                                                                                       target_element_type))
511                                                                 return new EmptyCast (expr, target_type);
512                                         }
513                                 }
514                                 
515                                 
516                                 // from an array-type to System.Array
517                                 if (expr_type.IsArray && target_type == TypeManager.array_type)
518                                         return new EmptyCast (expr, target_type);
519                                 
520                                 // from any delegate type to System.Delegate
521                                 if (expr_type.IsSubclassOf (TypeManager.delegate_type) &&
522                                     target_type == TypeManager.delegate_type)
523                                         return new EmptyCast (expr, target_type);
524                                         
525                                 // from any array-type or delegate type into System.ICloneable.
526                                 if (expr_type.IsArray || expr_type.IsSubclassOf (TypeManager.delegate_type))
527                                         if (target_type == TypeManager.icloneable_type)
528                                                 return new EmptyCast (expr, target_type);
529                                 
530                                 return null;
531
532                         }
533                         
534                         return null;
535                 }
536
537                 /// <summary>
538                 ///   Handles expressions like this: decimal d; d = 1;
539                 ///   and changes them into: decimal d; d = new System.Decimal (1);
540                 /// </summary>
541                 static Expression InternalTypeConstructor (EmitContext ec, Expression expr, Type target)
542                 {
543                         ArrayList args = new ArrayList ();
544
545                         args.Add (new Argument (expr, Argument.AType.Expression));
546
547                         Expression ne = new New (target.FullName, args,
548                                                  new Location (-1));
549
550                         return ne.Resolve (ec);
551                 }
552
553                 /// <summary>
554                 ///   Implicit Numeric Conversions.
555                 ///
556                 ///   expr is the expression to convert, returns a new expression of type
557                 ///   target_type or null if an implicit conversion is not possible.
558                 /// </summary>
559                 static public Expression ImplicitNumericConversion (EmitContext ec, Expression expr,
560                                                                     Type target_type, Location loc)
561                 {
562                         Type expr_type = expr.Type;
563                         
564                         //
565                         // Attempt to do the implicit constant expression conversions
566
567                         if (expr is IntConstant){
568                                 Expression e;
569                                 
570                                 e = TryImplicitIntConversion (target_type, (IntConstant) expr);
571
572                                 if (e != null)
573                                         return e;
574                         } else if (expr is LongConstant && target_type == TypeManager.uint64_type){
575                                 //
576                                 // Try the implicit constant expression conversion
577                                 // from long to ulong, instead of a nice routine,
578                                 // we just inline it
579                                 //
580                                 long v = ((LongConstant) expr).Value;
581                                 if (v > 0)
582                                         return new ULongConstant ((ulong) v);
583                         }
584
585                         //
586                         // If we have an enumeration, extract the underlying type,
587                         // use this during the comparission, but wrap around the original
588                         // target_type
589                         //
590                         Type real_target_type = target_type;
591
592                         if (TypeManager.IsEnumType (real_target_type))
593                                 real_target_type = TypeManager.EnumToUnderlying (real_target_type);
594
595                         if (expr_type == real_target_type)
596                                 return new EmptyCast (expr, target_type);
597                         
598                         if (expr_type == TypeManager.sbyte_type){
599                                 //
600                                 // From sbyte to short, int, long, float, double.
601                                 //
602                                 if (real_target_type == TypeManager.int32_type)
603                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_I4);
604                                 if (real_target_type == TypeManager.int64_type)
605                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_I8);
606                                 if (real_target_type == TypeManager.double_type)
607                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_R8);
608                                 if (real_target_type == TypeManager.float_type)
609                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_R4);
610                                 if (real_target_type == TypeManager.short_type)
611                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_I2);
612                                 if (real_target_type == TypeManager.decimal_type)
613                                         return InternalTypeConstructor (ec, expr, target_type);
614                         } else if (expr_type == TypeManager.byte_type){
615                                 //
616                                 // From byte to short, ushort, int, uint, long, ulong, float, double
617                                 // 
618                                 if ((real_target_type == TypeManager.short_type) ||
619                                     (real_target_type == TypeManager.ushort_type) ||
620                                     (real_target_type == TypeManager.int32_type) ||
621                                     (real_target_type == TypeManager.uint32_type))
622                                         return new EmptyCast (expr, target_type);
623
624                                 if (real_target_type == TypeManager.uint64_type)
625                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_U8);
626                                 if (real_target_type == TypeManager.int64_type)
627                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_I8);
628                                 if (real_target_type == TypeManager.float_type)
629                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_R4);
630                                 if (real_target_type == TypeManager.double_type)
631                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_R8);
632                                 if (real_target_type == TypeManager.decimal_type)
633                                         return InternalTypeConstructor (ec, expr, target_type);
634                         } else if (expr_type == TypeManager.short_type){
635                                 //
636                                 // From short to int, long, float, double
637                                 // 
638                                 if (real_target_type == TypeManager.int32_type)
639                                         return new EmptyCast (expr, target_type);
640                                 if (real_target_type == TypeManager.int64_type)
641                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_I8);
642                                 if (real_target_type == TypeManager.double_type)
643                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_R8);
644                                 if (real_target_type == TypeManager.float_type)
645                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_R4);
646                                 if (real_target_type == TypeManager.decimal_type)
647                                         return InternalTypeConstructor (ec, expr, target_type);
648                         } else if (expr_type == TypeManager.ushort_type){
649                                 //
650                                 // From ushort to int, uint, long, ulong, float, double
651                                 //
652                                 if (real_target_type == TypeManager.uint32_type)
653                                         return new EmptyCast (expr, target_type);
654
655                                 if (real_target_type == TypeManager.uint64_type)
656                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_U8);
657                                 if (real_target_type == TypeManager.int32_type)
658                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_I4);
659                                 if (real_target_type == TypeManager.int64_type)
660                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_I8);
661                                 if (real_target_type == TypeManager.double_type)
662                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_R8);
663                                 if (real_target_type == TypeManager.float_type)
664                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_R4);
665                                 if (real_target_type == TypeManager.decimal_type)
666                                         return InternalTypeConstructor (ec, expr, target_type);
667                         } else if (expr_type == TypeManager.int32_type){
668                                 //
669                                 // From int to long, float, double
670                                 //
671                                 if (real_target_type == TypeManager.int64_type)
672                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_I8);
673                                 if (real_target_type == TypeManager.double_type)
674                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_R8);
675                                 if (real_target_type == TypeManager.float_type)
676                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_R4);
677                                 if (real_target_type == TypeManager.decimal_type)
678                                         return InternalTypeConstructor (ec, expr, target_type);
679                         } else if (expr_type == TypeManager.uint32_type){
680                                 //
681                                 // From uint to long, ulong, float, double
682                                 //
683                                 if (real_target_type == TypeManager.int64_type)
684                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_U8);
685                                 if (real_target_type == TypeManager.uint64_type)
686                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_U8);
687                                 if (real_target_type == TypeManager.double_type)
688                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_R_Un,
689                                                                OpCodes.Conv_R8);
690                                 if (real_target_type == TypeManager.float_type)
691                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_R_Un,
692                                                                OpCodes.Conv_R4);
693                                 if (real_target_type == TypeManager.decimal_type)
694                                         return InternalTypeConstructor (ec, expr, target_type);
695                         } else if ((expr_type == TypeManager.uint64_type) ||
696                                    (expr_type == TypeManager.int64_type)){
697                                 //
698                                 // From long/ulong to float, double
699                                 //
700                                 if (real_target_type == TypeManager.double_type)
701                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_R_Un,
702                                                                OpCodes.Conv_R8);
703                                 if (real_target_type == TypeManager.float_type)
704                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_R_Un,
705                                                                OpCodes.Conv_R4);        
706                                 if (real_target_type == TypeManager.decimal_type)
707                                         return InternalTypeConstructor (ec, expr, target_type);
708                         } else if (expr_type == TypeManager.char_type){
709                                 //
710                                 // From char to ushort, int, uint, long, ulong, float, double
711                                 // 
712                                 if ((real_target_type == TypeManager.ushort_type) ||
713                                     (real_target_type == TypeManager.int32_type) ||
714                                     (real_target_type == TypeManager.uint32_type))
715                                         return new EmptyCast (expr, target_type);
716                                 if (real_target_type == TypeManager.uint64_type)
717                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_U8);
718                                 if (real_target_type == TypeManager.int64_type)
719                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_I8);
720                                 if (real_target_type == TypeManager.float_type)
721                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_R4);
722                                 if (real_target_type == TypeManager.double_type)
723                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_R8);
724                                 if (real_target_type == TypeManager.decimal_type)
725                                         return InternalTypeConstructor (ec, expr, target_type);
726                         } else if (expr_type == TypeManager.float_type){
727                                 //
728                                 // float to double
729                                 //
730                                 if (real_target_type == TypeManager.double_type)
731                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_R8);
732                         }
733
734                         return null;
735                 }
736
737                 /// <summary>
738                 ///  Determines if a standard implicit conversion exists from
739                 ///  expr_type to target_type
740                 /// </summary>
741                 public static bool StandardConversionExists (Expression expr, Type target_type)
742                 {
743                         Type expr_type = expr.Type;
744                         
745                         if (expr_type == target_type)
746                                 return true;
747
748                         // First numeric conversions 
749                         
750                         if (expr_type == TypeManager.sbyte_type){
751                                 //
752                                 // From sbyte to short, int, long, float, double.
753                                 //
754                                 if ((target_type == TypeManager.int32_type) || 
755                                     (target_type == TypeManager.int64_type) ||
756                                     (target_type == TypeManager.double_type) ||
757                                     (target_type == TypeManager.float_type)  ||
758                                     (target_type == TypeManager.short_type) ||
759                                     (target_type == TypeManager.decimal_type))
760                                         return true;
761                                 
762                         } else if (expr_type == TypeManager.byte_type){
763                                 //
764                                 // From byte to short, ushort, int, uint, long, ulong, float, double
765                                 // 
766                                 if ((target_type == TypeManager.short_type) ||
767                                     (target_type == TypeManager.ushort_type) ||
768                                     (target_type == TypeManager.int32_type) ||
769                                     (target_type == TypeManager.uint32_type) ||
770                                     (target_type == TypeManager.uint64_type) ||
771                                     (target_type == TypeManager.int64_type) ||
772                                     (target_type == TypeManager.float_type) ||
773                                     (target_type == TypeManager.double_type) ||
774                                     (target_type == TypeManager.decimal_type))
775                                         return true;
776         
777                         } else if (expr_type == TypeManager.short_type){
778                                 //
779                                 // From short to int, long, float, double
780                                 // 
781                                 if ((target_type == TypeManager.int32_type) ||
782                                     (target_type == TypeManager.int64_type) ||
783                                     (target_type == TypeManager.double_type) ||
784                                     (target_type == TypeManager.float_type) ||
785                                     (target_type == TypeManager.decimal_type))
786                                         return true;
787                                         
788                         } else if (expr_type == TypeManager.ushort_type){
789                                 //
790                                 // From ushort to int, uint, long, ulong, float, double
791                                 //
792                                 if ((target_type == TypeManager.uint32_type) ||
793                                     (target_type == TypeManager.uint64_type) ||
794                                     (target_type == TypeManager.int32_type) ||
795                                     (target_type == TypeManager.int64_type) ||
796                                     (target_type == TypeManager.double_type) ||
797                                     (target_type == TypeManager.float_type) ||
798                                     (target_type == TypeManager.decimal_type))
799                                         return true;
800                                     
801                         } else if (expr_type == TypeManager.int32_type){
802                                 //
803                                 // From int to long, float, double
804                                 //
805                                 if ((target_type == TypeManager.int64_type) ||
806                                     (target_type == TypeManager.double_type) ||
807                                     (target_type == TypeManager.float_type) ||
808                                     (target_type == TypeManager.decimal_type))
809                                         return true;
810                                         
811                         } else if (expr_type == TypeManager.uint32_type){
812                                 //
813                                 // From uint to long, ulong, float, double
814                                 //
815                                 if ((target_type == TypeManager.int64_type) ||
816                                     (target_type == TypeManager.uint64_type) ||
817                                     (target_type == TypeManager.double_type) ||
818                                     (target_type == TypeManager.float_type) ||
819                                     (target_type == TypeManager.decimal_type))
820                                         return true;
821                                         
822                         } else if ((expr_type == TypeManager.uint64_type) ||
823                                    (expr_type == TypeManager.int64_type)) {
824                                 //
825                                 // From long/ulong to float, double
826                                 //
827                                 if ((target_type == TypeManager.double_type) ||
828                                     (target_type == TypeManager.float_type) ||
829                                     (target_type == TypeManager.decimal_type))
830                                         return true;
831                                     
832                         } else if (expr_type == TypeManager.char_type){
833                                 //
834                                 // From char to ushort, int, uint, long, ulong, float, double
835                                 // 
836                                 if ((target_type == TypeManager.ushort_type) ||
837                                     (target_type == TypeManager.int32_type) ||
838                                     (target_type == TypeManager.uint32_type) ||
839                                     (target_type == TypeManager.uint64_type) ||
840                                     (target_type == TypeManager.int64_type) ||
841                                     (target_type == TypeManager.float_type) ||
842                                     (target_type == TypeManager.double_type) ||
843                                     (target_type == TypeManager.decimal_type))
844                                         return true;
845
846                         } else if (expr_type == TypeManager.float_type){
847                                 //
848                                 // float to double
849                                 //
850                                 if (target_type == TypeManager.double_type)
851                                         return true;
852                         }       
853                         
854                         // Next reference conversions
855
856                         if (target_type == TypeManager.object_type) {
857                                 if ((expr_type.IsClass) ||
858                                     (expr_type.IsValueType))
859                                         return true;
860                                 
861                         } else if (expr_type.IsSubclassOf (target_type)) {
862                                 return true;
863                                 
864                         } else {
865                                 // Please remember that all code below actually comes
866                                 // from ImplicitReferenceConversion so make sure code remains in sync
867                                 
868                                 // from any class-type S to any interface-type T.
869                                 if (expr_type.IsClass && target_type.IsInterface) {
870                                         if (TypeManager.ImplementsInterface (expr_type, target_type))
871                                                 return true;
872                                 }
873                                 
874                                 // from any interface type S to interface-type T.
875                                 // FIXME : Is it right to use IsAssignableFrom ?
876                                 if (expr_type.IsInterface && target_type.IsInterface)
877                                         if (target_type.IsAssignableFrom (expr_type))
878                                                 return true;
879                                 
880                                 // from an array-type S to an array-type of type T
881                                 if (expr_type.IsArray && target_type.IsArray) {
882                                         if (expr_type.GetArrayRank () == target_type.GetArrayRank ()) {
883                                                 
884                                                 Type expr_element_type = expr_type.GetElementType ();
885
886                                                 if (MyEmptyExpr == null)
887                                                         MyEmptyExpr = new EmptyExpression ();
888                                                 
889                                                 MyEmptyExpr.SetType (expr_element_type);
890                                                 Type target_element_type = target_type.GetElementType ();
891                                                 
892                                                 if (!expr_element_type.IsValueType && !target_element_type.IsValueType)
893                                                         if (StandardConversionExists (MyEmptyExpr,
894                                                                                       target_element_type))
895                                                                 return true;
896                                         }
897                                 }
898                                 
899                                 // from an array-type to System.Array
900                                 if (expr_type.IsArray && target_type.IsAssignableFrom (expr_type))
901                                         return true;
902                                 
903                                 // from any delegate type to System.Delegate
904                                 if (expr_type.IsSubclassOf (TypeManager.delegate_type) &&
905                                     target_type == TypeManager.delegate_type)
906                                         if (target_type.IsAssignableFrom (expr_type))
907                                                 return true;
908                                         
909                                 // from any array-type or delegate type into System.ICloneable.
910                                 if (expr_type.IsArray || expr_type.IsSubclassOf (TypeManager.delegate_type))
911                                         if (target_type == TypeManager.icloneable_type)
912                                                 return true;
913                                 
914                                 // from the null type to any reference-type.
915                                 if (expr is NullLiteral && !target_type.IsValueType)
916                                         return true;
917                                 
918                         }
919
920                         return false;
921                 }
922
923                 //
924                 // Used internally by FindMostEncompassedType, this is used
925                 // to avoid creating lots of objects in the tight loop inside
926                 // FindMostEncompassedType
927                 //
928                 static EmptyExpression priv_fmet_param;
929                 
930                 /// <summary>
931                 ///  Finds "most encompassed type" according to the spec (13.4.2)
932                 ///  amongst the methods in the MethodGroupExpr
933                 /// </summary>
934                 static Type FindMostEncompassedType (ArrayList types)
935                 {
936                         Type best = null;
937
938                         if (priv_fmet_param == null)
939                                 priv_fmet_param = new EmptyExpression ();
940                                         
941                         for (int i = 0; i < types.Count; ++i) {
942                                 Type t = (Type) types [i];
943                                 priv_fmet_param.SetType (t);
944                                 
945                                 if (best == null) {
946                                         best = t;
947                                         continue;
948                                 }
949                                 Console.WriteLine ("Candidate : " + t);
950                                 if (StandardConversionExists (priv_fmet_param, best))
951                                         best = t;
952                         }
953
954                         return best;
955                 }
956
957                 //
958                 // Used internally by FindMostEncompassingType, this is used
959                 // to avoid creating lots of objects in the tight loop inside
960                 // FindMostEncompassingType
961                 //
962                 static EmptyExpression priv_fmee_ret;
963                 
964                 /// <summary>
965                 ///  Finds "most encompassing type" according to the spec (13.4.2)
966                 ///  amongst the types in the given set
967                 /// </summary>
968                 static Type FindMostEncompassingType (ArrayList types)
969                 {
970                         Type best = null;
971
972                         if (priv_fmee_ret == null)
973                                 priv_fmee_ret = new EmptyExpression ();
974                         
975                         for (int i = 0; i < types.Count; ++i ) {
976                                 
977                                 Type t = (Type) types [i];
978                                 priv_fmee_ret.SetType (best);
979
980                                 if (best == null) {
981                                         best = t;
982                                         continue;
983                                 }
984
985                                 Console.WriteLine ("Casdkalkds " + t);
986                                 if (StandardConversionExists (priv_fmee_ret, t))
987                                         best = t;
988                         }
989                         
990                         return best;
991                 }
992
993                 //
994                 // Used to avoid creating too many objects
995                 //
996                 static EmptyExpression priv_fms_expr;
997                 
998                 /// <summary>
999                 ///   Finds the most specific source Sx according to the rules of the spec (13.4.4)
1000                 ///   by making use of FindMostEncomp* methods. Applies the correct rules separately
1001                 ///   for explicit and implicit conversion operators.
1002                 /// </summary>
1003                 static public Type FindMostSpecificSource (MethodGroupExpr me, Type source_type,
1004                                                            bool apply_explicit_conv_rules,
1005                                                            Location loc)
1006                 {
1007                         ArrayList src_types_set = new ArrayList ();
1008                         
1009                         if (priv_fms_expr == null)
1010                                 priv_fms_expr = new EmptyExpression ();
1011                         
1012                         //
1013                         // If any operator converts from S then Sx = S
1014                         //
1015                         for (int i = me.Methods.Length; i > 0; ) {
1016                                 i--;
1017
1018                                 MethodBase mb = me.Methods [i];
1019                                 ParameterData pd = Invocation.GetParameterData (mb);
1020                                 Type param_type = pd.ParameterType (0);
1021
1022                                 if (param_type == source_type)
1023                                         return param_type;
1024
1025                                 src_types_set.Add (param_type);
1026                         }
1027                         
1028                         //
1029                         // Explicit Conv rules
1030                         //
1031                         if (apply_explicit_conv_rules) {
1032
1033                                 ArrayList candidate_set = new ArrayList ();
1034
1035                                 for (int i = 0; i < src_types_set.Count; ++i) {
1036                                         Type param_type = (Type) src_types_set [i];
1037
1038                                         priv_fms_expr.SetType (source_type);
1039                                         
1040                                         if (StandardConversionExists (priv_fms_expr, param_type))
1041                                                 candidate_set.Add (param_type);
1042                                 }
1043
1044                                 if (candidate_set.Count != 0)
1045                                         return FindMostEncompassedType (candidate_set);
1046                         }
1047
1048                         //
1049                         // Final case
1050                         //
1051                         if (apply_explicit_conv_rules)
1052                                 return FindMostEncompassingType (src_types_set);
1053                         else
1054                                 return FindMostEncompassedType (src_types_set);
1055                 }
1056
1057                 //
1058                 // Useful in avoiding proliferation of objects
1059                 //
1060                 static EmptyExpression priv_fmt_expr;
1061                 
1062                 /// <summary>
1063                 ///  Finds the most specific target Tx according to section 13.4.4
1064                 /// </summary>
1065                 static public Type FindMostSpecificTarget (MethodGroupExpr me, Type target,
1066                                                            bool apply_explicit_conv_rules,
1067                                                            Location loc)
1068                 {
1069                         ArrayList tgt_types_set = new ArrayList ();
1070                         
1071                         if (priv_fmt_expr == null)
1072                                 priv_fmt_expr = new EmptyExpression ();
1073                         
1074                         //
1075                         // If any operator converts to T then Tx = T
1076                         //
1077                         for (int i = me.Methods.Length; i > 0; ) {
1078                                 i--;
1079                                 
1080                                 MethodInfo mi = (MethodInfo) me.Methods [i];
1081                                 Type ret_type = mi.ReturnType;
1082
1083                                 if (ret_type == target)
1084                                         return ret_type;
1085
1086                                 tgt_types_set.Add (ret_type);
1087                         }
1088
1089                         //
1090                         // Explicit conv rules
1091                         //
1092                         if (apply_explicit_conv_rules) {
1093
1094                                 ArrayList candidate_set = new ArrayList ();
1095                                 
1096                                 for (int i = 0; i < tgt_types_set.Count; ++i) {
1097                                         Type ret_type = (Type) tgt_types_set [i];
1098                                         
1099                                         priv_fmt_expr.SetType (ret_type);
1100                                         
1101                                         if (StandardConversionExists (priv_fmt_expr, target))
1102                                                 candidate_set.Add (ret_type);
1103                                 }
1104
1105                                 if (candidate_set.Count != 0)
1106                                         return FindMostEncompassingType (candidate_set);
1107                         }
1108                         
1109                         //
1110                         // Okay, final case !
1111                         //
1112                         if (apply_explicit_conv_rules)
1113                                 return FindMostEncompassedType (tgt_types_set);
1114                         else
1115                                 return FindMostEncompassingType (tgt_types_set);
1116                 }
1117                 
1118                 /// <summary>
1119                 ///  User-defined Implicit conversions
1120                 /// </summary>
1121                 static public Expression ImplicitUserConversion (EmitContext ec, Expression source,
1122                                                                  Type target, Location loc)
1123                 {
1124                         return UserDefinedConversion (ec, source, target, loc, false);
1125                 }
1126
1127                 /// <summary>
1128                 ///  User-defined Explicit conversions
1129                 /// </summary>
1130                 static public Expression ExplicitUserConversion (EmitContext ec, Expression source,
1131                                                                  Type target, Location loc)
1132                 {
1133                         return UserDefinedConversion (ec, source, target, loc, true);
1134                 }
1135
1136                 /// <summary>
1137                 ///   Computes the MethodGroup for the user-defined conversion
1138                 ///   operators from source_type to target_type.  `look_for_explicit'
1139                 ///   controls whether we should also include the list of explicit
1140                 ///   operators
1141                 /// </summary>
1142                 static MethodGroupExpr GetConversionOperators (EmitContext ec,
1143                                                                Type source_type, Type target_type,
1144                                                                Location loc, bool look_for_explicit)
1145                 {
1146                         Expression mg1 = null, mg2 = null;
1147                         Expression mg5 = null, mg6 = null, mg7 = null, mg8 = null;
1148                         string op_name;
1149                         
1150                         // If we have a boolean type, we need to check for the True operator
1151
1152                         // FIXME : How does the False operator come into the picture ?
1153                         // FIXME : This doesn't look complete and very correct !
1154                         if (target_type == TypeManager.bool_type)
1155                                 op_name = "op_True";
1156                         else
1157                                 op_name = "op_Implicit";
1158                         
1159                         MethodGroupExpr union3;
1160                         
1161                         mg1 = MethodLookup (ec, source_type, op_name, loc);
1162                         if (source_type.BaseType != null)
1163                                 mg2 = MethodLookup (ec, source_type.BaseType, op_name, loc);
1164
1165                         if (mg1 == null)
1166                                 union3 = (MethodGroupExpr) mg2;
1167                         else if (mg2 == null)
1168                                 union3 = (MethodGroupExpr) mg1;
1169                         else
1170                                 union3 = Invocation.MakeUnionSet (mg1, mg2, loc);
1171
1172                         mg1 = MethodLookup (ec, target_type, op_name, loc);
1173                         if (mg1 != null){
1174                                 if (union3 != null)
1175                                         union3 = Invocation.MakeUnionSet (union3, mg1, loc);
1176                                 else
1177                                         union3 = (MethodGroupExpr) mg1;
1178                         }
1179
1180                         if (target_type.BaseType != null)
1181                                 mg1 = MethodLookup (ec, target_type.BaseType, op_name, loc);
1182                         
1183                         if (mg1 != null){
1184                                 if (union3 != null)
1185                                         union3 = Invocation.MakeUnionSet (union3, mg1, loc);
1186                                 else
1187                                         union3 = (MethodGroupExpr) mg1;
1188                         }
1189
1190                         MethodGroupExpr union4 = null;
1191
1192                         if (look_for_explicit) {
1193                                 op_name = "op_Explicit";
1194
1195                                 mg5 = MemberLookup (ec, source_type, op_name, loc);
1196                                 if (source_type.BaseType != null)
1197                                         mg6 = MethodLookup (ec, source_type.BaseType, op_name, loc);
1198                                 
1199                                 mg7 = MemberLookup (ec, target_type, op_name, loc);
1200                                 if (target_type.BaseType != null)
1201                                         mg8 = MethodLookup (ec, target_type.BaseType, op_name, loc);
1202                                 
1203                                 MethodGroupExpr union5 = Invocation.MakeUnionSet (mg5, mg6, loc);
1204                                 MethodGroupExpr union6 = Invocation.MakeUnionSet (mg7, mg8, loc);
1205
1206                                 union4 = Invocation.MakeUnionSet (union5, union6, loc);
1207                         }
1208                         
1209                         return Invocation.MakeUnionSet (union3, union4, loc);
1210                 }
1211                 
1212                 /// <summary>
1213                 ///   User-defined conversions
1214                 /// </summary>
1215                 static public Expression UserDefinedConversion (EmitContext ec, Expression source,
1216                                                                 Type target, Location loc,
1217                                                                 bool look_for_explicit)
1218                 {
1219                         MethodGroupExpr union;
1220                         Type source_type = source.Type;
1221                         MethodBase method = null;
1222                         
1223                         union = GetConversionOperators (ec, source_type, target, loc, look_for_explicit);
1224                         if (union == null)
1225                                 return null;
1226                         
1227                         Type most_specific_source, most_specific_target;
1228
1229                         most_specific_source = FindMostSpecificSource (union, source_type, look_for_explicit, loc);
1230                         if (most_specific_source == null)
1231                                 return null;
1232
1233                         most_specific_target = FindMostSpecificTarget (union, target, look_for_explicit, loc);
1234                         if (most_specific_target == null) 
1235                                 return null;
1236                         
1237                         int count = 0;
1238                         
1239                         for (int i = union.Methods.Length; i > 0;) {
1240                                 i--;
1241                                 
1242                                 MethodBase mb = union.Methods [i];
1243                                 ParameterData pd = Invocation.GetParameterData (mb);
1244                                 MethodInfo mi = (MethodInfo) union.Methods [i];
1245                                 
1246                                 if (pd.ParameterType (0) == most_specific_source &&
1247                                     mi.ReturnType == most_specific_target) {
1248                                         method = mb;
1249                                         count++;
1250                                 }
1251                         }
1252                         
1253                         if (method == null || count > 1) {
1254                                 Report.Error (-11, loc, "Ambiguous user defined conversion");
1255                                 return null;
1256                         }
1257                         
1258                         //
1259                         // This will do the conversion to the best match that we
1260                         // found.  Now we need to perform an implict standard conversion
1261                         // if the best match was not the type that we were requested
1262                         // by target.
1263                         //
1264                         if (look_for_explicit)
1265                                 source = ConvertExplicitStandard (ec, source, most_specific_source, loc);
1266                         else
1267                                 source = ConvertImplicitStandard (ec, source, most_specific_source, loc);
1268
1269                         if (source == null)
1270                                 return null;
1271
1272                         Expression e;
1273                         e =  new UserCast ((MethodInfo) method, source);
1274                         if (e.Type != target){
1275                                 if (!look_for_explicit)
1276                                         e = ConvertImplicitStandard (ec, e, target, loc);
1277                                 else
1278                                         e = ConvertExplicitStandard (ec, e, target, loc);
1279                         } 
1280                         return e;
1281                 }
1282                 
1283                 /// <summary>
1284                 ///   Converts implicitly the resolved expression `expr' into the
1285                 ///   `target_type'.  It returns a new expression that can be used
1286                 ///   in a context that expects a `target_type'. 
1287                 /// </summary>
1288                 static public Expression ConvertImplicit (EmitContext ec, Expression expr,
1289                                                           Type target_type, Location loc)
1290                 {
1291                         Type expr_type = expr.Type;
1292                         Expression e;
1293
1294                         if (expr_type == target_type)
1295                                 return expr;
1296
1297                         if (target_type == null)
1298                                 throw new Exception ("Target type is null");
1299
1300                         e = ConvertImplicitStandard (ec, expr, target_type, loc);
1301                         if (e != null)
1302                                 return e;
1303
1304                         e = ImplicitUserConversion (ec, expr, target_type, loc);
1305                         if (e != null)
1306                                 return e;
1307
1308                         return null;
1309                 }
1310
1311                 
1312                 /// <summary>
1313                 ///   Attempts to apply the `Standard Implicit
1314                 ///   Conversion' rules to the expression `expr' into
1315                 ///   the `target_type'.  It returns a new expression
1316                 ///   that can be used in a context that expects a
1317                 ///   `target_type'.
1318                 ///
1319                 ///   This is different from `ConvertImplicit' in that the
1320                 ///   user defined implicit conversions are excluded. 
1321                 /// </summary>
1322                 static public Expression ConvertImplicitStandard (EmitContext ec, Expression expr,
1323                                                                   Type target_type, Location loc)
1324                 {
1325                         Type expr_type = expr.Type;
1326                         Expression e;
1327
1328                         if (expr_type == target_type)
1329                                 return expr;
1330
1331                         e = ImplicitNumericConversion (ec, expr, target_type, loc);
1332                         if (e != null)
1333                                 return e;
1334
1335                         e = ImplicitReferenceConversion (expr, target_type);
1336                         if (e != null)
1337                                 return e;
1338
1339                         if (target_type.IsSubclassOf (TypeManager.enum_type) && expr is IntLiteral){
1340                                 IntLiteral i = (IntLiteral) expr;
1341
1342                                 if (i.Value == 0)
1343                                         return new EmptyCast (expr, target_type);
1344                         }
1345
1346                         if (ec.InUnsafe) {
1347                                 if (expr_type.IsPointer){
1348                                         if (target_type == TypeManager.void_ptr_type)
1349                                                 return new EmptyCast (expr, target_type);
1350
1351                                         //
1352                                         // yep, comparing pointer types cant be done with
1353                                         // t1 == t2, we have to compare their element types.
1354                                         //
1355                                         if (target_type.IsPointer){
1356                                                 if (target_type.GetElementType()==expr_type.GetElementType())
1357                                                         return expr;
1358                                         }
1359                                 }
1360                                 
1361                                 if (target_type.IsPointer){
1362                                         if (expr is NullLiteral)
1363                                                 return new EmptyCast (expr, target_type);
1364                                 }
1365                         }
1366
1367                         return null;
1368                 }
1369
1370                 /// <summary>
1371                 ///   Attemps to perform an implict constant conversion of the IntConstant
1372                 ///   into a different data type using casts (See Implicit Constant
1373                 ///   Expression Conversions)
1374                 /// </summary>
1375                 static protected Expression TryImplicitIntConversion (Type target_type, IntConstant ic)
1376                 {
1377                         int value = ic.Value;
1378
1379                         //
1380                         // FIXME: This could return constants instead of EmptyCasts
1381                         //
1382                         if (target_type == TypeManager.sbyte_type){
1383                                 if (value >= SByte.MinValue && value <= SByte.MaxValue)
1384                                         return new SByteConstant ((sbyte) value);
1385                         } else if (target_type == TypeManager.byte_type){
1386                                 if (Byte.MinValue >= 0 && value <= Byte.MaxValue)
1387                                         return new ByteConstant ((byte) value);
1388                         } else if (target_type == TypeManager.short_type){
1389                                 if (value >= Int16.MinValue && value <= Int16.MaxValue)
1390                                         return new ShortConstant ((short) value);
1391                         } else if (target_type == TypeManager.ushort_type){
1392                                 if (value >= UInt16.MinValue && value <= UInt16.MaxValue)
1393                                         return new UShortConstant ((ushort) value);
1394                         } else if (target_type == TypeManager.uint32_type){
1395                                 if (value >= 0)
1396                                         return new UIntConstant ((uint) value);
1397                         } else if (target_type == TypeManager.uint64_type){
1398                                 //
1399                                 // we can optimize this case: a positive int32
1400                                 // always fits on a uint64.  But we need an opcode
1401                                 // to do it.
1402                                 //
1403                                 if (value >= 0)
1404                                         return new ULongConstant ((ulong) value);
1405                         }
1406                         
1407                         if (value == 0 && ic is IntLiteral && TypeManager.IsEnumType (target_type))
1408                                 return new EnumConstant (ic, target_type);
1409
1410                         return null;
1411                 }
1412
1413                 static public void Error_CannotConvertImplicit (Location loc, Type source, Type target)
1414                 {
1415                         string msg = "Cannot convert implicitly from `"+
1416                                 TypeManager.CSharpName (source) + "' to `" +
1417                                 TypeManager.CSharpName (target) + "'";
1418
1419                         Error (29, loc, msg);
1420                 }
1421
1422                 /// <summary>
1423                 ///   Attemptes to implicityly convert `target' into `type', using
1424                 ///   ConvertImplicit.  If there is no implicit conversion, then
1425                 ///   an error is signaled
1426                 /// </summary>
1427                 static public Expression ConvertImplicitRequired (EmitContext ec, Expression source,
1428                                                                   Type target_type, Location loc)
1429                 {
1430                         Expression e;
1431                         
1432                         e = ConvertImplicit (ec, source, target_type, loc);
1433                         if (e != null)
1434                                 return e;
1435
1436                         if (source is DoubleLiteral && target_type == TypeManager.float_type){
1437                                 Error (664, loc,
1438                                        "Double literal cannot be implicitly converted to " +
1439                                        "float type, use F suffix to create a float literal");
1440                         }
1441                         
1442                         Error_CannotConvertImplicit (loc, source.Type, target_type);
1443
1444                         return null;
1445                 }
1446
1447                 /// <summary>
1448                 ///   Performs the explicit numeric conversions
1449                 /// </summary>
1450                 static Expression ConvertNumericExplicit (EmitContext ec, Expression expr,
1451                                                           Type target_type)
1452                 {
1453                         Type expr_type = expr.Type;
1454
1455                         //
1456                         // If we have an enumeration, extract the underlying type,
1457                         // use this during the comparission, but wrap around the original
1458                         // target_type
1459                         //
1460                         Type real_target_type = target_type;
1461
1462                         if (TypeManager.IsEnumType (real_target_type))
1463                                 real_target_type = TypeManager.EnumToUnderlying (real_target_type);
1464
1465                         if (expr_type == TypeManager.sbyte_type){
1466                                 //
1467                                 // From sbyte to byte, ushort, uint, ulong, char
1468                                 //
1469                                 if (real_target_type == TypeManager.byte_type)
1470                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.I1_U1);
1471                                 if (real_target_type == TypeManager.ushort_type)
1472                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.I1_U2);
1473                                 if (real_target_type == TypeManager.uint32_type)
1474                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.I1_U4);
1475                                 if (real_target_type == TypeManager.uint64_type)
1476                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.I1_U8);
1477                                 if (real_target_type == TypeManager.char_type)
1478                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.I1_CH);
1479                         } else if (expr_type == TypeManager.byte_type){
1480                                 //
1481                                 // From byte to sbyte and char
1482                                 //
1483                                 if (real_target_type == TypeManager.sbyte_type)
1484                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.U1_I1);
1485                                 if (real_target_type == TypeManager.char_type)
1486                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.U1_CH);
1487                         } else if (expr_type == TypeManager.short_type){
1488                                 //
1489                                 // From short to sbyte, byte, ushort, uint, ulong, char
1490                                 //
1491                                 if (real_target_type == TypeManager.sbyte_type)
1492                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.I2_I1);
1493                                 if (real_target_type == TypeManager.byte_type)
1494                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.I2_U1);
1495                                 if (real_target_type == TypeManager.ushort_type)
1496                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.I2_U2);
1497                                 if (real_target_type == TypeManager.uint32_type)
1498                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.I2_U4);
1499                                 if (real_target_type == TypeManager.uint64_type)
1500                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.I2_U8);
1501                                 if (real_target_type == TypeManager.char_type)
1502                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.I2_CH);
1503                         } else if (expr_type == TypeManager.ushort_type){
1504                                 //
1505                                 // From ushort to sbyte, byte, short, char
1506                                 //
1507                                 if (real_target_type == TypeManager.sbyte_type)
1508                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.U2_I1);
1509                                 if (real_target_type == TypeManager.byte_type)
1510                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.U2_U1);
1511                                 if (real_target_type == TypeManager.short_type)
1512                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.U2_I2);
1513                                 if (real_target_type == TypeManager.char_type)
1514                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.U2_CH);
1515                         } else if (expr_type == TypeManager.int32_type){
1516                                 //
1517                                 // From int to sbyte, byte, short, ushort, uint, ulong, char
1518                                 //
1519                                 if (real_target_type == TypeManager.sbyte_type)
1520                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.I4_I1);
1521                                 if (real_target_type == TypeManager.byte_type)
1522                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.I4_U1);
1523                                 if (real_target_type == TypeManager.short_type)
1524                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.I4_I2);
1525                                 if (real_target_type == TypeManager.ushort_type)
1526                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.I4_U2);
1527                                 if (real_target_type == TypeManager.uint32_type)
1528                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.I4_U4);
1529                                 if (real_target_type == TypeManager.uint64_type)
1530                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.I4_U8);
1531                                 if (real_target_type == TypeManager.char_type)
1532                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.I4_CH);
1533                         } else if (expr_type == TypeManager.uint32_type){
1534                                 //
1535                                 // From uint to sbyte, byte, short, ushort, int, char
1536                                 //
1537                                 if (real_target_type == TypeManager.sbyte_type)
1538                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.U4_I1);
1539                                 if (real_target_type == TypeManager.byte_type)
1540                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.U4_U1);
1541                                 if (real_target_type == TypeManager.short_type)
1542                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.U4_I2);
1543                                 if (real_target_type == TypeManager.ushort_type)
1544                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.U4_U2);
1545                                 if (real_target_type == TypeManager.int32_type)
1546                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.U4_I4);
1547                                 if (real_target_type == TypeManager.char_type)
1548                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.U4_CH);
1549                         } else if (expr_type == TypeManager.int64_type){
1550                                 //
1551                                 // From long to sbyte, byte, short, ushort, int, uint, ulong, char
1552                                 //
1553                                 if (real_target_type == TypeManager.sbyte_type)
1554                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.I8_I1);
1555                                 if (real_target_type == TypeManager.byte_type)
1556                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.I8_U1);
1557                                 if (real_target_type == TypeManager.short_type)
1558                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.I8_I2);
1559                                 if (real_target_type == TypeManager.ushort_type)
1560                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.I8_U2);
1561                                 if (real_target_type == TypeManager.int32_type)
1562                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.I8_I4);
1563                                 if (real_target_type == TypeManager.uint32_type)
1564                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.I8_U4);
1565                                 if (real_target_type == TypeManager.uint64_type)
1566                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.I8_U8);
1567                                 if (real_target_type == TypeManager.char_type)
1568                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.I8_CH);
1569                         } else if (expr_type == TypeManager.uint64_type){
1570                                 //
1571                                 // From ulong to sbyte, byte, short, ushort, int, uint, long, char
1572                                 //
1573                                 if (real_target_type == TypeManager.sbyte_type)
1574                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.U8_I1);
1575                                 if (real_target_type == TypeManager.byte_type)
1576                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.U8_U1);
1577                                 if (real_target_type == TypeManager.short_type)
1578                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.U8_I2);
1579                                 if (real_target_type == TypeManager.ushort_type)
1580                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.U8_U2);
1581                                 if (real_target_type == TypeManager.int32_type)
1582                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.U8_I4);
1583                                 if (real_target_type == TypeManager.uint32_type)
1584                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.U8_U4);
1585                                 if (real_target_type == TypeManager.int64_type)
1586                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.U8_I8);
1587                                 if (real_target_type == TypeManager.char_type)
1588                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.U8_CH);
1589                         } else if (expr_type == TypeManager.char_type){
1590                                 //
1591                                 // From char to sbyte, byte, short
1592                                 //
1593                                 if (real_target_type == TypeManager.sbyte_type)
1594                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.CH_I1);
1595                                 if (real_target_type == TypeManager.byte_type)
1596                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.CH_U1);
1597                                 if (real_target_type == TypeManager.short_type)
1598                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.CH_I2);
1599                         } else if (expr_type == TypeManager.float_type){
1600                                 //
1601                                 // From float to sbyte, byte, short,
1602                                 // ushort, int, uint, long, ulong, char
1603                                 // or decimal
1604                                 //
1605                                 if (real_target_type == TypeManager.sbyte_type)
1606                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.R4_I1);
1607                                 if (real_target_type == TypeManager.byte_type)
1608                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.R4_U1);
1609                                 if (real_target_type == TypeManager.short_type)
1610                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.R4_I2);
1611                                 if (real_target_type == TypeManager.ushort_type)
1612                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.R4_U2);
1613                                 if (real_target_type == TypeManager.int32_type)
1614                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.R4_I4);
1615                                 if (real_target_type == TypeManager.uint32_type)
1616                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.R4_U4);
1617                                 if (real_target_type == TypeManager.int64_type)
1618                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.R4_I8);
1619                                 if (real_target_type == TypeManager.uint64_type)
1620                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.R4_U8);
1621                                 if (real_target_type == TypeManager.char_type)
1622                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.R4_CH);
1623                                 if (real_target_type == TypeManager.decimal_type)
1624                                         return InternalTypeConstructor (ec, expr, target_type);
1625                         } else if (expr_type == TypeManager.double_type){
1626                                 //
1627                                 // From double to byte, byte, short,
1628                                 // ushort, int, uint, long, ulong,
1629                                 // char, float or decimal
1630                                 //
1631                                 if (real_target_type == TypeManager.sbyte_type)
1632                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.R8_I1);
1633                                 if (real_target_type == TypeManager.byte_type)
1634                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.R8_U1);
1635                                 if (real_target_type == TypeManager.short_type)
1636                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.R8_I2);
1637                                 if (real_target_type == TypeManager.ushort_type)
1638                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.R8_U2);
1639                                 if (real_target_type == TypeManager.int32_type)
1640                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.R8_I4);
1641                                 if (real_target_type == TypeManager.uint32_type)
1642                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.R8_U4);
1643                                 if (real_target_type == TypeManager.int64_type)
1644                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.R8_I8);
1645                                 if (real_target_type == TypeManager.uint64_type)
1646                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.R8_U8);
1647                                 if (real_target_type == TypeManager.char_type)
1648                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.R8_CH);
1649                                 if (real_target_type == TypeManager.float_type)
1650                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.R8_R4);
1651                                 if (real_target_type == TypeManager.decimal_type)
1652                                         return InternalTypeConstructor (ec, expr, target_type);
1653                         } 
1654
1655                         // decimal is taken care of by the op_Explicit methods.
1656
1657                         return null;
1658                 }
1659
1660                 /// <summary>
1661                 ///  Returns whether an explicit reference conversion can be performed
1662                 ///  from source_type to target_type
1663                 /// </summary>
1664                 static bool ExplicitReferenceConversionExists (Type source_type, Type target_type)
1665                 {
1666                         bool target_is_value_type = target_type.IsValueType;
1667                         
1668                         if (source_type == target_type)
1669                                 return true;
1670                         
1671                         //
1672                         // From object to any reference type
1673                         //
1674                         if (source_type == TypeManager.object_type && !target_is_value_type)
1675                                 return true;
1676                                         
1677                         //
1678                         // From any class S to any class-type T, provided S is a base class of T
1679                         //
1680                         if (target_type.IsSubclassOf (source_type))
1681                                 return true;
1682
1683                         //
1684                         // From any interface type S to any interface T provided S is not derived from T
1685                         //
1686                         if (source_type.IsInterface && target_type.IsInterface){
1687                                 if (!target_type.IsSubclassOf (source_type))
1688                                         return true;
1689                         }
1690                             
1691                         //
1692                         // From any class type S to any interface T, provides S is not sealed
1693                         // and provided S does not implement T.
1694                         //
1695                         if (target_type.IsInterface && !source_type.IsSealed &&
1696                             !target_type.IsAssignableFrom (source_type))
1697                                 return true;
1698
1699                         //
1700                         // From any interface-type S to to any class type T, provided T is not
1701                         // sealed, or provided T implements S.
1702                         //
1703                         if (source_type.IsInterface &&
1704                             (!target_type.IsSealed || source_type.IsAssignableFrom (target_type)))
1705                                 return true;
1706
1707                         // From an array type S with an element type Se to an array type T with an 
1708                         // element type Te provided all the following are true:
1709                         //     * S and T differe only in element type, in other words, S and T
1710                         //       have the same number of dimensions.
1711                         //     * Both Se and Te are reference types
1712                         //     * An explicit referenc conversions exist from Se to Te
1713                         //
1714                         if (source_type.IsArray && target_type.IsArray) {
1715                                 if (source_type.GetArrayRank () == target_type.GetArrayRank ()) {
1716                                         
1717                                         Type source_element_type = source_type.GetElementType ();
1718                                         Type target_element_type = target_type.GetElementType ();
1719                                         
1720                                         if (!source_element_type.IsValueType && !target_element_type.IsValueType)
1721                                                 if (ExplicitReferenceConversionExists (source_element_type,
1722                                                                                        target_element_type))
1723                                                         return true;
1724                                 }
1725                         }
1726                         
1727
1728                         // From System.Array to any array-type
1729                         if (source_type == TypeManager.array_type &&
1730                             target_type.IsSubclassOf (TypeManager.array_type)){
1731                                 return true;
1732                         }
1733
1734                         //
1735                         // From System delegate to any delegate-type
1736                         //
1737                         if (source_type == TypeManager.delegate_type &&
1738                             target_type.IsSubclassOf (TypeManager.delegate_type))
1739                                 return true;
1740
1741                         //
1742                         // From ICloneable to Array or Delegate types
1743                         //
1744                         if (source_type == TypeManager.icloneable_type &&
1745                             (target_type == TypeManager.array_type ||
1746                              target_type == TypeManager.delegate_type))
1747                                 return true;
1748                         
1749                         return false;
1750                 }
1751
1752                 /// <summary>
1753                 ///   Implements Explicit Reference conversions
1754                 /// </summary>
1755                 static Expression ConvertReferenceExplicit (Expression source, Type target_type)
1756                 {
1757                         Type source_type = source.Type;
1758                         bool target_is_value_type = target_type.IsValueType;
1759                         
1760                         //
1761                         // From object to any reference type
1762                         //
1763                         if (source_type == TypeManager.object_type && !target_is_value_type)
1764                                 return new ClassCast (source, target_type);
1765
1766
1767                         //
1768                         // From any class S to any class-type T, provided S is a base class of T
1769                         //
1770                         if (target_type.IsSubclassOf (source_type))
1771                                 return new ClassCast (source, target_type);
1772
1773                         //
1774                         // From any interface type S to any interface T provided S is not derived from T
1775                         //
1776                         if (source_type.IsInterface && target_type.IsInterface){
1777                                 if (TypeManager.ImplementsInterface (source_type, target_type))
1778                                         return null;
1779                                 else
1780                                         return new ClassCast (source, target_type);
1781                         }
1782                             
1783                         //
1784                         // From any class type S to any interface T, provides S is not sealed
1785                         // and provided S does not implement T.
1786                         //
1787                         if (target_type.IsInterface && !source_type.IsSealed) {
1788                                 
1789                                 if (TypeManager.ImplementsInterface (source_type, target_type))
1790                                         return null;
1791                                 else
1792                                         return new ClassCast (source, target_type);
1793                                 
1794                         }
1795
1796                         //
1797                         // From any interface-type S to to any class type T, provided T is not
1798                         // sealed, or provided T implements S.
1799                         //
1800                         if (source_type.IsInterface) {
1801
1802                                 if (target_type.IsSealed)
1803                                         return null;
1804                                 
1805                                 if (TypeManager.ImplementsInterface (target_type, source_type))
1806                                         return new ClassCast (source, target_type);
1807                                 else
1808                                         return null;
1809                         }
1810                         
1811                         // From an array type S with an element type Se to an array type T with an 
1812                         // element type Te provided all the following are true:
1813                         //     * S and T differe only in element type, in other words, S and T
1814                         //       have the same number of dimensions.
1815                         //     * Both Se and Te are reference types
1816                         //     * An explicit referenc conversions exist from Se to Te
1817                         //
1818                         if (source_type.IsArray && target_type.IsArray) {
1819                                 if (source_type.GetArrayRank () == target_type.GetArrayRank ()) {
1820                                         
1821                                         Type source_element_type = source_type.GetElementType ();
1822                                         Type target_element_type = target_type.GetElementType ();
1823                                         
1824                                         if (!source_element_type.IsValueType && !target_element_type.IsValueType)
1825                                                 if (ExplicitReferenceConversionExists (source_element_type,
1826                                                                                        target_element_type))
1827                                                         return new ClassCast (source, target_type);
1828                                 }
1829                         }
1830                         
1831
1832                         // From System.Array to any array-type
1833                         if (source_type == TypeManager.array_type &&
1834                             target_type.IsSubclassOf (TypeManager.array_type)){
1835                                 return new ClassCast (source, target_type);
1836                         }
1837
1838                         //
1839                         // From System delegate to any delegate-type
1840                         //
1841                         if (source_type == TypeManager.delegate_type &&
1842                             target_type.IsSubclassOf (TypeManager.delegate_type))
1843                                 return new ClassCast (source, target_type);
1844
1845                         //
1846                         // From ICloneable to Array or Delegate types
1847                         //
1848                         if (source_type == TypeManager.icloneable_type &&
1849                             (target_type == TypeManager.array_type ||
1850                              target_type == TypeManager.delegate_type))
1851                                 return new ClassCast (source, target_type);
1852                         
1853                         return null;
1854                 }
1855                 
1856                 /// <summary>
1857                 ///   Performs an explicit conversion of the expression `expr' whose
1858                 ///   type is expr.Type to `target_type'.
1859                 /// </summary>
1860                 static public Expression ConvertExplicit (EmitContext ec, Expression expr,
1861                                                           Type target_type, Location loc)
1862                 {
1863                         Type expr_type = expr.Type;
1864                         Expression ne = ConvertImplicitStandard (ec, expr, target_type, loc);
1865
1866                         if (ne != null)
1867                                 return ne;
1868
1869                         ne = ConvertNumericExplicit (ec, expr, target_type);
1870                         if (ne != null)
1871                                 return ne;
1872
1873                         //
1874                         // Unboxing conversion.
1875                         //
1876                         if (expr_type == TypeManager.object_type && target_type.IsValueType)
1877                                 return new UnboxCast (expr, target_type);
1878
1879                         //
1880                         // Enum types
1881                         //
1882                         if (expr_type.IsSubclassOf (TypeManager.enum_type)) {
1883                                 Expression e;
1884
1885                                 //
1886                                 // FIXME: Is there any reason we should have EnumConstant
1887                                 // dealt with here instead of just using always the
1888                                 // UnderlyingSystemType to wrap the type?
1889                                 //
1890                                 if (expr is EnumConstant)
1891                                         e = ((EnumConstant) expr).Child;
1892                                 else {
1893                                         e = new EmptyCast (expr, TypeManager.EnumToUnderlying (expr_type));
1894                                 }
1895                                 
1896                                 Expression t = ConvertImplicit (ec, e, target_type, loc);
1897                                 if (t != null)
1898                                         return t;
1899                                 
1900                                 return ConvertNumericExplicit (ec, e, target_type);
1901                         }
1902                         
1903                         ne = ConvertReferenceExplicit (expr, target_type);
1904                         if (ne != null)
1905                                 return ne;
1906
1907                         if (ec.InUnsafe){
1908                                 if (target_type.IsPointer){
1909                                         if (expr_type.IsPointer)
1910                                                 return new EmptyCast (expr, target_type);
1911                                         
1912                                         if (expr_type == TypeManager.sbyte_type ||
1913                                             expr_type == TypeManager.byte_type ||
1914                                             expr_type == TypeManager.short_type ||
1915                                             expr_type == TypeManager.ushort_type ||
1916                                             expr_type == TypeManager.int32_type ||
1917                                             expr_type == TypeManager.uint32_type ||
1918                                             expr_type == TypeManager.uint64_type ||
1919                                             expr_type == TypeManager.int64_type)
1920                                                 return new OpcodeCast (expr, target_type, OpCodes.Conv_U);
1921                                 }
1922                                 if (expr_type.IsPointer){
1923                                         if (target_type == TypeManager.sbyte_type ||
1924                                             target_type == TypeManager.byte_type ||
1925                                             target_type == TypeManager.short_type ||
1926                                             target_type == TypeManager.ushort_type ||
1927                                             target_type == TypeManager.int32_type ||
1928                                             target_type == TypeManager.uint32_type ||
1929                                             target_type == TypeManager.uint64_type ||
1930                                             target_type == TypeManager.int64_type){
1931                                                 Expression e = new EmptyCast (expr, TypeManager.uint32_type);
1932                                                 Expression ci, ce;
1933
1934                                                 ci = ConvertImplicitStandard (ec, e, target_type, loc);
1935
1936                                                 if (ci != null)
1937                                                         return ci;
1938
1939                                                 ce = ConvertNumericExplicit (ec, e, target_type);
1940                                                 if (ce != null)
1941                                                         return ce;
1942                                                 //
1943                                                 // We should always be able to go from an uint32
1944                                                 // implicitly or explicitly to the other integral
1945                                                 // types
1946                                                 //
1947                                                 throw new Exception ("Internal compiler error");
1948                                         }
1949                                 }
1950                         }
1951                         
1952                         ne = ExplicitUserConversion (ec, expr, target_type, loc);
1953                         if (ne != null)
1954                                 return ne;
1955
1956                         Error_CannotConvertType (loc, expr_type, target_type);
1957                         return null;
1958                 }
1959
1960                 /// <summary>
1961                 ///   Same as ConvertExplicit, only it doesn't include user defined conversions
1962                 /// </summary>
1963                 static public Expression ConvertExplicitStandard (EmitContext ec, Expression expr,
1964                                                                   Type target_type, Location l)
1965                 {
1966                         Expression ne = ConvertImplicitStandard (ec, expr, target_type, l);
1967
1968                         if (ne != null)
1969                                 return ne;
1970
1971                         ne = ConvertNumericExplicit (ec, expr, target_type);
1972                         if (ne != null)
1973                                 return ne;
1974
1975                         ne = ConvertReferenceExplicit (expr, target_type);
1976                         if (ne != null)
1977                                 return ne;
1978
1979                         Error_CannotConvertType (l, expr.Type, target_type);
1980                         return null;
1981                 }
1982
1983                 static string ExprClassName (ExprClass c)
1984                 {
1985                         switch (c){
1986                         case ExprClass.Invalid:
1987                                 return "Invalid";
1988                         case ExprClass.Value:
1989                                 return "value";
1990                         case ExprClass.Variable:
1991                                 return "variable";
1992                         case ExprClass.Namespace:
1993                                 return "namespace";
1994                         case ExprClass.Type:
1995                                 return "type";
1996                         case ExprClass.MethodGroup:
1997                                 return "method group";
1998                         case ExprClass.PropertyAccess:
1999                                 return "property access";
2000                         case ExprClass.EventAccess:
2001                                 return "event access";
2002                         case ExprClass.IndexerAccess:
2003                                 return "indexer access";
2004                         case ExprClass.Nothing:
2005                                 return "null";
2006                         }
2007                         throw new Exception ("Should not happen");
2008                 }
2009                 
2010                 /// <summary>
2011                 ///   Reports that we were expecting `expr' to be of class `expected'
2012                 /// </summary>
2013                 protected void report118 (Location loc, Expression expr, string expected)
2014                 {
2015                         string kind = "Unknown";
2016                         
2017                         if (expr != null)
2018                                 kind = ExprClassName (expr.eclass);
2019
2020                         Error (118, loc, "Expression denotes a `" + kind +
2021                                "' where a `" + expected + "' was expected");
2022                 }
2023
2024                 static void Error_ConstantValueCannotBeConverted (Location l, string val, Type t)
2025                 {
2026                         Report.Error (31, l, "Constant value `" + val + "' cannot be converted to " +
2027                                       TypeManager.CSharpName (t));
2028                 }
2029
2030                 public static void UnsafeError (Location loc)
2031                 {
2032                         Report.Error (214, loc, "Pointers may only be used in an unsafe context");
2033                 }
2034                 
2035                 /// <summary>
2036                 ///   Converts the IntConstant, UIntConstant, LongConstant or
2037                 ///   ULongConstant into the integral target_type.   Notice
2038                 ///   that we do not return an `Expression' we do return
2039                 ///   a boxed integral type.
2040                 ///
2041                 ///   FIXME: Since I added the new constants, we need to
2042                 ///   also support conversions from CharConstant, ByteConstant,
2043                 ///   SByteConstant, UShortConstant, ShortConstant
2044                 ///
2045                 ///   This is used by the switch statement, so the domain
2046                 ///   of work is restricted to the literals above, and the
2047                 ///   targets are int32, uint32, char, byte, sbyte, ushort,
2048                 ///   short, uint64 and int64
2049                 /// </summary>
2050                 public static object ConvertIntLiteral (Constant c, Type target_type, Location loc)
2051                 {
2052                         string s = "";
2053
2054                         if (c.Type == target_type)
2055                                 return ((Constant) c).GetValue ();
2056
2057                         //
2058                         // Make into one of the literals we handle, we dont really care
2059                         // about this value as we will just return a few limited types
2060                         // 
2061                         if (c is EnumConstant)
2062                                 c = ((EnumConstant)c).WidenToCompilerConstant ();
2063
2064                         if (c is IntConstant){
2065                                 int v = ((IntConstant) c).Value;
2066                                 
2067                                 if (target_type == TypeManager.uint32_type){
2068                                         if (v >= 0)
2069                                                 return (uint) v;
2070                                 } else if (target_type == TypeManager.char_type){
2071                                         if (v >= Char.MinValue && v <= Char.MaxValue)
2072                                                 return (char) v;
2073                                 } else if (target_type == TypeManager.byte_type){
2074                                         if (v >= Byte.MinValue && v <= Byte.MaxValue)
2075                                                 return (byte) v;
2076                                 } else if (target_type == TypeManager.sbyte_type){
2077                                         if (v >= SByte.MinValue && v <= SByte.MaxValue)
2078                                                 return (sbyte) v;
2079                                 } else if (target_type == TypeManager.short_type){
2080                                         if (v >= Int16.MinValue && v <= UInt16.MaxValue)
2081                                                 return (short) v;
2082                                 } else if (target_type == TypeManager.ushort_type){
2083                                         if (v >= UInt16.MinValue && v <= UInt16.MaxValue)
2084                                                 return (ushort) v;
2085                                 } else if (target_type == TypeManager.int64_type)
2086                                         return (long) v;
2087                                 else if (target_type == TypeManager.uint64_type){
2088                                         if (v > 0)
2089                                                 return (ulong) v;
2090                                 }
2091
2092                                 s = v.ToString ();
2093                         } else if (c is UIntConstant){
2094                                 uint v = ((UIntConstant) c).Value;
2095
2096                                 if (target_type == TypeManager.int32_type){
2097                                         if (v <= Int32.MaxValue)
2098                                                 return (int) v;
2099                                 } else if (target_type == TypeManager.char_type){
2100                                         if (v >= Char.MinValue && v <= Char.MaxValue)
2101                                                 return (char) v;
2102                                 } else if (target_type == TypeManager.byte_type){
2103                                         if (v <= Byte.MaxValue)
2104                                                 return (byte) v;
2105                                 } else if (target_type == TypeManager.sbyte_type){
2106                                         if (v <= SByte.MaxValue)
2107                                                 return (sbyte) v;
2108                                 } else if (target_type == TypeManager.short_type){
2109                                         if (v <= UInt16.MaxValue)
2110                                                 return (short) v;
2111                                 } else if (target_type == TypeManager.ushort_type){
2112                                         if (v <= UInt16.MaxValue)
2113                                                 return (ushort) v;
2114                                 } else if (target_type == TypeManager.int64_type)
2115                                         return (long) v;
2116                                 else if (target_type == TypeManager.uint64_type)
2117                                         return (ulong) v;
2118                                 s = v.ToString ();
2119                         } else if (c is LongConstant){ 
2120                                 long v = ((LongConstant) c).Value;
2121
2122                                 if (target_type == TypeManager.int32_type){
2123                                         if (v >= UInt32.MinValue && v <= UInt32.MaxValue)
2124                                                 return (int) v;
2125                                 } else if (target_type == TypeManager.uint32_type){
2126                                         if (v >= 0 && v <= UInt32.MaxValue)
2127                                                 return (uint) v;
2128                                 } else if (target_type == TypeManager.char_type){
2129                                         if (v >= Char.MinValue && v <= Char.MaxValue)
2130                                                 return (char) v;
2131                                 } else if (target_type == TypeManager.byte_type){
2132                                         if (v >= Byte.MinValue && v <= Byte.MaxValue)
2133                                                 return (byte) v;
2134                                 } else if (target_type == TypeManager.sbyte_type){
2135                                         if (v >= SByte.MinValue && v <= SByte.MaxValue)
2136                                                 return (sbyte) v;
2137                                 } else if (target_type == TypeManager.short_type){
2138                                         if (v >= Int16.MinValue && v <= UInt16.MaxValue)
2139                                                 return (short) v;
2140                                 } else if (target_type == TypeManager.ushort_type){
2141                                         if (v >= UInt16.MinValue && v <= UInt16.MaxValue)
2142                                                 return (ushort) v;
2143                                 } else if (target_type == TypeManager.uint64_type){
2144                                         if (v > 0)
2145                                                 return (ulong) v;
2146                                 }
2147                                 s = v.ToString ();
2148                         } else if (c is ULongConstant){
2149                                 ulong v = ((ULongConstant) c).Value;
2150
2151                                 if (target_type == TypeManager.int32_type){
2152                                         if (v <= Int32.MaxValue)
2153                                                 return (int) v;
2154                                 } else if (target_type == TypeManager.uint32_type){
2155                                         if (v <= UInt32.MaxValue)
2156                                                 return (uint) v;
2157                                 } else if (target_type == TypeManager.char_type){
2158                                         if (v >= Char.MinValue && v <= Char.MaxValue)
2159                                                 return (char) v;
2160                                 } else if (target_type == TypeManager.byte_type){
2161                                         if (v >= Byte.MinValue && v <= Byte.MaxValue)
2162                                                 return (byte) v;
2163                                 } else if (target_type == TypeManager.sbyte_type){
2164                                         if (v <= (int) SByte.MaxValue)
2165                                                 return (sbyte) v;
2166                                 } else if (target_type == TypeManager.short_type){
2167                                         if (v <= UInt16.MaxValue)
2168                                                 return (short) v;
2169                                 } else if (target_type == TypeManager.ushort_type){
2170                                         if (v <= UInt16.MaxValue)
2171                                                 return (ushort) v;
2172                                 } else if (target_type == TypeManager.int64_type){
2173                                         if (v <= Int64.MaxValue)
2174                                                 return (long) v;
2175                                 }
2176                                 s = v.ToString ();
2177                         } else if (c is ByteConstant){
2178                                 byte v = ((ByteConstant) c).Value;
2179                                 
2180                                 if (target_type == TypeManager.int32_type)
2181                                         return (int) v;
2182                                 else if (target_type == TypeManager.uint32_type)
2183                                         return (uint) v;
2184                                 else if (target_type == TypeManager.char_type)
2185                                         return (char) v;
2186                                 else if (target_type == TypeManager.sbyte_type){
2187                                         if (v <= SByte.MaxValue)
2188                                                 return (sbyte) v;
2189                                 } else if (target_type == TypeManager.short_type)
2190                                         return (short) v;
2191                                 else if (target_type == TypeManager.ushort_type)
2192                                         return (ushort) v;
2193                                 else if (target_type == TypeManager.int64_type)
2194                                         return (long) v;
2195                                 else if (target_type == TypeManager.uint64_type)
2196                                         return (ulong) v;
2197                                 s = v.ToString ();
2198                         } else if (c is SByteConstant){
2199                                 sbyte v = ((SByteConstant) c).Value;
2200                                 
2201                                 if (target_type == TypeManager.int32_type)
2202                                         return (int) v;
2203                                 else if (target_type == TypeManager.uint32_type){
2204                                         if (v >= 0)
2205                                                 return (uint) v;
2206                                 } else if (target_type == TypeManager.char_type){
2207                                         if (v >= 0)
2208                                                 return (char) v;
2209                                 } else if (target_type == TypeManager.byte_type){
2210                                         if (v >= 0)
2211                                                 return (byte) v;
2212                                 } else if (target_type == TypeManager.short_type)
2213                                         return (short) v;
2214                                 else if (target_type == TypeManager.ushort_type){
2215                                         if (v >= 0)
2216                                                 return (ushort) v;
2217                                 } else if (target_type == TypeManager.int64_type)
2218                                         return (long) v;
2219                                 else if (target_type == TypeManager.uint64_type){
2220                                         if (v >= 0)
2221                                                 return (ulong) v;
2222                                 }
2223                                 s = v.ToString ();
2224                         } else if (c is ShortConstant){
2225                                 short v = ((ShortConstant) c).Value;
2226                                 
2227                                 if (target_type == TypeManager.int32_type){
2228                                         return (int) v;
2229                                 } else if (target_type == TypeManager.uint32_type){
2230                                         if (v >= 0)
2231                                                 return (uint) v;
2232                                 } else if (target_type == TypeManager.char_type){
2233                                         if (v >= 0)
2234                                                 return (char) v;
2235                                 } else if (target_type == TypeManager.byte_type){
2236                                         if (v >= Byte.MinValue && v <= Byte.MaxValue)
2237                                                 return (byte) v;
2238                                 } else if (target_type == TypeManager.sbyte_type){
2239                                         if (v >= SByte.MinValue && v <= SByte.MaxValue)
2240                                                 return (sbyte) v;
2241                                 } else if (target_type == TypeManager.ushort_type){
2242                                         if (v >= 0)
2243                                                 return (ushort) v;
2244                                 } else if (target_type == TypeManager.int64_type)
2245                                         return (long) v;
2246                                 else if (target_type == TypeManager.uint64_type)
2247                                         return (ulong) v;
2248
2249                                 s = v.ToString ();
2250                         } else if (c is UShortConstant){
2251                                 ushort v = ((UShortConstant) c).Value;
2252                                 
2253                                 if (target_type == TypeManager.int32_type)
2254                                         return (int) v;
2255                                 else if (target_type == TypeManager.uint32_type)
2256                                         return (uint) v;
2257                                 else if (target_type == TypeManager.char_type){
2258                                         if (v >= Char.MinValue && v <= Char.MaxValue)
2259                                                 return (char) v;
2260                                 } else if (target_type == TypeManager.byte_type){
2261                                         if (v >= Byte.MinValue && v <= Byte.MaxValue)
2262                                                 return (byte) v;
2263                                 } else if (target_type == TypeManager.sbyte_type){
2264                                         if (v <= SByte.MaxValue)
2265                                                 return (byte) v;
2266                                 } else if (target_type == TypeManager.short_type){
2267                                         if (v <= Int16.MaxValue)
2268                                                 return (short) v;
2269                                 } else if (target_type == TypeManager.int64_type)
2270                                         return (long) v;
2271                                 else if (target_type == TypeManager.uint64_type)
2272                                         return (ulong) v;
2273
2274                                 s = v.ToString ();
2275                         } else if (c is CharConstant){
2276                                 char v = ((CharConstant) c).Value;
2277                                 
2278                                 if (target_type == TypeManager.int32_type)
2279                                         return (int) v;
2280                                 else if (target_type == TypeManager.uint32_type)
2281                                         return (uint) v;
2282                                 else if (target_type == TypeManager.byte_type){
2283                                         if (v >= Byte.MinValue && v <= Byte.MaxValue)
2284                                                 return (byte) v;
2285                                 } else if (target_type == TypeManager.sbyte_type){
2286                                         if (v <= SByte.MaxValue)
2287                                                 return (sbyte) v;
2288                                 } else if (target_type == TypeManager.short_type){
2289                                         if (v <= Int16.MaxValue)
2290                                                 return (short) v;
2291                                 } else if (target_type == TypeManager.ushort_type)
2292                                         return (short) v;
2293                                 else if (target_type == TypeManager.int64_type)
2294                                         return (long) v;
2295                                 else if (target_type == TypeManager.uint64_type)
2296                                         return (ulong) v;
2297
2298                                 s = v.ToString ();
2299                         }
2300                         Error_ConstantValueCannotBeConverted (loc, s, target_type);
2301                         return null;
2302                 }
2303
2304                 //
2305                 // Load the object from the pointer.  The `IsReference' is used
2306                 // to control whether we should use Ldind_Ref or LdObj if the
2307                 // value is not a `core' type.
2308                 //
2309                 // Maybe we should try to extract this infromation form the type?
2310                 // TODO: Maybe this is a bug.  The reason we have this flag is because
2311                 // I had almost identical code in ParameterReference (for handling
2312                 // references) and in UnboxCast.
2313                 //
2314                 public static void LoadFromPtr (ILGenerator ig, Type t, bool IsReference)
2315                 {
2316                         if (t == TypeManager.int32_type)
2317                                 ig.Emit (OpCodes.Ldind_I4);
2318                         else if (t == TypeManager.uint32_type)
2319                                 ig.Emit (OpCodes.Ldind_U4);
2320                         else if (t == TypeManager.short_type)
2321                                 ig.Emit (OpCodes.Ldind_I2);
2322                         else if (t == TypeManager.ushort_type)
2323                                 ig.Emit (OpCodes.Ldind_U2);
2324                         else if (t == TypeManager.char_type)
2325                                 ig.Emit (OpCodes.Ldind_U2);
2326                         else if (t == TypeManager.byte_type)
2327                                 ig.Emit (OpCodes.Ldind_U1);
2328                         else if (t == TypeManager.sbyte_type)
2329                                 ig.Emit (OpCodes.Ldind_I1);
2330                         else if (t == TypeManager.uint64_type)
2331                                 ig.Emit (OpCodes.Ldind_I8);
2332                         else if (t == TypeManager.int64_type)
2333                                 ig.Emit (OpCodes.Ldind_I8);
2334                         else if (t == TypeManager.float_type)
2335                                 ig.Emit (OpCodes.Ldind_R4);
2336                         else if (t == TypeManager.double_type)
2337                                 ig.Emit (OpCodes.Ldind_R8);
2338                         else if (t == TypeManager.bool_type)
2339                                 ig.Emit (OpCodes.Ldind_I1);
2340                         else if (t == TypeManager.intptr_type)
2341                                 ig.Emit (OpCodes.Ldind_I);
2342                         else if (TypeManager.IsEnumType (t)){
2343                                 LoadFromPtr (ig, TypeManager.EnumToUnderlying (t), IsReference);
2344                         } else {
2345                                 if (IsReference)
2346                                         ig.Emit (OpCodes.Ldind_Ref);
2347                                 else 
2348                                         ig.Emit (OpCodes.Ldobj, t);
2349                         }
2350                 }
2351
2352                 //
2353                 // The stack contains the pointer and the value of type `type'
2354                 //
2355                 public static void StoreFromPtr (ILGenerator ig, Type type)
2356                 {
2357                         if (type == TypeManager.int32_type || type == TypeManager.uint32_type)
2358                                 ig.Emit (OpCodes.Stind_I4);
2359                         else if (type == TypeManager.int64_type || type == TypeManager.uint64_type)
2360                                 ig.Emit (OpCodes.Stind_I8);
2361                         else if (type == TypeManager.char_type || type == TypeManager.short_type ||
2362                                  type == TypeManager.ushort_type)
2363                                 ig.Emit (OpCodes.Stind_I2);
2364                         else if (type == TypeManager.float_type)
2365                                 ig.Emit (OpCodes.Stind_R4);
2366                         else if (type == TypeManager.double_type)
2367                                 ig.Emit (OpCodes.Stind_R8);
2368                         else if (type == TypeManager.byte_type || type == TypeManager.sbyte_type ||
2369                                  type == TypeManager.bool_type)
2370                                 ig.Emit (OpCodes.Stind_I1);
2371                         else if (type == TypeManager.intptr_type)
2372                                 ig.Emit (OpCodes.Stind_I);
2373                         else
2374                                 ig.Emit (OpCodes.Stind_Ref);
2375                 }
2376                 
2377                 //
2378                 // Returns the size of type `t' if known, otherwise, 0
2379                 //
2380                 public static int GetTypeSize (Type t)
2381                 {
2382                         if (t == TypeManager.int32_type ||
2383                             t == TypeManager.uint32_type ||
2384                             t == TypeManager.float_type)
2385                                 return 4;
2386                         else if (t == TypeManager.int64_type ||
2387                                  t == TypeManager.uint64_type ||
2388                                  t == TypeManager.double_type)
2389                                 return 8;
2390                         else if (t == TypeManager.byte_type ||
2391                                  t == TypeManager.sbyte_type ||
2392                                  t == TypeManager.bool_type)    
2393                                 return 1;
2394                         else if (t == TypeManager.short_type ||
2395                                  t == TypeManager.char_type ||
2396                                  t == TypeManager.ushort_type)
2397                                 return 2;
2398                         else
2399                                 return 0;
2400                 }
2401         }
2402
2403         /// <summary>
2404         ///   This is just a base class for expressions that can
2405         ///   appear on statements (invocations, object creation,
2406         ///   assignments, post/pre increment and decrement).  The idea
2407         ///   being that they would support an extra Emition interface that
2408         ///   does not leave a result on the stack.
2409         /// </summary>
2410         public abstract class ExpressionStatement : Expression {
2411
2412                 /// <summary>
2413                 ///   Requests the expression to be emitted in a `statement'
2414                 ///   context.  This means that no new value is left on the
2415                 ///   stack after invoking this method (constrasted with
2416                 ///   Emit that will always leave a value on the stack).
2417                 /// </summary>
2418                 public abstract void EmitStatement (EmitContext ec);
2419         }
2420
2421         /// <summary>
2422         ///   This kind of cast is used to encapsulate the child
2423         ///   whose type is child.Type into an expression that is
2424         ///   reported to return "return_type".  This is used to encapsulate
2425         ///   expressions which have compatible types, but need to be dealt
2426         ///   at higher levels with.
2427         ///
2428         ///   For example, a "byte" expression could be encapsulated in one
2429         ///   of these as an "unsigned int".  The type for the expression
2430         ///   would be "unsigned int".
2431         ///
2432         /// </summary>
2433         public class EmptyCast : Expression {
2434                 protected Expression child;
2435
2436                 public EmptyCast (Expression child, Type return_type)
2437                 {
2438                         eclass = child.eclass;
2439                         type = return_type;
2440                         this.child = child;
2441                 }
2442
2443                 public override Expression DoResolve (EmitContext ec)
2444                 {
2445                         // This should never be invoked, we are born in fully
2446                         // initialized state.
2447
2448                         return this;
2449                 }
2450
2451                 public override void Emit (EmitContext ec)
2452                 {
2453                         child.Emit (ec);
2454                 }
2455         }
2456
2457         /// <summary>
2458         ///  This class is used to wrap literals which belong inside Enums
2459         /// </summary>
2460         public class EnumConstant : Constant {
2461                 public Constant Child;
2462
2463                 public EnumConstant (Constant child, Type enum_type)
2464                 {
2465                         eclass = child.eclass;
2466                         this.Child = child;
2467                         type = enum_type;
2468                 }
2469                 
2470                 public override Expression DoResolve (EmitContext ec)
2471                 {
2472                         // This should never be invoked, we are born in fully
2473                         // initialized state.
2474
2475                         return this;
2476                 }
2477
2478                 public override void Emit (EmitContext ec)
2479                 {
2480                         Child.Emit (ec);
2481                 }
2482
2483                 public override object GetValue ()
2484                 {
2485                         return Child.GetValue ();
2486                 }
2487
2488                 //
2489                 // Converts from one of the valid underlying types for an enumeration
2490                 // (int32, uint32, int64, uint64, short, ushort, byte, sbyte) to
2491                 // one of the internal compiler literals: Int/UInt/Long/ULong Literals.
2492                 //
2493                 public Constant WidenToCompilerConstant ()
2494                 {
2495                         Type t = TypeManager.EnumToUnderlying (Child.Type);
2496                         object v = ((Constant) Child).GetValue ();;
2497                         
2498                         if (t == TypeManager.int32_type)
2499                                 return new IntConstant ((int) v);
2500                         if (t == TypeManager.uint32_type)
2501                                 return new UIntConstant ((uint) v);
2502                         if (t == TypeManager.int64_type)
2503                                 return new LongConstant ((long) v);
2504                         if (t == TypeManager.uint64_type)
2505                                 return new ULongConstant ((ulong) v);
2506                         if (t == TypeManager.short_type)
2507                                 return new ShortConstant ((short) v);
2508                         if (t == TypeManager.ushort_type)
2509                                 return new UShortConstant ((ushort) v);
2510                         if (t == TypeManager.byte_type)
2511                                 return new ByteConstant ((byte) v);
2512                         if (t == TypeManager.sbyte_type)
2513                                 return new SByteConstant ((sbyte) v);
2514
2515                         throw new Exception ("Invalid enumeration underlying type: " + t);
2516                 }
2517
2518                 //
2519                 // Extracts the value in the enumeration on its native representation
2520                 //
2521                 public object GetPlainValue ()
2522                 {
2523                         Type t = TypeManager.EnumToUnderlying (Child.Type);
2524                         object v = ((Constant) Child).GetValue ();;
2525                         
2526                         if (t == TypeManager.int32_type)
2527                                 return (int) v;
2528                         if (t == TypeManager.uint32_type)
2529                                 return (uint) v;
2530                         if (t == TypeManager.int64_type)
2531                                 return (long) v;
2532                         if (t == TypeManager.uint64_type)
2533                                 return (ulong) v;
2534                         if (t == TypeManager.short_type)
2535                                 return (short) v;
2536                         if (t == TypeManager.ushort_type)
2537                                 return (ushort) v;
2538                         if (t == TypeManager.byte_type)
2539                                 return (byte) v;
2540                         if (t == TypeManager.sbyte_type)
2541                                 return (sbyte) v;
2542
2543                         return null;
2544                 }
2545                 
2546                 public override string AsString ()
2547                 {
2548                         return Child.AsString ();
2549                 }
2550
2551                 public override DoubleConstant ConvertToDouble ()
2552                 {
2553                         return Child.ConvertToDouble ();
2554                 }
2555
2556                 public override FloatConstant ConvertToFloat ()
2557                 {
2558                         return Child.ConvertToFloat ();
2559                 }
2560
2561                 public override ULongConstant ConvertToULong ()
2562                 {
2563                         return Child.ConvertToULong ();
2564                 }
2565
2566                 public override LongConstant ConvertToLong ()
2567                 {
2568                         return Child.ConvertToLong ();
2569                 }
2570
2571                 public override UIntConstant ConvertToUInt ()
2572                 {
2573                         return Child.ConvertToUInt ();
2574                 }
2575
2576                 public override IntConstant ConvertToInt ()
2577                 {
2578                         return Child.ConvertToInt ();
2579                 }
2580         }
2581
2582         /// <summary>
2583         ///   This kind of cast is used to encapsulate Value Types in objects.
2584         ///
2585         ///   The effect of it is to box the value type emitted by the previous
2586         ///   operation.
2587         /// </summary>
2588         public class BoxedCast : EmptyCast {
2589
2590                 public BoxedCast (Expression expr)
2591                         : base (expr, TypeManager.object_type)
2592                 {
2593                 }
2594
2595                 public override Expression DoResolve (EmitContext ec)
2596                 {
2597                         // This should never be invoked, we are born in fully
2598                         // initialized state.
2599
2600                         return this;
2601                 }
2602
2603                 public override void Emit (EmitContext ec)
2604                 {
2605                         base.Emit (ec);
2606                         
2607                         ec.ig.Emit (OpCodes.Box, child.Type);
2608                 }
2609         }
2610
2611         public class UnboxCast : EmptyCast {
2612                 public UnboxCast (Expression expr, Type return_type)
2613                         : base (expr, return_type)
2614                 {
2615                 }
2616
2617                 public override Expression DoResolve (EmitContext ec)
2618                 {
2619                         // This should never be invoked, we are born in fully
2620                         // initialized state.
2621
2622                         return this;
2623                 }
2624
2625                 public override void Emit (EmitContext ec)
2626                 {
2627                         Type t = type;
2628                         ILGenerator ig = ec.ig;
2629                         
2630                         base.Emit (ec);
2631                         ig.Emit (OpCodes.Unbox, t);
2632
2633                         LoadFromPtr (ig, t, false);
2634                 }
2635         }
2636         
2637         /// <summary>
2638         ///   This is used to perform explicit numeric conversions.
2639         ///
2640         ///   Explicit numeric conversions might trigger exceptions in a checked
2641         ///   context, so they should generate the conv.ovf opcodes instead of
2642         ///   conv opcodes.
2643         /// </summary>
2644         public class ConvCast : EmptyCast {
2645                 public enum Mode : byte {
2646                         I1_U1, I1_U2, I1_U4, I1_U8, I1_CH,
2647                         U1_I1, U1_CH,
2648                         I2_I1, I2_U1, I2_U2, I2_U4, I2_U8, I2_CH,
2649                         U2_I1, U2_U1, U2_I2, U2_CH,
2650                         I4_I1, I4_U1, I4_I2, I4_U2, I4_U4, I4_U8, I4_CH,
2651                         U4_I1, U4_U1, U4_I2, U4_U2, U4_I4, U4_CH,
2652                         I8_I1, I8_U1, I8_I2, I8_U2, I8_I4, I8_U4, I8_U8, I8_CH,
2653                         U8_I1, U8_U1, U8_I2, U8_U2, U8_I4, U8_U4, U8_I8, U8_CH,
2654                         CH_I1, CH_U1, CH_I2,
2655                         R4_I1, R4_U1, R4_I2, R4_U2, R4_I4, R4_U4, R4_I8, R4_U8, R4_CH,
2656                         R8_I1, R8_U1, R8_I2, R8_U2, R8_I4, R8_U4, R8_I8, R8_U8, R8_CH, R8_R4
2657                 }
2658
2659                 Mode mode;
2660                 bool checked_state;
2661                 
2662                 public ConvCast (EmitContext ec, Expression child, Type return_type, Mode m)
2663                         : base (child, return_type)
2664                 {
2665                         mode = m;
2666                         checked_state = ec.CheckState;
2667                 }
2668
2669                 public override Expression DoResolve (EmitContext ec)
2670                 {
2671                         // This should never be invoked, we are born in fully
2672                         // initialized state.
2673
2674                         return this;
2675                 }
2676
2677                 public override void Emit (EmitContext ec)
2678                 {
2679                         ILGenerator ig = ec.ig;
2680                         
2681                         base.Emit (ec);
2682
2683                         if (checked_state){
2684                                 switch (mode){
2685                                 case Mode.I1_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
2686                                 case Mode.I1_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
2687                                 case Mode.I1_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
2688                                 case Mode.I1_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
2689                                 case Mode.I1_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
2690
2691                                 case Mode.U1_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
2692                                 case Mode.U1_CH: /* nothing */ break;
2693
2694                                 case Mode.I2_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
2695                                 case Mode.I2_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
2696                                 case Mode.I2_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
2697                                 case Mode.I2_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
2698                                 case Mode.I2_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
2699                                 case Mode.I2_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
2700
2701                                 case Mode.U2_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
2702                                 case Mode.U2_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
2703                                 case Mode.U2_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
2704                                 case Mode.U2_CH: /* nothing */ break;
2705
2706                                 case Mode.I4_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
2707                                 case Mode.I4_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
2708                                 case Mode.I4_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
2709                                 case Mode.I4_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
2710                                 case Mode.I4_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
2711                                 case Mode.I4_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
2712                                 case Mode.I4_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
2713
2714                                 case Mode.U4_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
2715                                 case Mode.U4_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
2716                                 case Mode.U4_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
2717                                 case Mode.U4_U2: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
2718                                 case Mode.U4_I4: ig.Emit (OpCodes.Conv_Ovf_I4_Un); break;
2719                                 case Mode.U4_CH: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
2720
2721                                 case Mode.I8_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
2722                                 case Mode.I8_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
2723                                 case Mode.I8_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
2724                                 case Mode.I8_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
2725                                 case Mode.I8_I4: ig.Emit (OpCodes.Conv_Ovf_I4); break;
2726                                 case Mode.I8_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
2727                                 case Mode.I8_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
2728                                 case Mode.I8_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
2729
2730                                 case Mode.U8_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
2731                                 case Mode.U8_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
2732                                 case Mode.U8_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
2733                                 case Mode.U8_U2: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
2734                                 case Mode.U8_I4: ig.Emit (OpCodes.Conv_Ovf_I4_Un); break;
2735                                 case Mode.U8_U4: ig.Emit (OpCodes.Conv_Ovf_U4_Un); break;
2736                                 case Mode.U8_I8: ig.Emit (OpCodes.Conv_Ovf_I8_Un); break;
2737                                 case Mode.U8_CH: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
2738
2739                                 case Mode.CH_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
2740                                 case Mode.CH_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
2741                                 case Mode.CH_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
2742
2743                                 case Mode.R4_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
2744                                 case Mode.R4_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
2745                                 case Mode.R4_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
2746                                 case Mode.R4_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
2747                                 case Mode.R4_I4: ig.Emit (OpCodes.Conv_Ovf_I4); break;
2748                                 case Mode.R4_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
2749                                 case Mode.R4_I8: ig.Emit (OpCodes.Conv_Ovf_I8); break;
2750                                 case Mode.R4_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
2751                                 case Mode.R4_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
2752
2753                                 case Mode.R8_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
2754                                 case Mode.R8_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
2755                                 case Mode.R8_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
2756                                 case Mode.R8_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
2757                                 case Mode.R8_I4: ig.Emit (OpCodes.Conv_Ovf_I4); break;
2758                                 case Mode.R8_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
2759                                 case Mode.R8_I8: ig.Emit (OpCodes.Conv_Ovf_I8); break;
2760                                 case Mode.R8_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
2761                                 case Mode.R8_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
2762                                 case Mode.R8_R4: ig.Emit (OpCodes.Conv_R4); break;
2763                                 }
2764                         } else {
2765                                 switch (mode){
2766                                 case Mode.I1_U1: ig.Emit (OpCodes.Conv_U1); break;
2767                                 case Mode.I1_U2: ig.Emit (OpCodes.Conv_U2); break;
2768                                 case Mode.I1_U4: ig.Emit (OpCodes.Conv_U4); break;
2769                                 case Mode.I1_U8: ig.Emit (OpCodes.Conv_I8); break;
2770                                 case Mode.I1_CH: ig.Emit (OpCodes.Conv_U2); break;
2771
2772                                 case Mode.U1_I1: ig.Emit (OpCodes.Conv_I1); break;
2773                                 case Mode.U1_CH: ig.Emit (OpCodes.Conv_U2); break;
2774
2775                                 case Mode.I2_I1: ig.Emit (OpCodes.Conv_I1); break;
2776                                 case Mode.I2_U1: ig.Emit (OpCodes.Conv_U1); break;
2777                                 case Mode.I2_U2: ig.Emit (OpCodes.Conv_U2); break;
2778                                 case Mode.I2_U4: ig.Emit (OpCodes.Conv_U4); break;
2779                                 case Mode.I2_U8: ig.Emit (OpCodes.Conv_I8); break;
2780                                 case Mode.I2_CH: ig.Emit (OpCodes.Conv_U2); break;
2781
2782                                 case Mode.U2_I1: ig.Emit (OpCodes.Conv_I1); break;
2783                                 case Mode.U2_U1: ig.Emit (OpCodes.Conv_U1); break;
2784                                 case Mode.U2_I2: ig.Emit (OpCodes.Conv_I2); break;
2785                                 case Mode.U2_CH: /* nothing */ break;
2786
2787                                 case Mode.I4_I1: ig.Emit (OpCodes.Conv_I1); break;
2788                                 case Mode.I4_U1: ig.Emit (OpCodes.Conv_U1); break;
2789                                 case Mode.I4_I2: ig.Emit (OpCodes.Conv_I2); break;
2790                                 case Mode.I4_U4: /* nothing */ break;
2791                                 case Mode.I4_U2: ig.Emit (OpCodes.Conv_U2); break;
2792                                 case Mode.I4_U8: ig.Emit (OpCodes.Conv_I8); break;
2793                                 case Mode.I4_CH: ig.Emit (OpCodes.Conv_U2); break;
2794
2795                                 case Mode.U4_I1: ig.Emit (OpCodes.Conv_I1); break;
2796                                 case Mode.U4_U1: ig.Emit (OpCodes.Conv_U1); break;
2797                                 case Mode.U4_I2: ig.Emit (OpCodes.Conv_I2); break;
2798                                 case Mode.U4_U2: ig.Emit (OpCodes.Conv_U2); break;
2799                                 case Mode.U4_I4: /* nothing */ break;
2800                                 case Mode.U4_CH: ig.Emit (OpCodes.Conv_U2); break;
2801
2802                                 case Mode.I8_I1: ig.Emit (OpCodes.Conv_I1); break;
2803                                 case Mode.I8_U1: ig.Emit (OpCodes.Conv_U1); break;
2804                                 case Mode.I8_I2: ig.Emit (OpCodes.Conv_I2); break;
2805                                 case Mode.I8_U2: ig.Emit (OpCodes.Conv_U2); break;
2806                                 case Mode.I8_I4: ig.Emit (OpCodes.Conv_I4); break;
2807                                 case Mode.I8_U4: ig.Emit (OpCodes.Conv_U4); break;
2808                                 case Mode.I8_U8: /* nothing */ break;
2809                                 case Mode.I8_CH: ig.Emit (OpCodes.Conv_U2); break;
2810
2811                                 case Mode.U8_I1: ig.Emit (OpCodes.Conv_I1); break;
2812                                 case Mode.U8_U1: ig.Emit (OpCodes.Conv_U1); break;
2813                                 case Mode.U8_I2: ig.Emit (OpCodes.Conv_I2); break;
2814                                 case Mode.U8_U2: ig.Emit (OpCodes.Conv_U2); break;
2815                                 case Mode.U8_I4: ig.Emit (OpCodes.Conv_I4); break;
2816                                 case Mode.U8_U4: ig.Emit (OpCodes.Conv_U4); break;
2817                                 case Mode.U8_I8: /* nothing */ break;
2818                                 case Mode.U8_CH: ig.Emit (OpCodes.Conv_U2); break;
2819
2820                                 case Mode.CH_I1: ig.Emit (OpCodes.Conv_I1); break;
2821                                 case Mode.CH_U1: ig.Emit (OpCodes.Conv_U1); break;
2822                                 case Mode.CH_I2: ig.Emit (OpCodes.Conv_I2); break;
2823
2824                                 case Mode.R4_I1: ig.Emit (OpCodes.Conv_I1); break;
2825                                 case Mode.R4_U1: ig.Emit (OpCodes.Conv_U1); break;
2826                                 case Mode.R4_I2: ig.Emit (OpCodes.Conv_I2); break;
2827                                 case Mode.R4_U2: ig.Emit (OpCodes.Conv_U2); break;
2828                                 case Mode.R4_I4: ig.Emit (OpCodes.Conv_I4); break;
2829                                 case Mode.R4_U4: ig.Emit (OpCodes.Conv_U4); break;
2830                                 case Mode.R4_I8: ig.Emit (OpCodes.Conv_I8); break;
2831                                 case Mode.R4_U8: ig.Emit (OpCodes.Conv_U8); break;
2832                                 case Mode.R4_CH: ig.Emit (OpCodes.Conv_U2); break;
2833
2834                                 case Mode.R8_I1: ig.Emit (OpCodes.Conv_I1); break;
2835                                 case Mode.R8_U1: ig.Emit (OpCodes.Conv_U1); break;
2836                                 case Mode.R8_I2: ig.Emit (OpCodes.Conv_I2); break;
2837                                 case Mode.R8_U2: ig.Emit (OpCodes.Conv_U2); break;
2838                                 case Mode.R8_I4: ig.Emit (OpCodes.Conv_I4); break;
2839                                 case Mode.R8_U4: ig.Emit (OpCodes.Conv_U4); break;
2840                                 case Mode.R8_I8: ig.Emit (OpCodes.Conv_I8); break;
2841                                 case Mode.R8_U8: ig.Emit (OpCodes.Conv_U8); break;
2842                                 case Mode.R8_CH: ig.Emit (OpCodes.Conv_U2); break;
2843                                 case Mode.R8_R4: ig.Emit (OpCodes.Conv_R4); break;
2844                                 }
2845                         }
2846                 }
2847         }
2848         
2849         public class OpcodeCast : EmptyCast {
2850                 OpCode op, op2;
2851                 bool second_valid;
2852                 
2853                 public OpcodeCast (Expression child, Type return_type, OpCode op)
2854                         : base (child, return_type)
2855                         
2856                 {
2857                         this.op = op;
2858                         second_valid = false;
2859                 }
2860
2861                 public OpcodeCast (Expression child, Type return_type, OpCode op, OpCode op2)
2862                         : base (child, return_type)
2863                         
2864                 {
2865                         this.op = op;
2866                         this.op2 = op2;
2867                         second_valid = true;
2868                 }
2869
2870                 public override Expression DoResolve (EmitContext ec)
2871                 {
2872                         // This should never be invoked, we are born in fully
2873                         // initialized state.
2874
2875                         return this;
2876                 }
2877
2878                 public override void Emit (EmitContext ec)
2879                 {
2880                         base.Emit (ec);
2881                         ec.ig.Emit (op);
2882
2883                         if (second_valid)
2884                                 ec.ig.Emit (op2);
2885                 }                       
2886         }
2887
2888         /// <summary>
2889         ///   This kind of cast is used to encapsulate a child and cast it
2890         ///   to the class requested
2891         /// </summary>
2892         public class ClassCast : EmptyCast {
2893                 public ClassCast (Expression child, Type return_type)
2894                         : base (child, return_type)
2895                         
2896                 {
2897                 }
2898
2899                 public override Expression DoResolve (EmitContext ec)
2900                 {
2901                         // This should never be invoked, we are born in fully
2902                         // initialized state.
2903
2904                         return this;
2905                 }
2906
2907                 public override void Emit (EmitContext ec)
2908                 {
2909                         base.Emit (ec);
2910
2911                         ec.ig.Emit (OpCodes.Castclass, type);
2912                 }                       
2913                 
2914         }
2915         
2916         /// <summary>
2917         ///   SimpleName expressions are initially formed of a single
2918         ///   word and it only happens at the beginning of the expression.
2919         /// </summary>
2920         ///
2921         /// <remarks>
2922         ///   The expression will try to be bound to a Field, a Method
2923         ///   group or a Property.  If those fail we pass the name to our
2924         ///   caller and the SimpleName is compounded to perform a type
2925         ///   lookup.  The idea behind this process is that we want to avoid
2926         ///   creating a namespace map from the assemblies, as that requires
2927         ///   the GetExportedTypes function to be called and a hashtable to
2928         ///   be constructed which reduces startup time.  If later we find
2929         ///   that this is slower, we should create a `NamespaceExpr' expression
2930         ///   that fully participates in the resolution process. 
2931         ///   
2932         ///   For example `System.Console.WriteLine' is decomposed into
2933         ///   MemberAccess (MemberAccess (SimpleName ("System"), "Console"), "WriteLine")
2934         ///   
2935         ///   The first SimpleName wont produce a match on its own, so it will
2936         ///   be turned into:
2937         ///   MemberAccess (SimpleName ("System.Console"), "WriteLine").
2938         ///   
2939         ///   System.Console will produce a TypeExpr match.
2940         ///   
2941         ///   The downside of this is that we might be hitting `LookupType' too many
2942         ///   times with this scheme.
2943         /// </remarks>
2944         public class SimpleName : Expression {
2945                 public readonly string Name;
2946                 public readonly Location Location;
2947                 
2948                 public SimpleName (string name, Location l)
2949                 {
2950                         Name = name;
2951                         Location = l;
2952                 }
2953
2954                 public static void Error120 (Location l, string name)
2955                 {
2956                         Report.Error (
2957                                 120, l,
2958                                 "An object reference is required " +
2959                                 "for the non-static field `"+name+"'");
2960                 }
2961                 
2962                 //
2963                 // Checks whether we are trying to access an instance
2964                 // property, method or field from a static body.
2965                 //
2966                 Expression MemberStaticCheck (Expression e)
2967                 {
2968                         if (e is FieldExpr){
2969                                 FieldInfo fi = ((FieldExpr) e).FieldInfo;
2970                                 
2971                                 if (!fi.IsStatic){
2972                                         Error120 (Location, Name);
2973                                         return null;
2974                                 }
2975                         } else if (e is MethodGroupExpr){
2976                                 MethodGroupExpr mg = (MethodGroupExpr) e;
2977
2978                                 if (!mg.RemoveInstanceMethods ()){
2979                                         Error120 (Location, mg.Methods [0].Name);
2980                                         return null;
2981                                 }
2982                                 return e;
2983                         } else if (e is PropertyExpr){
2984                                 if (!((PropertyExpr) e).IsStatic){
2985                                         Error120 (Location, Name);
2986                                         return null;
2987                                 }
2988                         } else if (e is EventExpr) {
2989                                 if (!((EventExpr) e).IsStatic) {
2990                                         Error120 (Location, Name);
2991                                         return null;
2992                                 }
2993                         }
2994
2995                         return e;
2996                 }
2997                 
2998                 public override Expression DoResolve (EmitContext ec)
2999                 {
3000                         return SimpleNameResolve (ec, false);
3001                 }
3002
3003                 public Expression DoResolveAllowStatic (EmitContext ec)
3004                 {
3005                         return SimpleNameResolve (ec, true);
3006                 }
3007
3008                 /// <remarks>
3009                 ///   7.5.2: Simple Names. 
3010                 ///
3011                 ///   Local Variables and Parameters are handled at
3012                 ///   parse time, so they never occur as SimpleNames.
3013                 ///
3014                 ///   The `allow_static' flag is used by MemberAccess only
3015                 ///   and it is used to inform us that it is ok for us to 
3016                 ///   avoid the static check, because MemberAccess might end
3017                 ///   up resolving the Name as a Type name and the access as
3018                 ///   a static type access.
3019                 ///
3020                 ///   ie: Type Type; .... { Type.GetType (""); }
3021                 ///
3022                 ///   Type is both an instance variable and a Type;  Type.GetType
3023                 ///   is the static method not an instance method of type.
3024                 /// </remarks>
3025                 Expression SimpleNameResolve (EmitContext ec, bool allow_static)
3026                 {
3027                         Expression e = null;
3028
3029                         //
3030                         // Stage 1: Performed by the parser (binding to locals or parameters).
3031                         //
3032                         if (!ec.OnlyLookupTypes){
3033                                 Block current_block = ec.CurrentBlock;
3034                                 if (current_block != null && current_block.IsVariableDefined (Name)){
3035                                         LocalVariableReference var;
3036                                         
3037                                         var = new LocalVariableReference (ec.CurrentBlock, Name, Location);
3038                                         
3039                                         return var.Resolve (ec);
3040                                 }
3041                         
3042                                 //
3043                                 // Stage 2: Lookup members 
3044                                 //
3045
3046                                 //
3047                                 // For enums, the TypeBuilder is not ec.DeclSpace.TypeBuilder
3048                                 // Hence we have two different cases
3049                                 //
3050
3051                                 DeclSpace lookup_ds = ec.DeclSpace;
3052                                 do {
3053                                         if (lookup_ds.TypeBuilder == null)
3054                                                 break;
3055
3056                                         e = MemberLookup (ec, lookup_ds.TypeBuilder, Name, Location);
3057                                         if (e != null)
3058                                                 break;
3059
3060                                         //
3061                                         // Classes/structs keep looking, enums break
3062                                         //
3063                                         if (lookup_ds is TypeContainer)
3064                                                 lookup_ds = ((TypeContainer) lookup_ds).Parent;
3065                                         else
3066                                                 break;
3067                                 } while (lookup_ds != null);
3068                                 
3069                                 if (e == null && ec.ContainerType != null)
3070                                         e = MemberLookup (ec, ec.ContainerType, Name, Location);
3071                         }
3072
3073                         // Continuation of stage 2
3074                         if (e == null){
3075                                 //
3076                                 // Stage 3: Lookup symbol in the various namespaces. 
3077                                 //
3078                                 DeclSpace ds = ec.DeclSpace;
3079                                 Type t;
3080                                 string alias_value;
3081
3082                                 if ((t = RootContext.LookupType (ds, Name, true, Location)) != null)
3083                                         return new TypeExpr (t);
3084                                 
3085                                 //
3086                                 // Stage 2 part b: Lookup up if we are an alias to a type
3087                                 // or a namespace.
3088                                 //
3089                                 // Since we are cheating: we only do the Alias lookup for
3090                                 // namespaces if the name does not include any dots in it
3091                                 //
3092                                 
3093                                 if (Name.IndexOf ('.') == -1 && (alias_value = ec.TypeContainer.LookupAlias (Name)) != null) {
3094                                 // System.Console.WriteLine (Name + " --> " + alias_value);
3095                                         if ((t = RootContext.LookupType (ds, alias_value, true, Location))
3096                                             != null)
3097                                                 return new TypeExpr (t);
3098                                         
3099                                 // we have alias value, but it isn't Type, so try if it's namespace
3100                                         return new SimpleName (alias_value, Location);
3101                                 }
3102                                 
3103                                 // No match, maybe our parent can compose us
3104                                 // into something meaningful.
3105                                 return this;
3106                         }
3107                         
3108                         //
3109                         // Stage 2 continues here. 
3110                         // 
3111                         if (e is TypeExpr)
3112                                 return e;
3113
3114                         if (ec.OnlyLookupTypes)
3115                                 return null;
3116                         
3117                         if (e is FieldExpr){
3118                                 FieldExpr fe = (FieldExpr) e;
3119                                 FieldInfo fi = fe.FieldInfo;
3120
3121                                 if (fi.FieldType.IsPointer && !ec.InUnsafe){
3122                                         UnsafeError (Location);
3123                                 }
3124                                 
3125                                 if (ec.IsStatic){
3126                                         if (!allow_static && !fi.IsStatic){
3127                                                 Error120 (Location, Name);
3128                                                 return null;
3129                                         }
3130                                 } else {
3131                                         // If we are not in static code and this
3132                                         // field is not static, set the instance to `this'.
3133
3134                                         if (!fi.IsStatic)
3135                                                 fe.InstanceExpression = ec.This;
3136                                 }
3137
3138                                 
3139                                 if (fi is FieldBuilder) {
3140                                         Const c = TypeManager.LookupConstant ((FieldBuilder) fi);
3141                                         
3142                                         if (c != null) {
3143                                                 object o = c.LookupConstantValue (ec);
3144                                                 object real_value = ((Constant)c.Expr).GetValue ();
3145                                                 return Constantify (real_value, fi.FieldType);
3146                                         }
3147                                 }
3148
3149                                 if (fi.IsLiteral) {
3150                                         Type t = fi.FieldType;
3151                                         Type decl_type = fi.DeclaringType;
3152                                         object o;
3153
3154                                         if (fi is FieldBuilder)
3155                                                 o = TypeManager.GetValue ((FieldBuilder) fi);
3156                                         else
3157                                                 o = fi.GetValue (fi);
3158                                         
3159                                         if (decl_type.IsSubclassOf (TypeManager.enum_type)) {
3160                                                 Expression enum_member = MemberLookup (
3161                                                         ec, decl_type, "value__", MemberTypes.Field,
3162                                                         AllBindingFlags, Location); 
3163
3164                                                 Enum en = TypeManager.LookupEnum (decl_type);
3165
3166                                                 Constant c;
3167                                                 if (en != null)
3168                                                         c = Constantify (o, en.UnderlyingType);
3169                                                 else 
3170                                                         c = Constantify (o, enum_member.Type);
3171                                                 
3172                                                 return new EnumConstant (c, decl_type);
3173                                         }
3174                                         
3175                                         Expression exp = Constantify (o, t);
3176                                 }
3177                                         
3178                                 return e;
3179                         }                               
3180
3181                         if (e is EventExpr) {
3182                                 //
3183                                 // If the event is local to this class, we transform ourselves into
3184                                 // a FieldExpr
3185                                 //
3186                                 EventExpr ee = (EventExpr) e;
3187
3188                                 Expression ml = MemberLookup (
3189                                         ec, ec.DeclSpace.TypeBuilder, ee.EventInfo.Name,
3190                                         MemberTypes.Event, AllBindingFlags, Location);
3191
3192                                 if (ml != null) {
3193                                         MemberInfo mi = ec.TypeContainer.GetFieldFromEvent ((EventExpr) ml);
3194
3195                                         if (mi == null) {
3196                                                 //
3197                                                 // If this happens, then we have an event with its own
3198                                                 // accessors and private field etc so there's no need
3199                                                 // to transform ourselves : we should instead flag an error
3200                                                 //
3201                                                 Assign.error70 (ee.EventInfo, Location);
3202                                                 return null;
3203                                         }
3204
3205                                         ml = ExprClassFromMemberInfo (ec, mi, Location);
3206                                         
3207                                         if (ml == null) {
3208                                                 Report.Error (-200, Location, "Internal error!!");
3209                                                 return null;
3210                                         }
3211
3212                                         Expression instance_expr;
3213                                         
3214                                         FieldInfo fi = ((FieldExpr) ml).FieldInfo;
3215
3216                                         if (fi.IsStatic)
3217                                                 instance_expr = null;
3218                                         else
3219                                                 instance_expr = ec.This;
3220
3221                                         instance_expr = instance_expr.Resolve (ec);
3222
3223                                         if (instance_expr != null)
3224                                                 instance_expr = instance_expr.Resolve (ec);
3225                                         
3226                                         return MemberAccess.ResolveMemberAccess (ec, ml, instance_expr, Location, null);
3227                                 }
3228                         }
3229                                 
3230                         
3231                         if (ec.IsStatic){
3232                                 if (allow_static)
3233                                         return e;
3234
3235                                 return MemberStaticCheck (e);
3236                         } else
3237                                 return e;
3238                 }
3239
3240                 public override void Emit (EmitContext ec)
3241                 {
3242                         //
3243                         // If this is ever reached, then we failed to
3244                         // find the name as a namespace
3245                         //
3246
3247                         Error (103, Location, "The name `" + Name +
3248                                "' does not exist in the class `" +
3249                                ec.DeclSpace.Name + "'");
3250                 }
3251         }
3252         
3253         /// <summary>
3254         ///   Fully resolved expression that evaluates to a type
3255         /// </summary>
3256         public class TypeExpr : Expression {
3257                 public TypeExpr (Type t)
3258                 {
3259                         Type = t;
3260                         eclass = ExprClass.Type;
3261                 }
3262
3263                 override public Expression DoResolve (EmitContext ec)
3264                 {
3265                         return this;
3266                 }
3267
3268                 override public void Emit (EmitContext ec)
3269                 {
3270                         throw new Exception ("Implement me");
3271                 }
3272         }
3273
3274         /// <summary>
3275         ///   MethodGroup Expression.
3276         ///  
3277         ///   This is a fully resolved expression that evaluates to a type
3278         /// </summary>
3279         public class MethodGroupExpr : Expression {
3280                 public MethodBase [] Methods;
3281                 Location loc;
3282                 Expression instance_expression = null;
3283                 
3284                 public MethodGroupExpr (MemberInfo [] mi, Location l)
3285                 {
3286                         Methods = new MethodBase [mi.Length];
3287                         mi.CopyTo (Methods, 0);
3288                         eclass = ExprClass.MethodGroup;
3289                         type = TypeManager.object_type;
3290                         loc = l;
3291                 }
3292
3293                 public MethodGroupExpr (ArrayList list, Location l)
3294                 {
3295                         Methods = new MethodBase [list.Count];
3296
3297                         try {
3298                                 list.CopyTo (Methods, 0);
3299                         } catch {
3300                                 foreach (MemberInfo m in list){
3301                                         if (!(m is MethodBase)){
3302                                                 Console.WriteLine ("Name " + m.Name);
3303                                                 Console.WriteLine ("Found a: " + m.GetType ().FullName);
3304                                         }
3305                                 }
3306                                 throw;
3307                         }
3308                         loc = l;
3309                         eclass = ExprClass.MethodGroup;
3310                         type = TypeManager.object_type;
3311                 }
3312                 
3313                 //
3314                 // `A method group may have associated an instance expression' 
3315                 // 
3316                 public Expression InstanceExpression {
3317                         get {
3318                                 return instance_expression;
3319                         }
3320
3321                         set {
3322                                 instance_expression = value;
3323                         }
3324                 }
3325                 
3326                 override public Expression DoResolve (EmitContext ec)
3327                 {
3328                         return this;
3329                 }
3330
3331                 public void ReportUsageError ()
3332                 {
3333                         Report.Error (654, loc, "Method `" + Methods [0].DeclaringType + "." +
3334                                       Methods [0].Name + "()' is referenced without parentheses");
3335                 }
3336
3337                 override public void Emit (EmitContext ec)
3338                 {
3339                         ReportUsageError ();
3340                 }
3341
3342                 bool RemoveMethods (bool keep_static)
3343                 {
3344                         ArrayList smethods = new ArrayList ();
3345                         int top = Methods.Length;
3346                         int i;
3347                         
3348                         for (i = 0; i < top; i++){
3349                                 MethodBase mb = Methods [i];
3350
3351                                 if (mb.IsStatic == keep_static)
3352                                         smethods.Add (mb);
3353                         }
3354
3355                         if (smethods.Count == 0)
3356                                 return false;
3357
3358                         Methods = new MethodBase [smethods.Count];
3359                         smethods.CopyTo (Methods, 0);
3360
3361                         return true;
3362                 }
3363                 
3364                 /// <summary>
3365                 ///   Removes any instance methods from the MethodGroup, returns
3366                 ///   false if the resulting set is empty.
3367                 /// </summary>
3368                 public bool RemoveInstanceMethods ()
3369                 {
3370                         return RemoveMethods (true);
3371                 }
3372
3373                 /// <summary>
3374                 ///   Removes any static methods from the MethodGroup, returns
3375                 ///   false if the resulting set is empty.
3376                 /// </summary>
3377                 public bool RemoveStaticMethods ()
3378                 {
3379                         return RemoveMethods (false);
3380                 }
3381         }
3382
3383         /// <summary>
3384         ///   Fully resolved expression that evaluates to a Field
3385         /// </summary>
3386         public class FieldExpr : Expression, IAssignMethod, IMemoryLocation {
3387                 public readonly FieldInfo FieldInfo;
3388                 public Expression InstanceExpression;
3389                 Location loc;
3390                 
3391                 public FieldExpr (FieldInfo fi, Location l)
3392                 {
3393                         FieldInfo = fi;
3394                         eclass = ExprClass.Variable;
3395                         type = fi.FieldType;
3396                         loc = l;
3397                 }
3398
3399                 override public Expression DoResolve (EmitContext ec)
3400                 {
3401                         if (!FieldInfo.IsStatic){
3402                                 if (InstanceExpression == null){
3403                                         throw new Exception ("non-static FieldExpr without instance var\n" +
3404                                                              "You have to assign the Instance variable\n" +
3405                                                              "Of the FieldExpr to set this\n");
3406                                 }
3407
3408                                 InstanceExpression = InstanceExpression.Resolve (ec);
3409                                 if (InstanceExpression == null)
3410                                         return null;
3411                         }
3412
3413                         return this;
3414                 }
3415
3416                 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
3417                 {
3418                         Expression e = DoResolve (ec);
3419
3420                         if (e == null)
3421                                 return null;
3422                         
3423                         if (!FieldInfo.IsInitOnly)
3424                                 return this;
3425
3426                         //
3427                         // InitOnly fields can only be assigned in constructors
3428                         //
3429
3430                         if (ec.IsConstructor)
3431                                 return this;
3432
3433                         Report.Error (191, loc,
3434                                       "Readonly field can not be assigned outside " +
3435                                       "of constructor or variable initializer");
3436                         
3437                         return null;
3438                 }
3439
3440                 override public void Emit (EmitContext ec)
3441                 {
3442                         ILGenerator ig = ec.ig;
3443                         bool is_volatile = false;
3444                                 
3445                         if (FieldInfo is FieldBuilder){
3446                                 FieldBase f = TypeManager.GetField (FieldInfo);
3447
3448                                 if ((f.ModFlags & Modifiers.VOLATILE) != 0)
3449                                         is_volatile = true;
3450                                 
3451                                 f.status |= Field.Status.USED;
3452                         }
3453                         
3454                         if (FieldInfo.IsStatic){
3455                                 if (is_volatile)
3456                                         ig.Emit (OpCodes.Volatile);
3457                                 
3458                                 ig.Emit (OpCodes.Ldsfld, FieldInfo);
3459                         } else {
3460                                 if (InstanceExpression.Type.IsValueType){
3461                                         IMemoryLocation ml;
3462                                         LocalTemporary tempo = null;
3463                                         
3464                                         if (!(InstanceExpression is IMemoryLocation)){
3465                                                 tempo = new LocalTemporary (
3466                                                         ec, InstanceExpression.Type);
3467
3468                                                 InstanceExpression.Emit (ec);
3469                                                 tempo.Store (ec);
3470                                                 ml = tempo;
3471                                         } else
3472                                                 ml = (IMemoryLocation) InstanceExpression;
3473
3474                                         ml.AddressOf (ec, AddressOp.Load);
3475                                 } else 
3476                                         InstanceExpression.Emit (ec);
3477
3478                                 if (is_volatile)
3479                                         ig.Emit (OpCodes.Volatile);
3480                                 
3481                                 ig.Emit (OpCodes.Ldfld, FieldInfo);
3482                         }
3483                 }
3484
3485                 public void EmitAssign (EmitContext ec, Expression source)
3486                 {
3487                         bool is_static = FieldInfo.IsStatic;
3488                         ILGenerator ig = ec.ig;
3489                         
3490                         if (!is_static){
3491                                 Expression instance = InstanceExpression;
3492
3493                                 if (instance.Type.IsValueType){
3494                                         if (instance is IMemoryLocation){
3495                                                 IMemoryLocation ml = (IMemoryLocation) instance;
3496
3497                                                 ml.AddressOf (ec, AddressOp.Store);
3498                                         } else
3499                                                 throw new Exception ("The " + instance + " of type " +
3500                                                                      instance.Type +
3501                                                                      " represents a ValueType and does " +
3502                                                                      "not implement IMemoryLocation");
3503                                 } else
3504                                         instance.Emit (ec);
3505                         }
3506                         source.Emit (ec);
3507
3508                         if (FieldInfo is FieldBuilder){
3509                                 FieldBase f = TypeManager.GetField (FieldInfo);
3510                                 
3511                                 if ((f.ModFlags & Modifiers.VOLATILE) != 0)
3512                                         ig.Emit (OpCodes.Volatile);
3513                         }
3514                         
3515                         if (is_static)
3516                                 ig.Emit (OpCodes.Stsfld, FieldInfo);
3517                         else 
3518                                 ig.Emit (OpCodes.Stfld, FieldInfo);
3519
3520                         if (FieldInfo is FieldBuilder){
3521                                 FieldBase f = TypeManager.GetField (FieldInfo);
3522
3523                                 f.status |= Field.Status.ASSIGNED;
3524                         }
3525                 }
3526                 
3527                 public void AddressOf (EmitContext ec, AddressOp mode)
3528                 {
3529                         ILGenerator ig = ec.ig;
3530                         
3531                         if (FieldInfo is FieldBuilder){
3532                                 FieldBase f = TypeManager.GetField (FieldInfo);
3533                                 if ((f.ModFlags & Modifiers.VOLATILE) != 0)
3534                                         ig.Emit (OpCodes.Volatile);
3535                         }
3536
3537                         if (FieldInfo is FieldBuilder){
3538                                 FieldBase f = TypeManager.GetField (FieldInfo);
3539
3540                                 if ((mode & AddressOp.Store) != 0)
3541                                         f.status |= Field.Status.ASSIGNED;
3542                                 if ((mode & AddressOp.Load) != 0)
3543                                         f.status |= Field.Status.USED;
3544                         }
3545
3546                         //
3547                         // Handle initonly fields specially: make a copy and then
3548                         // get the address of the copy.
3549                         //
3550                         if (FieldInfo.IsInitOnly){
3551                                 LocalBuilder local;
3552                                 
3553                                 Emit (ec);
3554                                 local = ig.DeclareLocal (type);
3555                                 ig.Emit (OpCodes.Stloc, local);
3556                                 ig.Emit (OpCodes.Ldloca, local);
3557                                 return;
3558                         } 
3559
3560                         if (FieldInfo.IsStatic)
3561                                 ig.Emit (OpCodes.Ldsflda, FieldInfo);
3562                         else {
3563                                 InstanceExpression.Emit (ec);
3564                                 ig.Emit (OpCodes.Ldflda, FieldInfo);
3565                         }
3566                 }
3567         }
3568         
3569         /// <summary>
3570         ///   Expression that evaluates to a Property.  The Assign class
3571         ///   might set the `Value' expression if we are in an assignment.
3572         ///
3573         ///   This is not an LValue because we need to re-write the expression, we
3574         ///   can not take data from the stack and store it.  
3575         /// </summary>
3576         public class PropertyExpr : ExpressionStatement, IAssignMethod {
3577                 public readonly PropertyInfo PropertyInfo;
3578                 public readonly bool IsStatic;
3579                 public bool IsBase;
3580                 MethodInfo [] Accessors;
3581                 Location loc;
3582                 
3583                 Expression instance_expr;
3584                 
3585                 public PropertyExpr (PropertyInfo pi, Location l)
3586                 {
3587                         PropertyInfo = pi;
3588                         eclass = ExprClass.PropertyAccess;
3589                         IsStatic = false;
3590                         loc = l;
3591                         Accessors = TypeManager.GetAccessors (pi);
3592
3593                         if (Accessors != null)
3594                                 for (int i = 0; i < Accessors.Length; i++){
3595                                         if (Accessors [i] != null)
3596                                                 if (Accessors [i].IsStatic)
3597                                                         IsStatic = true;
3598                                 }
3599                         else
3600                                 Accessors = new MethodInfo [2];
3601                         
3602                         type = pi.PropertyType;
3603                 }
3604
3605                 //
3606                 // The instance expression associated with this expression
3607                 //
3608                 public Expression InstanceExpression {
3609                         set {
3610                                 instance_expr = value;
3611                         }
3612
3613                         get {
3614                                 return instance_expr;
3615                         }
3616                 }
3617
3618                 public bool VerifyAssignable ()
3619                 {
3620                         if (!PropertyInfo.CanWrite){
3621                                 Report.Error (200, loc, 
3622                                               "The property `" + PropertyInfo.Name +
3623                                               "' can not be assigned to, as it has not set accessor");
3624                                 return false;
3625                         }
3626
3627                         return true;
3628                 }
3629
3630                 override public Expression DoResolve (EmitContext ec)
3631                 {
3632                         if (!PropertyInfo.CanRead){
3633                                 Report.Error (154, loc, 
3634                                               "The property `" + PropertyInfo.Name +
3635                                               "' can not be used in " +
3636                                               "this context because it lacks a get accessor");
3637                                 return null;
3638                         }
3639
3640                         type = PropertyInfo.PropertyType;
3641
3642                         return this;
3643                 }
3644
3645                 override public void Emit (EmitContext ec)
3646                 {
3647                         MethodInfo method = Accessors [0];
3648
3649                         //
3650                         // Special case: length of single dimension array is turned into ldlen
3651                         //
3652                         if (method == TypeManager.int_array_get_length){
3653                                 Type iet = instance_expr.Type;
3654
3655                                 if (iet.GetArrayRank () == 1){
3656                                         instance_expr.Emit (ec);
3657                                         ec.ig.Emit (OpCodes.Ldlen);
3658                                         return;
3659                                 }
3660                         }
3661
3662                         Invocation.EmitCall (ec, IsBase, IsStatic, instance_expr, method, null);
3663                         
3664                 }
3665
3666                 //
3667                 // Implements the IAssignMethod interface for assignments
3668                 //
3669                 public void EmitAssign (EmitContext ec, Expression source)
3670                 {
3671                         Argument arg = new Argument (source, Argument.AType.Expression);
3672                         ArrayList args = new ArrayList ();
3673
3674                         args.Add (arg);
3675                         Invocation.EmitCall (ec, false, IsStatic, instance_expr, Accessors [1], args);
3676                 }
3677
3678                 override public void EmitStatement (EmitContext ec)
3679                 {
3680                         Emit (ec);
3681                         ec.ig.Emit (OpCodes.Pop);
3682                 }
3683         }
3684
3685         /// <summary>
3686         ///   Fully resolved expression that evaluates to an Event
3687         /// </summary>
3688         public class EventExpr : Expression {
3689                 public readonly EventInfo EventInfo;
3690                 Location loc;
3691                 public Expression InstanceExpression;
3692
3693                 public readonly bool IsStatic;
3694
3695                 MethodInfo add_accessor, remove_accessor;
3696                 
3697                 public EventExpr (EventInfo ei, Location loc)
3698                 {
3699                         EventInfo = ei;
3700                         this.loc = loc;
3701                         eclass = ExprClass.EventAccess;
3702
3703                         add_accessor = TypeManager.GetAddMethod (ei);
3704                         remove_accessor = TypeManager.GetRemoveMethod (ei);
3705                         
3706                         if (add_accessor.IsStatic || remove_accessor.IsStatic)
3707                                         IsStatic = true;
3708
3709                         if (EventInfo is MyEventBuilder)
3710                                 type = ((MyEventBuilder) EventInfo).EventType;
3711                         else
3712                                 type = EventInfo.EventHandlerType;
3713                 }
3714
3715                 override public Expression DoResolve (EmitContext ec)
3716                 {
3717                         // We are born fully resolved
3718                         return this;
3719                 }
3720
3721                 override public void Emit (EmitContext ec)
3722                 {
3723                         throw new Exception ("Should not happen I think");
3724                 }
3725
3726                 public void EmitAddOrRemove (EmitContext ec, Expression source)
3727                 {
3728                         Expression handler = ((Binary) source).Right;
3729                         
3730                         Argument arg = new Argument (handler, Argument.AType.Expression);
3731                         ArrayList args = new ArrayList ();
3732                                 
3733                         args.Add (arg);
3734                         
3735                         if (((Binary) source).Oper == Binary.Operator.Addition)
3736                                 Invocation.EmitCall (
3737                                         ec, false, IsStatic, InstanceExpression, add_accessor, args);
3738                         else
3739                                 Invocation.EmitCall (
3740                                         ec, false, IsStatic, InstanceExpression, remove_accessor, args);
3741                 }
3742         }
3743 }