2002-05-10 Miguel de Icaza <miguel@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                                 Constant e = Constantify (v, v.GetType ());
318
319                                 return new EnumConstant (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                                     (expr_type.IsInterface))
860                                         return true;
861                                 
862                         } else if (expr_type.IsSubclassOf (target_type)) {
863                                 return true;
864                                 
865                         } else {
866                                 // Please remember that all code below actually comes
867                                 // from ImplicitReferenceConversion so make sure code remains in sync
868                                 
869                                 // from any class-type S to any interface-type T.
870                                 if (expr_type.IsClass && target_type.IsInterface) {
871                                         if (TypeManager.ImplementsInterface (expr_type, target_type))
872                                                 return true;
873                                 }
874                                 
875                                 // from any interface type S to interface-type T.
876                                 // FIXME : Is it right to use IsAssignableFrom ?
877                                 if (expr_type.IsInterface && target_type.IsInterface)
878                                         if (target_type.IsAssignableFrom (expr_type))
879                                                 return true;
880                                 
881                                 // from an array-type S to an array-type of type T
882                                 if (expr_type.IsArray && target_type.IsArray) {
883                                         if (expr_type.GetArrayRank () == target_type.GetArrayRank ()) {
884                                                 
885                                                 Type expr_element_type = expr_type.GetElementType ();
886
887                                                 if (MyEmptyExpr == null)
888                                                         MyEmptyExpr = new EmptyExpression ();
889                                                 
890                                                 MyEmptyExpr.SetType (expr_element_type);
891                                                 Type target_element_type = target_type.GetElementType ();
892                                                 
893                                                 if (!expr_element_type.IsValueType && !target_element_type.IsValueType)
894                                                         if (StandardConversionExists (MyEmptyExpr,
895                                                                                       target_element_type))
896                                                                 return true;
897                                         }
898                                 }
899                                 
900                                 // from an array-type to System.Array
901                                 if (expr_type.IsArray && target_type.IsAssignableFrom (expr_type))
902                                         return true;
903                                 
904                                 // from any delegate type to System.Delegate
905                                 if (expr_type.IsSubclassOf (TypeManager.delegate_type) &&
906                                     target_type == TypeManager.delegate_type)
907                                         if (target_type.IsAssignableFrom (expr_type))
908                                                 return true;
909                                         
910                                 // from any array-type or delegate type into System.ICloneable.
911                                 if (expr_type.IsArray || expr_type.IsSubclassOf (TypeManager.delegate_type))
912                                         if (target_type == TypeManager.icloneable_type)
913                                                 return true;
914                                 
915                                 // from the null type to any reference-type.
916                                 if (expr is NullLiteral && !target_type.IsValueType)
917                                         return true;
918                                 
919                         }
920
921                         if (expr is IntConstant){
922                                 int value = ((IntConstant) expr).Value;
923
924                                 if (target_type == TypeManager.sbyte_type){
925                                         if (value >= SByte.MinValue && value <= SByte.MaxValue)
926                                                 return true;
927                                 } else if (target_type == TypeManager.byte_type){
928                                         if (Byte.MinValue >= 0 && value <= Byte.MaxValue)
929                                                 return true;
930                                 } else if (target_type == TypeManager.short_type){
931                                         if (value >= Int16.MinValue && value <= Int16.MaxValue)
932                                                 return true;
933                                 } else if (target_type == TypeManager.ushort_type){
934                                         if (value >= UInt16.MinValue && value <= UInt16.MaxValue)
935                                                 return true;
936                                 } else if (target_type == TypeManager.uint32_type){
937                                         if (value >= 0)
938                                                 return true;
939                                 } else if (target_type == TypeManager.uint64_type){
940                                          //
941                                          // we can optimize this case: a positive int32
942                                          // always fits on a uint64.  But we need an opcode
943                                          // to do it.
944                                          //
945                                         if (value >= 0)
946                                                 return true;
947                                 }
948                                 
949                                 if (value == 0 && expr is IntLiteral && TypeManager.IsEnumType (target_type))
950                                         return true;
951                         }
952
953                         if (expr is LongConstant && target_type == TypeManager.uint64_type){
954                                 //
955                                 // Try the implicit constant expression conversion
956                                 // from long to ulong, instead of a nice routine,
957                                 // we just inline it
958                                 //
959                                 long v = ((LongConstant) expr).Value;
960                                 if (v > 0)
961                                         return true;
962                         }
963                         
964                         if (target_type.IsSubclassOf (TypeManager.enum_type) && expr is IntLiteral){
965                                 IntLiteral i = (IntLiteral) expr;
966
967                                 if (i.Value == 0)
968                                         return true;
969                         }
970                         return false;
971                 }
972
973                 //
974                 // Used internally by FindMostEncompassedType, this is used
975                 // to avoid creating lots of objects in the tight loop inside
976                 // FindMostEncompassedType
977                 //
978                 static EmptyExpression priv_fmet_param;
979                 
980                 /// <summary>
981                 ///  Finds "most encompassed type" according to the spec (13.4.2)
982                 ///  amongst the methods in the MethodGroupExpr
983                 /// </summary>
984                 static Type FindMostEncompassedType (ArrayList types)
985                 {
986                         Type best = null;
987
988                         if (priv_fmet_param == null)
989                                 priv_fmet_param = new EmptyExpression ();
990
991                         foreach (Type t in types){
992                                 priv_fmet_param.SetType (t);
993                                 
994                                 if (best == null) {
995                                         best = t;
996                                         continue;
997                                 }
998                                 
999                                 if (StandardConversionExists (priv_fmet_param, best))
1000                                         best = t;
1001                         }
1002
1003                         return best;
1004                 }
1005
1006                 //
1007                 // Used internally by FindMostEncompassingType, this is used
1008                 // to avoid creating lots of objects in the tight loop inside
1009                 // FindMostEncompassingType
1010                 //
1011                 static EmptyExpression priv_fmee_ret;
1012                 
1013                 /// <summary>
1014                 ///  Finds "most encompassing type" according to the spec (13.4.2)
1015                 ///  amongst the types in the given set
1016                 /// </summary>
1017                 static Type FindMostEncompassingType (ArrayList types)
1018                 {
1019                         Type best = null;
1020
1021                         if (priv_fmee_ret == null)
1022                                 priv_fmee_ret = new EmptyExpression ();
1023
1024                         foreach (Type t in types){
1025                                 priv_fmee_ret.SetType (best);
1026
1027                                 if (best == null) {
1028                                         best = t;
1029                                         continue;
1030                                 }
1031
1032                                 if (StandardConversionExists (priv_fmee_ret, t))
1033                                         best = t;
1034                         }
1035                         
1036                         return best;
1037                 }
1038
1039                 //
1040                 // Used to avoid creating too many objects
1041                 //
1042                 static EmptyExpression priv_fms_expr;
1043                 
1044                 /// <summary>
1045                 ///   Finds the most specific source Sx according to the rules of the spec (13.4.4)
1046                 ///   by making use of FindMostEncomp* methods. Applies the correct rules separately
1047                 ///   for explicit and implicit conversion operators.
1048                 /// </summary>
1049                 static public Type FindMostSpecificSource (MethodGroupExpr me, Type source_type,
1050                                                            bool apply_explicit_conv_rules,
1051                                                            Location loc)
1052                 {
1053                         ArrayList src_types_set = new ArrayList ();
1054                         
1055                         if (priv_fms_expr == null)
1056                                 priv_fms_expr = new EmptyExpression ();
1057                         
1058                         //
1059                         // If any operator converts from S then Sx = S
1060                         //
1061                         foreach (MethodBase mb in me.Methods){
1062                                 ParameterData pd = Invocation.GetParameterData (mb);
1063                                 Type param_type = pd.ParameterType (0);
1064
1065                                 if (param_type == source_type)
1066                                         return param_type;
1067
1068                                 if (apply_explicit_conv_rules) {
1069                                         //
1070                                         // From the spec :
1071                                         // Find the set of applicable user-defined conversion operators, U.  This set
1072                                         // consists of the
1073                                         // user-defined implicit or explicit conversion operators declared by
1074                                         // the classes or structs in D that convert from a type encompassing
1075                                         // or encompassed by S to a type encompassing or encompassed by T
1076                                         //
1077                                         priv_fms_expr.SetType (param_type);
1078                                         if (StandardConversionExists (priv_fms_expr, source_type))
1079                                                 src_types_set.Add (param_type);
1080                                         else {
1081                                                 priv_fms_expr.SetType (source_type);
1082                                                 if (StandardConversionExists (priv_fms_expr, param_type))
1083                                                         src_types_set.Add (param_type);
1084                                         }
1085                                 } else {
1086                                         //
1087                                         // Only if S is encompassed by param_type
1088                                         //
1089                                         priv_fms_expr.SetType (source_type);
1090                                         if (StandardConversionExists (priv_fms_expr, param_type))
1091                                                 src_types_set.Add (param_type);
1092                                 }
1093                         }
1094                         
1095                         //
1096                         // Explicit Conv rules
1097                         //
1098                         if (apply_explicit_conv_rules) {
1099                                 ArrayList candidate_set = new ArrayList ();
1100
1101                                 foreach (Type param_type in src_types_set){
1102                                         priv_fms_expr.SetType (source_type);
1103                                         
1104                                         if (StandardConversionExists (priv_fms_expr, param_type))
1105                                                 candidate_set.Add (param_type);
1106                                 }
1107
1108                                 if (candidate_set.Count != 0)
1109                                         return FindMostEncompassedType (candidate_set);
1110                         }
1111
1112                         //
1113                         // Final case
1114                         //
1115                         if (apply_explicit_conv_rules)
1116                                 return FindMostEncompassingType (src_types_set);
1117                         else
1118                                 return FindMostEncompassedType (src_types_set);
1119                 }
1120
1121                 //
1122                 // Useful in avoiding proliferation of objects
1123                 //
1124                 static EmptyExpression priv_fmt_expr;
1125                 
1126                 /// <summary>
1127                 ///  Finds the most specific target Tx according to section 13.4.4
1128                 /// </summary>
1129                 static public Type FindMostSpecificTarget (MethodGroupExpr me, Type target,
1130                                                            bool apply_explicit_conv_rules,
1131                                                            Location loc)
1132                 {
1133                         ArrayList tgt_types_set = new ArrayList ();
1134                         
1135                         if (priv_fmt_expr == null)
1136                                 priv_fmt_expr = new EmptyExpression ();
1137                         
1138                         //
1139                         // If any operator converts to T then Tx = T
1140                         //
1141                         foreach (MethodInfo mi in me.Methods){
1142                                 Type ret_type = mi.ReturnType;
1143
1144                                 if (ret_type == target)
1145                                         return ret_type;
1146
1147                                 if (apply_explicit_conv_rules) {
1148                                         //
1149                                         // From the spec :
1150                                         // Find the set of applicable user-defined conversion operators, U.
1151                                         //
1152                                         // This set consists of the
1153                                         // user-defined implicit or explicit conversion operators declared by
1154                                         // the classes or structs in D that convert from a type encompassing
1155                                         // or encompassed by S to a type encompassing or encompassed by T
1156                                         //
1157                                         priv_fms_expr.SetType (ret_type);
1158                                         if (StandardConversionExists (priv_fms_expr, target))
1159                                                 tgt_types_set.Add (ret_type);
1160                                         else {
1161                                                 priv_fms_expr.SetType (target);
1162                                                 if (StandardConversionExists (priv_fms_expr, ret_type))
1163                                                         tgt_types_set.Add (ret_type);
1164                                         }
1165                                 } else {
1166                                         //
1167                                         // Only if T is encompassed by param_type
1168                                         //
1169                                         priv_fms_expr.SetType (ret_type);
1170                                         if (StandardConversionExists (priv_fms_expr, target))
1171                                                 tgt_types_set.Add (ret_type);
1172                                 }
1173                         }
1174
1175                         //
1176                         // Explicit conv rules
1177                         //
1178                         if (apply_explicit_conv_rules) {
1179                                 ArrayList candidate_set = new ArrayList ();
1180
1181                                 foreach (Type ret_type in tgt_types_set){
1182                                         priv_fmt_expr.SetType (ret_type);
1183                                         
1184                                         if (StandardConversionExists (priv_fmt_expr, target))
1185                                                 candidate_set.Add (ret_type);
1186                                 }
1187
1188                                 if (candidate_set.Count != 0)
1189                                         return FindMostEncompassingType (candidate_set);
1190                         }
1191                         
1192                         //
1193                         // Okay, final case !
1194                         //
1195                         if (apply_explicit_conv_rules)
1196                                 return FindMostEncompassedType (tgt_types_set);
1197                         else
1198                                 return FindMostEncompassingType (tgt_types_set);
1199                 }
1200                 
1201                 /// <summary>
1202                 ///  User-defined Implicit conversions
1203                 /// </summary>
1204                 static public Expression ImplicitUserConversion (EmitContext ec, Expression source,
1205                                                                  Type target, Location loc)
1206                 {
1207                         return UserDefinedConversion (ec, source, target, loc, false);
1208                 }
1209
1210                 /// <summary>
1211                 ///  User-defined Explicit conversions
1212                 /// </summary>
1213                 static public Expression ExplicitUserConversion (EmitContext ec, Expression source,
1214                                                                  Type target, Location loc)
1215                 {
1216                         return UserDefinedConversion (ec, source, target, loc, true);
1217                 }
1218
1219                 /// <summary>
1220                 ///   Computes the MethodGroup for the user-defined conversion
1221                 ///   operators from source_type to target_type.  `look_for_explicit'
1222                 ///   controls whether we should also include the list of explicit
1223                 ///   operators
1224                 /// </summary>
1225                 static MethodGroupExpr GetConversionOperators (EmitContext ec,
1226                                                                Type source_type, Type target_type,
1227                                                                Location loc, bool look_for_explicit)
1228                 {
1229                         Expression mg1 = null, mg2 = null;
1230                         Expression mg5 = null, mg6 = null, mg7 = null, mg8 = null;
1231                         string op_name;
1232
1233                         //
1234                         // FIXME : How does the False operator come into the picture ?
1235                         // This doesn't look complete and very correct !
1236                         //
1237                         if (target_type == TypeManager.bool_type && !look_for_explicit)
1238                                 op_name = "op_True";
1239                         else
1240                                 op_name = "op_Implicit";
1241                         
1242                         MethodGroupExpr union3;
1243                         
1244                         mg1 = MethodLookup (ec, source_type, op_name, loc);
1245                         if (source_type.BaseType != null)
1246                                 mg2 = MethodLookup (ec, source_type.BaseType, op_name, loc);
1247
1248                         if (mg1 == null)
1249                                 union3 = (MethodGroupExpr) mg2;
1250                         else if (mg2 == null)
1251                                 union3 = (MethodGroupExpr) mg1;
1252                         else
1253                                 union3 = Invocation.MakeUnionSet (mg1, mg2, loc);
1254
1255                         mg1 = MethodLookup (ec, target_type, op_name, loc);
1256                         if (mg1 != null){
1257                                 if (union3 != null)
1258                                         union3 = Invocation.MakeUnionSet (union3, mg1, loc);
1259                                 else
1260                                         union3 = (MethodGroupExpr) mg1;
1261                         }
1262
1263                         if (target_type.BaseType != null)
1264                                 mg1 = MethodLookup (ec, target_type.BaseType, op_name, loc);
1265                         
1266                         if (mg1 != null){
1267                                 if (union3 != null)
1268                                         union3 = Invocation.MakeUnionSet (union3, mg1, loc);
1269                                 else
1270                                         union3 = (MethodGroupExpr) mg1;
1271                         }
1272
1273                         MethodGroupExpr union4 = null;
1274
1275                         if (look_for_explicit) {
1276                                 op_name = "op_Explicit";
1277
1278                                 mg5 = MemberLookup (ec, source_type, op_name, loc);
1279                                 if (source_type.BaseType != null)
1280                                         mg6 = MethodLookup (ec, source_type.BaseType, op_name, loc);
1281                                 
1282                                 mg7 = MemberLookup (ec, target_type, op_name, loc);
1283                                 if (target_type.BaseType != null)
1284                                         mg8 = MethodLookup (ec, target_type.BaseType, op_name, loc);
1285                                 
1286                                 MethodGroupExpr union5 = Invocation.MakeUnionSet (mg5, mg6, loc);
1287                                 MethodGroupExpr union6 = Invocation.MakeUnionSet (mg7, mg8, loc);
1288
1289                                 union4 = Invocation.MakeUnionSet (union5, union6, loc);
1290                         }
1291                         
1292                         return Invocation.MakeUnionSet (union3, union4, loc);
1293                 }
1294                 
1295                 /// <summary>
1296                 ///   User-defined conversions
1297                 /// </summary>
1298                 static public Expression UserDefinedConversion (EmitContext ec, Expression source,
1299                                                                 Type target, Location loc,
1300                                                                 bool look_for_explicit)
1301                 {
1302                         MethodGroupExpr union;
1303                         Type source_type = source.Type;
1304                         MethodBase method = null;
1305                         
1306                         union = GetConversionOperators (ec, source_type, target, loc, look_for_explicit);
1307                         if (union == null)
1308                                 return null;
1309                         
1310                         Type most_specific_source, most_specific_target;
1311
1312 #if BLAH
1313                         foreach (MethodBase m in union.Methods){
1314                                 Console.WriteLine ("Name: " + m.Name);
1315                                 Console.WriteLine ("    : " + ((MethodInfo)m).ReturnType);
1316                         }
1317 #endif
1318                         
1319                         most_specific_source = FindMostSpecificSource (union, source_type, look_for_explicit, loc);
1320                         if (most_specific_source == null)
1321                                 return null;
1322
1323                         most_specific_target = FindMostSpecificTarget (union, target, look_for_explicit, loc);
1324                         if (most_specific_target == null) 
1325                                 return null;
1326                         
1327                         Console.WriteLine ("S:T" + most_specific_source + ":" + most_specific_target);
1328                         int count = 0;
1329
1330                         foreach (MethodBase mb in union.Methods){
1331                                 ParameterData pd = Invocation.GetParameterData (mb);
1332                                 MethodInfo mi = (MethodInfo) mb;
1333                                 
1334                                 if (pd.ParameterType (0) == most_specific_source &&
1335                                     mi.ReturnType == most_specific_target) {
1336                                         method = mb;
1337                                         count++;
1338                                 }
1339                         }
1340                         
1341                         if (method == null || count > 1) {
1342                                 Report.Error (-11, loc, "Ambiguous user defined conversion");
1343                                 return null;
1344                         }
1345                         
1346                         //
1347                         // This will do the conversion to the best match that we
1348                         // found.  Now we need to perform an implict standard conversion
1349                         // if the best match was not the type that we were requested
1350                         // by target.
1351                         //
1352                         if (look_for_explicit)
1353                                 source = ConvertExplicitStandard (ec, source, most_specific_source, loc);
1354                         else
1355                                 source = ConvertImplicitStandard (ec, source, most_specific_source, loc);
1356
1357                         if (source == null)
1358                                 return null;
1359
1360                         Expression e;
1361                         e =  new UserCast ((MethodInfo) method, source);
1362                         if (e.Type != target){
1363                                 if (!look_for_explicit)
1364                                         e = ConvertImplicitStandard (ec, e, target, loc);
1365                                 else
1366                                         e = ConvertExplicitStandard (ec, e, target, loc);
1367                         } 
1368                         return e;
1369                 }
1370                 
1371                 /// <summary>
1372                 ///   Converts implicitly the resolved expression `expr' into the
1373                 ///   `target_type'.  It returns a new expression that can be used
1374                 ///   in a context that expects a `target_type'. 
1375                 /// </summary>
1376                 static public Expression ConvertImplicit (EmitContext ec, Expression expr,
1377                                                           Type target_type, Location loc)
1378                 {
1379                         Type expr_type = expr.Type;
1380                         Expression e;
1381
1382                         if (expr_type == target_type)
1383                                 return expr;
1384
1385                         if (target_type == null)
1386                                 throw new Exception ("Target type is null");
1387
1388                         e = ConvertImplicitStandard (ec, expr, target_type, loc);
1389                         if (e != null)
1390                                 return e;
1391
1392                         e = ImplicitUserConversion (ec, expr, target_type, loc);
1393                         if (e != null)
1394                                 return e;
1395
1396                         return null;
1397                 }
1398
1399                 
1400                 /// <summary>
1401                 ///   Attempts to apply the `Standard Implicit
1402                 ///   Conversion' rules to the expression `expr' into
1403                 ///   the `target_type'.  It returns a new expression
1404                 ///   that can be used in a context that expects a
1405                 ///   `target_type'.
1406                 ///
1407                 ///   This is different from `ConvertImplicit' in that the
1408                 ///   user defined implicit conversions are excluded. 
1409                 /// </summary>
1410                 static public Expression ConvertImplicitStandard (EmitContext ec, Expression expr,
1411                                                                   Type target_type, Location loc)
1412                 {
1413                         Type expr_type = expr.Type;
1414                         Expression e;
1415
1416                         if (expr_type == target_type)
1417                                 return expr;
1418
1419                         e = ImplicitNumericConversion (ec, expr, target_type, loc);
1420                         if (e != null)
1421                                 return e;
1422
1423                         e = ImplicitReferenceConversion (expr, target_type);
1424                         if (e != null)
1425                                 return e;
1426
1427                         if (target_type.IsSubclassOf (TypeManager.enum_type) && expr is IntLiteral){
1428                                 IntLiteral i = (IntLiteral) expr;
1429
1430                                 if (i.Value == 0)
1431                                         return new EmptyCast (expr, target_type);
1432                         }
1433
1434                         if (ec.InUnsafe) {
1435                                 if (expr_type.IsPointer){
1436                                         if (target_type == TypeManager.void_ptr_type)
1437                                                 return new EmptyCast (expr, target_type);
1438
1439                                         //
1440                                         // yep, comparing pointer types cant be done with
1441                                         // t1 == t2, we have to compare their element types.
1442                                         //
1443                                         if (target_type.IsPointer){
1444                                                 if (target_type.GetElementType()==expr_type.GetElementType())
1445                                                         return expr;
1446                                         }
1447                                 }
1448                                 
1449                                 if (target_type.IsPointer){
1450                                         if (expr is NullLiteral)
1451                                                 return new EmptyCast (expr, target_type);
1452                                 }
1453                         }
1454
1455                         return null;
1456                 }
1457
1458                 /// <summary>
1459                 ///   Attemps to perform an implict constant conversion of the IntConstant
1460                 ///   into a different data type using casts (See Implicit Constant
1461                 ///   Expression Conversions)
1462                 /// </summary>
1463                 static protected Expression TryImplicitIntConversion (Type target_type, IntConstant ic)
1464                 {
1465                         int value = ic.Value;
1466
1467                         //
1468                         // FIXME: This could return constants instead of EmptyCasts
1469                         //
1470                         if (target_type == TypeManager.sbyte_type){
1471                                 if (value >= SByte.MinValue && value <= SByte.MaxValue)
1472                                         return new SByteConstant ((sbyte) value);
1473                         } else if (target_type == TypeManager.byte_type){
1474                                 if (Byte.MinValue >= 0 && value <= Byte.MaxValue)
1475                                         return new ByteConstant ((byte) value);
1476                         } else if (target_type == TypeManager.short_type){
1477                                 if (value >= Int16.MinValue && value <= Int16.MaxValue)
1478                                         return new ShortConstant ((short) value);
1479                         } else if (target_type == TypeManager.ushort_type){
1480                                 if (value >= UInt16.MinValue && value <= UInt16.MaxValue)
1481                                         return new UShortConstant ((ushort) value);
1482                         } else if (target_type == TypeManager.uint32_type){
1483                                 if (value >= 0)
1484                                         return new UIntConstant ((uint) value);
1485                         } else if (target_type == TypeManager.uint64_type){
1486                                 //
1487                                 // we can optimize this case: a positive int32
1488                                 // always fits on a uint64.  But we need an opcode
1489                                 // to do it.
1490                                 //
1491                                 if (value >= 0)
1492                                         return new ULongConstant ((ulong) value);
1493                         }
1494                         
1495                         if (value == 0 && ic is IntLiteral && TypeManager.IsEnumType (target_type))
1496                                 return new EnumConstant (ic, target_type);
1497
1498                         return null;
1499                 }
1500
1501                 static public void Error_CannotConvertImplicit (Location loc, Type source, Type target)
1502                 {
1503                         string msg = "Cannot convert implicitly from `"+
1504                                 TypeManager.CSharpName (source) + "' to `" +
1505                                 TypeManager.CSharpName (target) + "'";
1506
1507                         Error (29, loc, msg);
1508                 }
1509
1510                 /// <summary>
1511                 ///   Attemptes to implicityly convert `target' into `type', using
1512                 ///   ConvertImplicit.  If there is no implicit conversion, then
1513                 ///   an error is signaled
1514                 /// </summary>
1515                 static public Expression ConvertImplicitRequired (EmitContext ec, Expression source,
1516                                                                   Type target_type, Location loc)
1517                 {
1518                         Expression e;
1519                         
1520                         e = ConvertImplicit (ec, source, target_type, loc);
1521                         if (e != null)
1522                                 return e;
1523
1524                         if (source is DoubleLiteral && target_type == TypeManager.float_type){
1525                                 Error (664, loc,
1526                                        "Double literal cannot be implicitly converted to " +
1527                                        "float type, use F suffix to create a float literal");
1528                         }
1529                         
1530                         Error_CannotConvertImplicit (loc, source.Type, target_type);
1531
1532                         return null;
1533                 }
1534
1535                 /// <summary>
1536                 ///   Performs the explicit numeric conversions
1537                 /// </summary>
1538                 static Expression ConvertNumericExplicit (EmitContext ec, Expression expr,
1539                                                           Type target_type)
1540                 {
1541                         Type expr_type = expr.Type;
1542
1543                         //
1544                         // If we have an enumeration, extract the underlying type,
1545                         // use this during the comparission, but wrap around the original
1546                         // target_type
1547                         //
1548                         Type real_target_type = target_type;
1549
1550                         if (TypeManager.IsEnumType (real_target_type))
1551                                 real_target_type = TypeManager.EnumToUnderlying (real_target_type);
1552
1553                         if (expr_type == TypeManager.sbyte_type){
1554                                 //
1555                                 // From sbyte to byte, ushort, uint, ulong, char
1556                                 //
1557                                 if (real_target_type == TypeManager.byte_type)
1558                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.I1_U1);
1559                                 if (real_target_type == TypeManager.ushort_type)
1560                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.I1_U2);
1561                                 if (real_target_type == TypeManager.uint32_type)
1562                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.I1_U4);
1563                                 if (real_target_type == TypeManager.uint64_type)
1564                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.I1_U8);
1565                                 if (real_target_type == TypeManager.char_type)
1566                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.I1_CH);
1567                         } else if (expr_type == TypeManager.byte_type){
1568                                 //
1569                                 // From byte to sbyte and char
1570                                 //
1571                                 if (real_target_type == TypeManager.sbyte_type)
1572                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.U1_I1);
1573                                 if (real_target_type == TypeManager.char_type)
1574                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.U1_CH);
1575                         } else if (expr_type == TypeManager.short_type){
1576                                 //
1577                                 // From short to sbyte, byte, ushort, uint, ulong, char
1578                                 //
1579                                 if (real_target_type == TypeManager.sbyte_type)
1580                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.I2_I1);
1581                                 if (real_target_type == TypeManager.byte_type)
1582                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.I2_U1);
1583                                 if (real_target_type == TypeManager.ushort_type)
1584                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.I2_U2);
1585                                 if (real_target_type == TypeManager.uint32_type)
1586                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.I2_U4);
1587                                 if (real_target_type == TypeManager.uint64_type)
1588                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.I2_U8);
1589                                 if (real_target_type == TypeManager.char_type)
1590                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.I2_CH);
1591                         } else if (expr_type == TypeManager.ushort_type){
1592                                 //
1593                                 // From ushort to sbyte, byte, short, char
1594                                 //
1595                                 if (real_target_type == TypeManager.sbyte_type)
1596                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.U2_I1);
1597                                 if (real_target_type == TypeManager.byte_type)
1598                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.U2_U1);
1599                                 if (real_target_type == TypeManager.short_type)
1600                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.U2_I2);
1601                                 if (real_target_type == TypeManager.char_type)
1602                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.U2_CH);
1603                         } else if (expr_type == TypeManager.int32_type){
1604                                 //
1605                                 // From int to sbyte, byte, short, ushort, uint, ulong, char
1606                                 //
1607                                 if (real_target_type == TypeManager.sbyte_type)
1608                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.I4_I1);
1609                                 if (real_target_type == TypeManager.byte_type)
1610                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.I4_U1);
1611                                 if (real_target_type == TypeManager.short_type)
1612                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.I4_I2);
1613                                 if (real_target_type == TypeManager.ushort_type)
1614                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.I4_U2);
1615                                 if (real_target_type == TypeManager.uint32_type)
1616                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.I4_U4);
1617                                 if (real_target_type == TypeManager.uint64_type)
1618                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.I4_U8);
1619                                 if (real_target_type == TypeManager.char_type)
1620                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.I4_CH);
1621                         } else if (expr_type == TypeManager.uint32_type){
1622                                 //
1623                                 // From uint to sbyte, byte, short, ushort, int, char
1624                                 //
1625                                 if (real_target_type == TypeManager.sbyte_type)
1626                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.U4_I1);
1627                                 if (real_target_type == TypeManager.byte_type)
1628                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.U4_U1);
1629                                 if (real_target_type == TypeManager.short_type)
1630                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.U4_I2);
1631                                 if (real_target_type == TypeManager.ushort_type)
1632                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.U4_U2);
1633                                 if (real_target_type == TypeManager.int32_type)
1634                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.U4_I4);
1635                                 if (real_target_type == TypeManager.char_type)
1636                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.U4_CH);
1637                         } else if (expr_type == TypeManager.int64_type){
1638                                 //
1639                                 // From long to sbyte, byte, short, ushort, int, uint, ulong, char
1640                                 //
1641                                 if (real_target_type == TypeManager.sbyte_type)
1642                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.I8_I1);
1643                                 if (real_target_type == TypeManager.byte_type)
1644                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.I8_U1);
1645                                 if (real_target_type == TypeManager.short_type)
1646                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.I8_I2);
1647                                 if (real_target_type == TypeManager.ushort_type)
1648                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.I8_U2);
1649                                 if (real_target_type == TypeManager.int32_type)
1650                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.I8_I4);
1651                                 if (real_target_type == TypeManager.uint32_type)
1652                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.I8_U4);
1653                                 if (real_target_type == TypeManager.uint64_type)
1654                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.I8_U8);
1655                                 if (real_target_type == TypeManager.char_type)
1656                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.I8_CH);
1657                         } else if (expr_type == TypeManager.uint64_type){
1658                                 //
1659                                 // From ulong to sbyte, byte, short, ushort, int, uint, long, char
1660                                 //
1661                                 if (real_target_type == TypeManager.sbyte_type)
1662                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.U8_I1);
1663                                 if (real_target_type == TypeManager.byte_type)
1664                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.U8_U1);
1665                                 if (real_target_type == TypeManager.short_type)
1666                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.U8_I2);
1667                                 if (real_target_type == TypeManager.ushort_type)
1668                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.U8_U2);
1669                                 if (real_target_type == TypeManager.int32_type)
1670                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.U8_I4);
1671                                 if (real_target_type == TypeManager.uint32_type)
1672                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.U8_U4);
1673                                 if (real_target_type == TypeManager.int64_type)
1674                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.U8_I8);
1675                                 if (real_target_type == TypeManager.char_type)
1676                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.U8_CH);
1677                         } else if (expr_type == TypeManager.char_type){
1678                                 //
1679                                 // From char to sbyte, byte, short
1680                                 //
1681                                 if (real_target_type == TypeManager.sbyte_type)
1682                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.CH_I1);
1683                                 if (real_target_type == TypeManager.byte_type)
1684                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.CH_U1);
1685                                 if (real_target_type == TypeManager.short_type)
1686                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.CH_I2);
1687                         } else if (expr_type == TypeManager.float_type){
1688                                 //
1689                                 // From float to sbyte, byte, short,
1690                                 // ushort, int, uint, long, ulong, char
1691                                 // or decimal
1692                                 //
1693                                 if (real_target_type == TypeManager.sbyte_type)
1694                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.R4_I1);
1695                                 if (real_target_type == TypeManager.byte_type)
1696                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.R4_U1);
1697                                 if (real_target_type == TypeManager.short_type)
1698                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.R4_I2);
1699                                 if (real_target_type == TypeManager.ushort_type)
1700                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.R4_U2);
1701                                 if (real_target_type == TypeManager.int32_type)
1702                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.R4_I4);
1703                                 if (real_target_type == TypeManager.uint32_type)
1704                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.R4_U4);
1705                                 if (real_target_type == TypeManager.int64_type)
1706                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.R4_I8);
1707                                 if (real_target_type == TypeManager.uint64_type)
1708                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.R4_U8);
1709                                 if (real_target_type == TypeManager.char_type)
1710                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.R4_CH);
1711                                 if (real_target_type == TypeManager.decimal_type)
1712                                         return InternalTypeConstructor (ec, expr, target_type);
1713                         } else if (expr_type == TypeManager.double_type){
1714                                 //
1715                                 // From double to byte, byte, short,
1716                                 // ushort, int, uint, long, ulong,
1717                                 // char, float or decimal
1718                                 //
1719                                 if (real_target_type == TypeManager.sbyte_type)
1720                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.R8_I1);
1721                                 if (real_target_type == TypeManager.byte_type)
1722                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.R8_U1);
1723                                 if (real_target_type == TypeManager.short_type)
1724                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.R8_I2);
1725                                 if (real_target_type == TypeManager.ushort_type)
1726                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.R8_U2);
1727                                 if (real_target_type == TypeManager.int32_type)
1728                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.R8_I4);
1729                                 if (real_target_type == TypeManager.uint32_type)
1730                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.R8_U4);
1731                                 if (real_target_type == TypeManager.int64_type)
1732                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.R8_I8);
1733                                 if (real_target_type == TypeManager.uint64_type)
1734                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.R8_U8);
1735                                 if (real_target_type == TypeManager.char_type)
1736                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.R8_CH);
1737                                 if (real_target_type == TypeManager.float_type)
1738                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.R8_R4);
1739                                 if (real_target_type == TypeManager.decimal_type)
1740                                         return InternalTypeConstructor (ec, expr, target_type);
1741                         } 
1742
1743                         // decimal is taken care of by the op_Explicit methods.
1744
1745                         return null;
1746                 }
1747
1748                 /// <summary>
1749                 ///  Returns whether an explicit reference conversion can be performed
1750                 ///  from source_type to target_type
1751                 /// </summary>
1752                 static bool ExplicitReferenceConversionExists (Type source_type, Type target_type)
1753                 {
1754                         bool target_is_value_type = target_type.IsValueType;
1755                         
1756                         if (source_type == target_type)
1757                                 return true;
1758                         
1759                         //
1760                         // From object to any reference type
1761                         //
1762                         if (source_type == TypeManager.object_type && !target_is_value_type)
1763                                 return true;
1764                                         
1765                         //
1766                         // From any class S to any class-type T, provided S is a base class of T
1767                         //
1768                         if (target_type.IsSubclassOf (source_type))
1769                                 return true;
1770
1771                         //
1772                         // From any interface type S to any interface T provided S is not derived from T
1773                         //
1774                         if (source_type.IsInterface && target_type.IsInterface){
1775                                 if (!target_type.IsSubclassOf (source_type))
1776                                         return true;
1777                         }
1778                             
1779                         //
1780                         // From any class type S to any interface T, provided S is not sealed
1781                         // and provided S does not implement T.
1782                         //
1783                         if (target_type.IsInterface && !source_type.IsSealed &&
1784                             !TypeManager.ImplementsInterface (source_type, target_type))
1785                                 return true;
1786
1787                         //
1788                         // From any interface-type S to to any class type T, provided T is not
1789                         // sealed, or provided T implements S.
1790                         //
1791                         if (source_type.IsInterface &&
1792                             (!target_type.IsSealed || TypeManager.ImplementsInterface (target_type, source_type)))
1793                                 return true;
1794                         
1795                         
1796                         // From an array type S with an element type Se to an array type T with an 
1797                         // element type Te provided all the following are true:
1798                         //     * S and T differe only in element type, in other words, S and T
1799                         //       have the same number of dimensions.
1800                         //     * Both Se and Te are reference types
1801                         //     * An explicit referenc conversions exist from Se to Te
1802                         //
1803                         if (source_type.IsArray && target_type.IsArray) {
1804                                 if (source_type.GetArrayRank () == target_type.GetArrayRank ()) {
1805                                         
1806                                         Type source_element_type = source_type.GetElementType ();
1807                                         Type target_element_type = target_type.GetElementType ();
1808                                         
1809                                         if (!source_element_type.IsValueType && !target_element_type.IsValueType)
1810                                                 if (ExplicitReferenceConversionExists (source_element_type,
1811                                                                                        target_element_type))
1812                                                         return true;
1813                                 }
1814                         }
1815                         
1816
1817                         // From System.Array to any array-type
1818                         if (source_type == TypeManager.array_type &&
1819                             target_type.IsSubclassOf (TypeManager.array_type)){
1820                                 return true;
1821                         }
1822
1823                         //
1824                         // From System delegate to any delegate-type
1825                         //
1826                         if (source_type == TypeManager.delegate_type &&
1827                             target_type.IsSubclassOf (TypeManager.delegate_type))
1828                                 return true;
1829
1830                         //
1831                         // From ICloneable to Array or Delegate types
1832                         //
1833                         if (source_type == TypeManager.icloneable_type &&
1834                             (target_type == TypeManager.array_type ||
1835                              target_type == TypeManager.delegate_type))
1836                                 return true;
1837                         
1838                         return false;
1839                 }
1840
1841                 /// <summary>
1842                 ///   Implements Explicit Reference conversions
1843                 /// </summary>
1844                 static Expression ConvertReferenceExplicit (Expression source, Type target_type)
1845                 {
1846                         Type source_type = source.Type;
1847                         bool target_is_value_type = target_type.IsValueType;
1848
1849                         //
1850                         // From object to any reference type
1851                         //
1852                         if (source_type == TypeManager.object_type && !target_is_value_type)
1853                                 return new ClassCast (source, target_type);
1854
1855
1856                         //
1857                         // From any class S to any class-type T, provided S is a base class of T
1858                         //
1859                         if (target_type.IsSubclassOf (source_type))
1860                                 return new ClassCast (source, target_type);
1861
1862                         //
1863                         // From any interface type S to any interface T provided S is not derived from T
1864                         //
1865                         if (source_type.IsInterface && target_type.IsInterface){
1866                                 if (TypeManager.ImplementsInterface (source_type, target_type))
1867                                         return null;
1868                                 else
1869                                         return new ClassCast (source, target_type);
1870                         }
1871                             
1872                         //
1873                         // From any class type S to any interface T, provides S is not sealed
1874                         // and provided S does not implement T.
1875                         //
1876                         if (target_type.IsInterface && !source_type.IsSealed) {
1877                                 if (TypeManager.ImplementsInterface (source_type, target_type))
1878                                         return null;
1879                                 else
1880                                         return new ClassCast (source, target_type);
1881                                 
1882                         }
1883
1884                         //
1885                         // From any interface-type S to to any class type T, provided T is not
1886                         // sealed, or provided T implements S.
1887                         //
1888                         if (source_type.IsInterface) {
1889                                 if (!target_type.IsSealed || TypeManager.ImplementsInterface (target_type, source_type))
1890                                         return new ClassCast (source, target_type);
1891                                 else
1892                                         return null;
1893                         }
1894                         
1895                         // From an array type S with an element type Se to an array type T with an 
1896                         // element type Te provided all the following are true:
1897                         //     * S and T differe only in element type, in other words, S and T
1898                         //       have the same number of dimensions.
1899                         //     * Both Se and Te are reference types
1900                         //     * An explicit referenc conversions exist from Se to Te
1901                         //
1902                         if (source_type.IsArray && target_type.IsArray) {
1903                                 if (source_type.GetArrayRank () == target_type.GetArrayRank ()) {
1904                                         
1905                                         Type source_element_type = source_type.GetElementType ();
1906                                         Type target_element_type = target_type.GetElementType ();
1907                                         
1908                                         if (!source_element_type.IsValueType && !target_element_type.IsValueType)
1909                                                 if (ExplicitReferenceConversionExists (source_element_type,
1910                                                                                        target_element_type))
1911                                                         return new ClassCast (source, target_type);
1912                                 }
1913                         }
1914                         
1915
1916                         // From System.Array to any array-type
1917                         if (source_type == TypeManager.array_type &&
1918                             target_type.IsSubclassOf (TypeManager.array_type)){
1919                                 return new ClassCast (source, target_type);
1920                         }
1921
1922                         //
1923                         // From System delegate to any delegate-type
1924                         //
1925                         if (source_type == TypeManager.delegate_type &&
1926                             target_type.IsSubclassOf (TypeManager.delegate_type))
1927                                 return new ClassCast (source, target_type);
1928
1929                         //
1930                         // From ICloneable to Array or Delegate types
1931                         //
1932                         if (source_type == TypeManager.icloneable_type &&
1933                             (target_type == TypeManager.array_type ||
1934                              target_type == TypeManager.delegate_type))
1935                                 return new ClassCast (source, target_type);
1936                         
1937                         return null;
1938                 }
1939                 
1940                 /// <summary>
1941                 ///   Performs an explicit conversion of the expression `expr' whose
1942                 ///   type is expr.Type to `target_type'.
1943                 /// </summary>
1944                 static public Expression ConvertExplicit (EmitContext ec, Expression expr,
1945                                                           Type target_type, Location loc)
1946                 {
1947                         Type expr_type = expr.Type;
1948                         Expression ne = ConvertImplicitStandard (ec, expr, target_type, loc);
1949
1950                         if (ne != null)
1951                                 return ne;
1952
1953                         ne = ConvertNumericExplicit (ec, expr, target_type);
1954                         if (ne != null)
1955                                 return ne;
1956
1957                         //
1958                         // Unboxing conversion.
1959                         //
1960                         if (expr_type == TypeManager.object_type && target_type.IsValueType)
1961                                 return new UnboxCast (expr, target_type);
1962
1963                         //
1964                         // Enum types
1965                         //
1966                         if (expr_type.IsSubclassOf (TypeManager.enum_type)) {
1967                                 Expression e;
1968
1969                                 //
1970                                 // FIXME: Is there any reason we should have EnumConstant
1971                                 // dealt with here instead of just using always the
1972                                 // UnderlyingSystemType to wrap the type?
1973                                 //
1974                                 if (expr is EnumConstant)
1975                                         e = ((EnumConstant) expr).Child;
1976                                 else {
1977                                         e = new EmptyCast (expr, TypeManager.EnumToUnderlying (expr_type));
1978                                 }
1979                                 
1980                                 Expression t = ConvertImplicit (ec, e, target_type, loc);
1981                                 if (t != null)
1982                                         return t;
1983                                 
1984                                 return ConvertNumericExplicit (ec, e, target_type);
1985                         }
1986                         
1987                         ne = ConvertReferenceExplicit (expr, target_type);
1988                         if (ne != null)
1989                                 return ne;
1990
1991                         if (ec.InUnsafe){
1992                                 if (target_type.IsPointer){
1993                                         if (expr_type.IsPointer)
1994                                                 return new EmptyCast (expr, target_type);
1995                                         
1996                                         if (expr_type == TypeManager.sbyte_type ||
1997                                             expr_type == TypeManager.byte_type ||
1998                                             expr_type == TypeManager.short_type ||
1999                                             expr_type == TypeManager.ushort_type ||
2000                                             expr_type == TypeManager.int32_type ||
2001                                             expr_type == TypeManager.uint32_type ||
2002                                             expr_type == TypeManager.uint64_type ||
2003                                             expr_type == TypeManager.int64_type)
2004                                                 return new OpcodeCast (expr, target_type, OpCodes.Conv_U);
2005                                 }
2006                                 if (expr_type.IsPointer){
2007                                         if (target_type == TypeManager.sbyte_type ||
2008                                             target_type == TypeManager.byte_type ||
2009                                             target_type == TypeManager.short_type ||
2010                                             target_type == TypeManager.ushort_type ||
2011                                             target_type == TypeManager.int32_type ||
2012                                             target_type == TypeManager.uint32_type ||
2013                                             target_type == TypeManager.uint64_type ||
2014                                             target_type == TypeManager.int64_type){
2015                                                 Expression e = new EmptyCast (expr, TypeManager.uint32_type);
2016                                                 Expression ci, ce;
2017
2018                                                 ci = ConvertImplicitStandard (ec, e, target_type, loc);
2019
2020                                                 if (ci != null)
2021                                                         return ci;
2022
2023                                                 ce = ConvertNumericExplicit (ec, e, target_type);
2024                                                 if (ce != null)
2025                                                         return ce;
2026                                                 //
2027                                                 // We should always be able to go from an uint32
2028                                                 // implicitly or explicitly to the other integral
2029                                                 // types
2030                                                 //
2031                                                 throw new Exception ("Internal compiler error");
2032                                         }
2033                                 }
2034                         }
2035                         
2036                         ne = ExplicitUserConversion (ec, expr, target_type, loc);
2037                         if (ne != null)
2038                                 return ne;
2039
2040                         Error_CannotConvertType (loc, expr_type, target_type);
2041                         return null;
2042                 }
2043
2044                 /// <summary>
2045                 ///   Same as ConvertExplicit, only it doesn't include user defined conversions
2046                 /// </summary>
2047                 static public Expression ConvertExplicitStandard (EmitContext ec, Expression expr,
2048                                                                   Type target_type, Location l)
2049                 {
2050                         Expression ne = ConvertImplicitStandard (ec, expr, target_type, l);
2051
2052                         if (ne != null)
2053                                 return ne;
2054
2055                         ne = ConvertNumericExplicit (ec, expr, target_type);
2056                         if (ne != null)
2057                                 return ne;
2058
2059                         ne = ConvertReferenceExplicit (expr, target_type);
2060                         if (ne != null)
2061                                 return ne;
2062
2063                         Error_CannotConvertType (l, expr.Type, target_type);
2064                         return null;
2065                 }
2066
2067                 static string ExprClassName (ExprClass c)
2068                 {
2069                         switch (c){
2070                         case ExprClass.Invalid:
2071                                 return "Invalid";
2072                         case ExprClass.Value:
2073                                 return "value";
2074                         case ExprClass.Variable:
2075                                 return "variable";
2076                         case ExprClass.Namespace:
2077                                 return "namespace";
2078                         case ExprClass.Type:
2079                                 return "type";
2080                         case ExprClass.MethodGroup:
2081                                 return "method group";
2082                         case ExprClass.PropertyAccess:
2083                                 return "property access";
2084                         case ExprClass.EventAccess:
2085                                 return "event access";
2086                         case ExprClass.IndexerAccess:
2087                                 return "indexer access";
2088                         case ExprClass.Nothing:
2089                                 return "null";
2090                         }
2091                         throw new Exception ("Should not happen");
2092                 }
2093                 
2094                 /// <summary>
2095                 ///   Reports that we were expecting `expr' to be of class `expected'
2096                 /// </summary>
2097                 protected void report118 (Location loc, Expression expr, string expected)
2098                 {
2099                         string kind = "Unknown";
2100                         
2101                         if (expr != null)
2102                                 kind = ExprClassName (expr.eclass);
2103
2104                         Error (118, loc, "Expression denotes a `" + kind +
2105                                "' where a `" + expected + "' was expected");
2106                 }
2107
2108                 static void Error_ConstantValueCannotBeConverted (Location l, string val, Type t)
2109                 {
2110                         Report.Error (31, l, "Constant value `" + val + "' cannot be converted to " +
2111                                       TypeManager.CSharpName (t));
2112                 }
2113
2114                 public static void UnsafeError (Location loc)
2115                 {
2116                         Report.Error (214, loc, "Pointers may only be used in an unsafe context");
2117                 }
2118                 
2119                 /// <summary>
2120                 ///   Converts the IntConstant, UIntConstant, LongConstant or
2121                 ///   ULongConstant into the integral target_type.   Notice
2122                 ///   that we do not return an `Expression' we do return
2123                 ///   a boxed integral type.
2124                 ///
2125                 ///   FIXME: Since I added the new constants, we need to
2126                 ///   also support conversions from CharConstant, ByteConstant,
2127                 ///   SByteConstant, UShortConstant, ShortConstant
2128                 ///
2129                 ///   This is used by the switch statement, so the domain
2130                 ///   of work is restricted to the literals above, and the
2131                 ///   targets are int32, uint32, char, byte, sbyte, ushort,
2132                 ///   short, uint64 and int64
2133                 /// </summary>
2134                 public static object ConvertIntLiteral (Constant c, Type target_type, Location loc)
2135                 {
2136                         string s = "";
2137
2138                         if (c.Type == target_type)
2139                                 return ((Constant) c).GetValue ();
2140
2141                         //
2142                         // Make into one of the literals we handle, we dont really care
2143                         // about this value as we will just return a few limited types
2144                         // 
2145                         if (c is EnumConstant)
2146                                 c = ((EnumConstant)c).WidenToCompilerConstant ();
2147
2148                         if (c is IntConstant){
2149                                 int v = ((IntConstant) c).Value;
2150                                 
2151                                 if (target_type == TypeManager.uint32_type){
2152                                         if (v >= 0)
2153                                                 return (uint) v;
2154                                 } else if (target_type == TypeManager.char_type){
2155                                         if (v >= Char.MinValue && v <= Char.MaxValue)
2156                                                 return (char) v;
2157                                 } else if (target_type == TypeManager.byte_type){
2158                                         if (v >= Byte.MinValue && v <= Byte.MaxValue)
2159                                                 return (byte) v;
2160                                 } else if (target_type == TypeManager.sbyte_type){
2161                                         if (v >= SByte.MinValue && v <= SByte.MaxValue)
2162                                                 return (sbyte) v;
2163                                 } else if (target_type == TypeManager.short_type){
2164                                         if (v >= Int16.MinValue && v <= UInt16.MaxValue)
2165                                                 return (short) v;
2166                                 } else if (target_type == TypeManager.ushort_type){
2167                                         if (v >= UInt16.MinValue && v <= UInt16.MaxValue)
2168                                                 return (ushort) v;
2169                                 } else if (target_type == TypeManager.int64_type)
2170                                         return (long) v;
2171                                 else if (target_type == TypeManager.uint64_type){
2172                                         if (v > 0)
2173                                                 return (ulong) v;
2174                                 }
2175
2176                                 s = v.ToString ();
2177                         } else if (c is UIntConstant){
2178                                 uint v = ((UIntConstant) c).Value;
2179
2180                                 if (target_type == TypeManager.int32_type){
2181                                         if (v <= Int32.MaxValue)
2182                                                 return (int) v;
2183                                 } else if (target_type == TypeManager.char_type){
2184                                         if (v >= Char.MinValue && v <= Char.MaxValue)
2185                                                 return (char) v;
2186                                 } else if (target_type == TypeManager.byte_type){
2187                                         if (v <= Byte.MaxValue)
2188                                                 return (byte) v;
2189                                 } else if (target_type == TypeManager.sbyte_type){
2190                                         if (v <= SByte.MaxValue)
2191                                                 return (sbyte) v;
2192                                 } else if (target_type == TypeManager.short_type){
2193                                         if (v <= UInt16.MaxValue)
2194                                                 return (short) v;
2195                                 } else if (target_type == TypeManager.ushort_type){
2196                                         if (v <= UInt16.MaxValue)
2197                                                 return (ushort) v;
2198                                 } else if (target_type == TypeManager.int64_type)
2199                                         return (long) v;
2200                                 else if (target_type == TypeManager.uint64_type)
2201                                         return (ulong) v;
2202                                 s = v.ToString ();
2203                         } else if (c is LongConstant){ 
2204                                 long v = ((LongConstant) c).Value;
2205
2206                                 if (target_type == TypeManager.int32_type){
2207                                         if (v >= UInt32.MinValue && v <= UInt32.MaxValue)
2208                                                 return (int) v;
2209                                 } else if (target_type == TypeManager.uint32_type){
2210                                         if (v >= 0 && v <= UInt32.MaxValue)
2211                                                 return (uint) v;
2212                                 } else if (target_type == TypeManager.char_type){
2213                                         if (v >= Char.MinValue && v <= Char.MaxValue)
2214                                                 return (char) v;
2215                                 } else if (target_type == TypeManager.byte_type){
2216                                         if (v >= Byte.MinValue && v <= Byte.MaxValue)
2217                                                 return (byte) v;
2218                                 } else if (target_type == TypeManager.sbyte_type){
2219                                         if (v >= SByte.MinValue && v <= SByte.MaxValue)
2220                                                 return (sbyte) v;
2221                                 } else if (target_type == TypeManager.short_type){
2222                                         if (v >= Int16.MinValue && v <= UInt16.MaxValue)
2223                                                 return (short) v;
2224                                 } else if (target_type == TypeManager.ushort_type){
2225                                         if (v >= UInt16.MinValue && v <= UInt16.MaxValue)
2226                                                 return (ushort) v;
2227                                 } else if (target_type == TypeManager.uint64_type){
2228                                         if (v > 0)
2229                                                 return (ulong) v;
2230                                 }
2231                                 s = v.ToString ();
2232                         } else if (c is ULongConstant){
2233                                 ulong v = ((ULongConstant) c).Value;
2234
2235                                 if (target_type == TypeManager.int32_type){
2236                                         if (v <= Int32.MaxValue)
2237                                                 return (int) v;
2238                                 } else if (target_type == TypeManager.uint32_type){
2239                                         if (v <= UInt32.MaxValue)
2240                                                 return (uint) v;
2241                                 } else if (target_type == TypeManager.char_type){
2242                                         if (v >= Char.MinValue && v <= Char.MaxValue)
2243                                                 return (char) v;
2244                                 } else if (target_type == TypeManager.byte_type){
2245                                         if (v >= Byte.MinValue && v <= Byte.MaxValue)
2246                                                 return (byte) v;
2247                                 } else if (target_type == TypeManager.sbyte_type){
2248                                         if (v <= (int) SByte.MaxValue)
2249                                                 return (sbyte) v;
2250                                 } else if (target_type == TypeManager.short_type){
2251                                         if (v <= UInt16.MaxValue)
2252                                                 return (short) v;
2253                                 } else if (target_type == TypeManager.ushort_type){
2254                                         if (v <= UInt16.MaxValue)
2255                                                 return (ushort) v;
2256                                 } else if (target_type == TypeManager.int64_type){
2257                                         if (v <= Int64.MaxValue)
2258                                                 return (long) v;
2259                                 }
2260                                 s = v.ToString ();
2261                         } else if (c is ByteConstant){
2262                                 byte v = ((ByteConstant) c).Value;
2263                                 
2264                                 if (target_type == TypeManager.int32_type)
2265                                         return (int) v;
2266                                 else if (target_type == TypeManager.uint32_type)
2267                                         return (uint) v;
2268                                 else if (target_type == TypeManager.char_type)
2269                                         return (char) v;
2270                                 else if (target_type == TypeManager.sbyte_type){
2271                                         if (v <= SByte.MaxValue)
2272                                                 return (sbyte) v;
2273                                 } else if (target_type == TypeManager.short_type)
2274                                         return (short) v;
2275                                 else if (target_type == TypeManager.ushort_type)
2276                                         return (ushort) v;
2277                                 else if (target_type == TypeManager.int64_type)
2278                                         return (long) v;
2279                                 else if (target_type == TypeManager.uint64_type)
2280                                         return (ulong) v;
2281                                 s = v.ToString ();
2282                         } else if (c is SByteConstant){
2283                                 sbyte v = ((SByteConstant) c).Value;
2284                                 
2285                                 if (target_type == TypeManager.int32_type)
2286                                         return (int) v;
2287                                 else if (target_type == TypeManager.uint32_type){
2288                                         if (v >= 0)
2289                                                 return (uint) v;
2290                                 } else if (target_type == TypeManager.char_type){
2291                                         if (v >= 0)
2292                                                 return (char) v;
2293                                 } else if (target_type == TypeManager.byte_type){
2294                                         if (v >= 0)
2295                                                 return (byte) v;
2296                                 } else if (target_type == TypeManager.short_type)
2297                                         return (short) v;
2298                                 else if (target_type == TypeManager.ushort_type){
2299                                         if (v >= 0)
2300                                                 return (ushort) v;
2301                                 } else if (target_type == TypeManager.int64_type)
2302                                         return (long) v;
2303                                 else if (target_type == TypeManager.uint64_type){
2304                                         if (v >= 0)
2305                                                 return (ulong) v;
2306                                 }
2307                                 s = v.ToString ();
2308                         } else if (c is ShortConstant){
2309                                 short v = ((ShortConstant) c).Value;
2310                                 
2311                                 if (target_type == TypeManager.int32_type){
2312                                         return (int) v;
2313                                 } else if (target_type == TypeManager.uint32_type){
2314                                         if (v >= 0)
2315                                                 return (uint) v;
2316                                 } else if (target_type == TypeManager.char_type){
2317                                         if (v >= 0)
2318                                                 return (char) v;
2319                                 } else if (target_type == TypeManager.byte_type){
2320                                         if (v >= Byte.MinValue && v <= Byte.MaxValue)
2321                                                 return (byte) v;
2322                                 } else if (target_type == TypeManager.sbyte_type){
2323                                         if (v >= SByte.MinValue && v <= SByte.MaxValue)
2324                                                 return (sbyte) v;
2325                                 } else if (target_type == TypeManager.ushort_type){
2326                                         if (v >= 0)
2327                                                 return (ushort) v;
2328                                 } else if (target_type == TypeManager.int64_type)
2329                                         return (long) v;
2330                                 else if (target_type == TypeManager.uint64_type)
2331                                         return (ulong) v;
2332
2333                                 s = v.ToString ();
2334                         } else if (c is UShortConstant){
2335                                 ushort v = ((UShortConstant) c).Value;
2336                                 
2337                                 if (target_type == TypeManager.int32_type)
2338                                         return (int) v;
2339                                 else if (target_type == TypeManager.uint32_type)
2340                                         return (uint) v;
2341                                 else if (target_type == TypeManager.char_type){
2342                                         if (v >= Char.MinValue && v <= Char.MaxValue)
2343                                                 return (char) v;
2344                                 } else if (target_type == TypeManager.byte_type){
2345                                         if (v >= Byte.MinValue && v <= Byte.MaxValue)
2346                                                 return (byte) v;
2347                                 } else if (target_type == TypeManager.sbyte_type){
2348                                         if (v <= SByte.MaxValue)
2349                                                 return (byte) v;
2350                                 } else if (target_type == TypeManager.short_type){
2351                                         if (v <= Int16.MaxValue)
2352                                                 return (short) v;
2353                                 } else if (target_type == TypeManager.int64_type)
2354                                         return (long) v;
2355                                 else if (target_type == TypeManager.uint64_type)
2356                                         return (ulong) v;
2357
2358                                 s = v.ToString ();
2359                         } else if (c is CharConstant){
2360                                 char v = ((CharConstant) c).Value;
2361                                 
2362                                 if (target_type == TypeManager.int32_type)
2363                                         return (int) v;
2364                                 else if (target_type == TypeManager.uint32_type)
2365                                         return (uint) v;
2366                                 else if (target_type == TypeManager.byte_type){
2367                                         if (v >= Byte.MinValue && v <= Byte.MaxValue)
2368                                                 return (byte) v;
2369                                 } else if (target_type == TypeManager.sbyte_type){
2370                                         if (v <= SByte.MaxValue)
2371                                                 return (sbyte) v;
2372                                 } else if (target_type == TypeManager.short_type){
2373                                         if (v <= Int16.MaxValue)
2374                                                 return (short) v;
2375                                 } else if (target_type == TypeManager.ushort_type)
2376                                         return (short) v;
2377                                 else if (target_type == TypeManager.int64_type)
2378                                         return (long) v;
2379                                 else if (target_type == TypeManager.uint64_type)
2380                                         return (ulong) v;
2381
2382                                 s = v.ToString ();
2383                         }
2384                         Error_ConstantValueCannotBeConverted (loc, s, target_type);
2385                         return null;
2386                 }
2387
2388                 //
2389                 // Load the object from the pointer.  The `IsReference' is used
2390                 // to control whether we should use Ldind_Ref or LdObj if the
2391                 // value is not a `core' type.
2392                 //
2393                 // Maybe we should try to extract this infromation form the type?
2394                 // TODO: Maybe this is a bug.  The reason we have this flag is because
2395                 // I had almost identical code in ParameterReference (for handling
2396                 // references) and in UnboxCast.
2397                 //
2398                 public static void LoadFromPtr (ILGenerator ig, Type t, bool IsReference)
2399                 {
2400                         if (t == TypeManager.int32_type)
2401                                 ig.Emit (OpCodes.Ldind_I4);
2402                         else if (t == TypeManager.uint32_type)
2403                                 ig.Emit (OpCodes.Ldind_U4);
2404                         else if (t == TypeManager.short_type)
2405                                 ig.Emit (OpCodes.Ldind_I2);
2406                         else if (t == TypeManager.ushort_type)
2407                                 ig.Emit (OpCodes.Ldind_U2);
2408                         else if (t == TypeManager.char_type)
2409                                 ig.Emit (OpCodes.Ldind_U2);
2410                         else if (t == TypeManager.byte_type)
2411                                 ig.Emit (OpCodes.Ldind_U1);
2412                         else if (t == TypeManager.sbyte_type)
2413                                 ig.Emit (OpCodes.Ldind_I1);
2414                         else if (t == TypeManager.uint64_type)
2415                                 ig.Emit (OpCodes.Ldind_I8);
2416                         else if (t == TypeManager.int64_type)
2417                                 ig.Emit (OpCodes.Ldind_I8);
2418                         else if (t == TypeManager.float_type)
2419                                 ig.Emit (OpCodes.Ldind_R4);
2420                         else if (t == TypeManager.double_type)
2421                                 ig.Emit (OpCodes.Ldind_R8);
2422                         else if (t == TypeManager.bool_type)
2423                                 ig.Emit (OpCodes.Ldind_I1);
2424                         else if (t == TypeManager.intptr_type)
2425                                 ig.Emit (OpCodes.Ldind_I);
2426                         else if (TypeManager.IsEnumType (t)){
2427                                 LoadFromPtr (ig, TypeManager.EnumToUnderlying (t), IsReference);
2428                         } else {
2429                                 if (IsReference)
2430                                         ig.Emit (OpCodes.Ldind_Ref);
2431                                 else 
2432                                         ig.Emit (OpCodes.Ldobj, t);
2433                         }
2434                 }
2435
2436                 //
2437                 // The stack contains the pointer and the value of type `type'
2438                 //
2439                 public static void StoreFromPtr (ILGenerator ig, Type type)
2440                 {
2441                         if (type == TypeManager.int32_type || type == TypeManager.uint32_type)
2442                                 ig.Emit (OpCodes.Stind_I4);
2443                         else if (type == TypeManager.int64_type || type == TypeManager.uint64_type)
2444                                 ig.Emit (OpCodes.Stind_I8);
2445                         else if (type == TypeManager.char_type || type == TypeManager.short_type ||
2446                                  type == TypeManager.ushort_type)
2447                                 ig.Emit (OpCodes.Stind_I2);
2448                         else if (type == TypeManager.float_type)
2449                                 ig.Emit (OpCodes.Stind_R4);
2450                         else if (type == TypeManager.double_type)
2451                                 ig.Emit (OpCodes.Stind_R8);
2452                         else if (type == TypeManager.byte_type || type == TypeManager.sbyte_type ||
2453                                  type == TypeManager.bool_type)
2454                                 ig.Emit (OpCodes.Stind_I1);
2455                         else if (type == TypeManager.intptr_type)
2456                                 ig.Emit (OpCodes.Stind_I);
2457                         else
2458                                 ig.Emit (OpCodes.Stind_Ref);
2459                 }
2460                 
2461                 //
2462                 // Returns the size of type `t' if known, otherwise, 0
2463                 //
2464                 public static int GetTypeSize (Type t)
2465                 {
2466                         if (t == TypeManager.int32_type ||
2467                             t == TypeManager.uint32_type ||
2468                             t == TypeManager.float_type)
2469                                 return 4;
2470                         else if (t == TypeManager.int64_type ||
2471                                  t == TypeManager.uint64_type ||
2472                                  t == TypeManager.double_type)
2473                                 return 8;
2474                         else if (t == TypeManager.byte_type ||
2475                                  t == TypeManager.sbyte_type ||
2476                                  t == TypeManager.bool_type)    
2477                                 return 1;
2478                         else if (t == TypeManager.short_type ||
2479                                  t == TypeManager.char_type ||
2480                                  t == TypeManager.ushort_type)
2481                                 return 2;
2482                         else
2483                                 return 0;
2484                 }
2485         }
2486
2487         /// <summary>
2488         ///   This is just a base class for expressions that can
2489         ///   appear on statements (invocations, object creation,
2490         ///   assignments, post/pre increment and decrement).  The idea
2491         ///   being that they would support an extra Emition interface that
2492         ///   does not leave a result on the stack.
2493         /// </summary>
2494         public abstract class ExpressionStatement : Expression {
2495
2496                 /// <summary>
2497                 ///   Requests the expression to be emitted in a `statement'
2498                 ///   context.  This means that no new value is left on the
2499                 ///   stack after invoking this method (constrasted with
2500                 ///   Emit that will always leave a value on the stack).
2501                 /// </summary>
2502                 public abstract void EmitStatement (EmitContext ec);
2503         }
2504
2505         /// <summary>
2506         ///   This kind of cast is used to encapsulate the child
2507         ///   whose type is child.Type into an expression that is
2508         ///   reported to return "return_type".  This is used to encapsulate
2509         ///   expressions which have compatible types, but need to be dealt
2510         ///   at higher levels with.
2511         ///
2512         ///   For example, a "byte" expression could be encapsulated in one
2513         ///   of these as an "unsigned int".  The type for the expression
2514         ///   would be "unsigned int".
2515         ///
2516         /// </summary>
2517         public class EmptyCast : Expression {
2518                 protected Expression child;
2519
2520                 public EmptyCast (Expression child, Type return_type)
2521                 {
2522                         eclass = child.eclass;
2523                         type = return_type;
2524                         this.child = child;
2525                 }
2526
2527                 public override Expression DoResolve (EmitContext ec)
2528                 {
2529                         // This should never be invoked, we are born in fully
2530                         // initialized state.
2531
2532                         return this;
2533                 }
2534
2535                 public override void Emit (EmitContext ec)
2536                 {
2537                         child.Emit (ec);
2538                 }
2539         }
2540
2541         /// <summary>
2542         ///  This class is used to wrap literals which belong inside Enums
2543         /// </summary>
2544         public class EnumConstant : Constant {
2545                 public Constant Child;
2546
2547                 public EnumConstant (Constant child, Type enum_type)
2548                 {
2549                         eclass = child.eclass;
2550                         this.Child = child;
2551                         type = enum_type;
2552                 }
2553                 
2554                 public override Expression DoResolve (EmitContext ec)
2555                 {
2556                         // This should never be invoked, we are born in fully
2557                         // initialized state.
2558
2559                         return this;
2560                 }
2561
2562                 public override void Emit (EmitContext ec)
2563                 {
2564                         Child.Emit (ec);
2565                 }
2566
2567                 public override object GetValue ()
2568                 {
2569                         return Child.GetValue ();
2570                 }
2571
2572                 //
2573                 // Converts from one of the valid underlying types for an enumeration
2574                 // (int32, uint32, int64, uint64, short, ushort, byte, sbyte) to
2575                 // one of the internal compiler literals: Int/UInt/Long/ULong Literals.
2576                 //
2577                 public Constant WidenToCompilerConstant ()
2578                 {
2579                         Type t = TypeManager.EnumToUnderlying (Child.Type);
2580                         object v = ((Constant) Child).GetValue ();;
2581                         
2582                         if (t == TypeManager.int32_type)
2583                                 return new IntConstant ((int) v);
2584                         if (t == TypeManager.uint32_type)
2585                                 return new UIntConstant ((uint) v);
2586                         if (t == TypeManager.int64_type)
2587                                 return new LongConstant ((long) v);
2588                         if (t == TypeManager.uint64_type)
2589                                 return new ULongConstant ((ulong) v);
2590                         if (t == TypeManager.short_type)
2591                                 return new ShortConstant ((short) v);
2592                         if (t == TypeManager.ushort_type)
2593                                 return new UShortConstant ((ushort) v);
2594                         if (t == TypeManager.byte_type)
2595                                 return new ByteConstant ((byte) v);
2596                         if (t == TypeManager.sbyte_type)
2597                                 return new SByteConstant ((sbyte) v);
2598
2599                         throw new Exception ("Invalid enumeration underlying type: " + t);
2600                 }
2601
2602                 //
2603                 // Extracts the value in the enumeration on its native representation
2604                 //
2605                 public object GetPlainValue ()
2606                 {
2607                         Type t = TypeManager.EnumToUnderlying (Child.Type);
2608                         object v = ((Constant) Child).GetValue ();;
2609                         
2610                         if (t == TypeManager.int32_type)
2611                                 return (int) v;
2612                         if (t == TypeManager.uint32_type)
2613                                 return (uint) v;
2614                         if (t == TypeManager.int64_type)
2615                                 return (long) v;
2616                         if (t == TypeManager.uint64_type)
2617                                 return (ulong) v;
2618                         if (t == TypeManager.short_type)
2619                                 return (short) v;
2620                         if (t == TypeManager.ushort_type)
2621                                 return (ushort) v;
2622                         if (t == TypeManager.byte_type)
2623                                 return (byte) v;
2624                         if (t == TypeManager.sbyte_type)
2625                                 return (sbyte) v;
2626
2627                         return null;
2628                 }
2629                 
2630                 public override string AsString ()
2631                 {
2632                         return Child.AsString ();
2633                 }
2634
2635                 public override DoubleConstant ConvertToDouble ()
2636                 {
2637                         return Child.ConvertToDouble ();
2638                 }
2639
2640                 public override FloatConstant ConvertToFloat ()
2641                 {
2642                         return Child.ConvertToFloat ();
2643                 }
2644
2645                 public override ULongConstant ConvertToULong ()
2646                 {
2647                         return Child.ConvertToULong ();
2648                 }
2649
2650                 public override LongConstant ConvertToLong ()
2651                 {
2652                         return Child.ConvertToLong ();
2653                 }
2654
2655                 public override UIntConstant ConvertToUInt ()
2656                 {
2657                         return Child.ConvertToUInt ();
2658                 }
2659
2660                 public override IntConstant ConvertToInt ()
2661                 {
2662                         return Child.ConvertToInt ();
2663                 }
2664         }
2665
2666         /// <summary>
2667         ///   This kind of cast is used to encapsulate Value Types in objects.
2668         ///
2669         ///   The effect of it is to box the value type emitted by the previous
2670         ///   operation.
2671         /// </summary>
2672         public class BoxedCast : EmptyCast {
2673
2674                 public BoxedCast (Expression expr)
2675                         : base (expr, TypeManager.object_type)
2676                 {
2677                 }
2678
2679                 public override Expression DoResolve (EmitContext ec)
2680                 {
2681                         // This should never be invoked, we are born in fully
2682                         // initialized state.
2683
2684                         return this;
2685                 }
2686
2687                 public override void Emit (EmitContext ec)
2688                 {
2689                         base.Emit (ec);
2690                         
2691                         ec.ig.Emit (OpCodes.Box, child.Type);
2692                 }
2693         }
2694
2695         public class UnboxCast : EmptyCast {
2696                 public UnboxCast (Expression expr, Type return_type)
2697                         : base (expr, return_type)
2698                 {
2699                 }
2700
2701                 public override Expression DoResolve (EmitContext ec)
2702                 {
2703                         // This should never be invoked, we are born in fully
2704                         // initialized state.
2705
2706                         return this;
2707                 }
2708
2709                 public override void Emit (EmitContext ec)
2710                 {
2711                         Type t = type;
2712                         ILGenerator ig = ec.ig;
2713                         
2714                         base.Emit (ec);
2715                         ig.Emit (OpCodes.Unbox, t);
2716
2717                         LoadFromPtr (ig, t, false);
2718                 }
2719         }
2720         
2721         /// <summary>
2722         ///   This is used to perform explicit numeric conversions.
2723         ///
2724         ///   Explicit numeric conversions might trigger exceptions in a checked
2725         ///   context, so they should generate the conv.ovf opcodes instead of
2726         ///   conv opcodes.
2727         /// </summary>
2728         public class ConvCast : EmptyCast {
2729                 public enum Mode : byte {
2730                         I1_U1, I1_U2, I1_U4, I1_U8, I1_CH,
2731                         U1_I1, U1_CH,
2732                         I2_I1, I2_U1, I2_U2, I2_U4, I2_U8, I2_CH,
2733                         U2_I1, U2_U1, U2_I2, U2_CH,
2734                         I4_I1, I4_U1, I4_I2, I4_U2, I4_U4, I4_U8, I4_CH,
2735                         U4_I1, U4_U1, U4_I2, U4_U2, U4_I4, U4_CH,
2736                         I8_I1, I8_U1, I8_I2, I8_U2, I8_I4, I8_U4, I8_U8, I8_CH,
2737                         U8_I1, U8_U1, U8_I2, U8_U2, U8_I4, U8_U4, U8_I8, U8_CH,
2738                         CH_I1, CH_U1, CH_I2,
2739                         R4_I1, R4_U1, R4_I2, R4_U2, R4_I4, R4_U4, R4_I8, R4_U8, R4_CH,
2740                         R8_I1, R8_U1, R8_I2, R8_U2, R8_I4, R8_U4, R8_I8, R8_U8, R8_CH, R8_R4
2741                 }
2742
2743                 Mode mode;
2744                 bool checked_state;
2745                 
2746                 public ConvCast (EmitContext ec, Expression child, Type return_type, Mode m)
2747                         : base (child, return_type)
2748                 {
2749                         mode = m;
2750                         checked_state = ec.CheckState;
2751                 }
2752
2753                 public override Expression DoResolve (EmitContext ec)
2754                 {
2755                         // This should never be invoked, we are born in fully
2756                         // initialized state.
2757
2758                         return this;
2759                 }
2760
2761                 public override void Emit (EmitContext ec)
2762                 {
2763                         ILGenerator ig = ec.ig;
2764                         
2765                         base.Emit (ec);
2766
2767                         if (checked_state){
2768                                 switch (mode){
2769                                 case Mode.I1_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
2770                                 case Mode.I1_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
2771                                 case Mode.I1_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
2772                                 case Mode.I1_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
2773                                 case Mode.I1_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
2774
2775                                 case Mode.U1_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
2776                                 case Mode.U1_CH: /* nothing */ break;
2777
2778                                 case Mode.I2_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
2779                                 case Mode.I2_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
2780                                 case Mode.I2_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
2781                                 case Mode.I2_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
2782                                 case Mode.I2_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
2783                                 case Mode.I2_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
2784
2785                                 case Mode.U2_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
2786                                 case Mode.U2_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
2787                                 case Mode.U2_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
2788                                 case Mode.U2_CH: /* nothing */ break;
2789
2790                                 case Mode.I4_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
2791                                 case Mode.I4_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
2792                                 case Mode.I4_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
2793                                 case Mode.I4_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
2794                                 case Mode.I4_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
2795                                 case Mode.I4_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
2796                                 case Mode.I4_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
2797
2798                                 case Mode.U4_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
2799                                 case Mode.U4_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
2800                                 case Mode.U4_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
2801                                 case Mode.U4_U2: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
2802                                 case Mode.U4_I4: ig.Emit (OpCodes.Conv_Ovf_I4_Un); break;
2803                                 case Mode.U4_CH: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
2804
2805                                 case Mode.I8_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
2806                                 case Mode.I8_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
2807                                 case Mode.I8_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
2808                                 case Mode.I8_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
2809                                 case Mode.I8_I4: ig.Emit (OpCodes.Conv_Ovf_I4); break;
2810                                 case Mode.I8_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
2811                                 case Mode.I8_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
2812                                 case Mode.I8_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
2813
2814                                 case Mode.U8_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
2815                                 case Mode.U8_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
2816                                 case Mode.U8_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
2817                                 case Mode.U8_U2: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
2818                                 case Mode.U8_I4: ig.Emit (OpCodes.Conv_Ovf_I4_Un); break;
2819                                 case Mode.U8_U4: ig.Emit (OpCodes.Conv_Ovf_U4_Un); break;
2820                                 case Mode.U8_I8: ig.Emit (OpCodes.Conv_Ovf_I8_Un); break;
2821                                 case Mode.U8_CH: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
2822
2823                                 case Mode.CH_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
2824                                 case Mode.CH_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
2825                                 case Mode.CH_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
2826
2827                                 case Mode.R4_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
2828                                 case Mode.R4_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
2829                                 case Mode.R4_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
2830                                 case Mode.R4_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
2831                                 case Mode.R4_I4: ig.Emit (OpCodes.Conv_Ovf_I4); break;
2832                                 case Mode.R4_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
2833                                 case Mode.R4_I8: ig.Emit (OpCodes.Conv_Ovf_I8); break;
2834                                 case Mode.R4_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
2835                                 case Mode.R4_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
2836
2837                                 case Mode.R8_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
2838                                 case Mode.R8_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
2839                                 case Mode.R8_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
2840                                 case Mode.R8_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
2841                                 case Mode.R8_I4: ig.Emit (OpCodes.Conv_Ovf_I4); break;
2842                                 case Mode.R8_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
2843                                 case Mode.R8_I8: ig.Emit (OpCodes.Conv_Ovf_I8); break;
2844                                 case Mode.R8_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
2845                                 case Mode.R8_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
2846                                 case Mode.R8_R4: ig.Emit (OpCodes.Conv_R4); break;
2847                                 }
2848                         } else {
2849                                 switch (mode){
2850                                 case Mode.I1_U1: ig.Emit (OpCodes.Conv_U1); break;
2851                                 case Mode.I1_U2: ig.Emit (OpCodes.Conv_U2); break;
2852                                 case Mode.I1_U4: ig.Emit (OpCodes.Conv_U4); break;
2853                                 case Mode.I1_U8: ig.Emit (OpCodes.Conv_I8); break;
2854                                 case Mode.I1_CH: ig.Emit (OpCodes.Conv_U2); break;
2855
2856                                 case Mode.U1_I1: ig.Emit (OpCodes.Conv_I1); break;
2857                                 case Mode.U1_CH: ig.Emit (OpCodes.Conv_U2); break;
2858
2859                                 case Mode.I2_I1: ig.Emit (OpCodes.Conv_I1); break;
2860                                 case Mode.I2_U1: ig.Emit (OpCodes.Conv_U1); break;
2861                                 case Mode.I2_U2: ig.Emit (OpCodes.Conv_U2); break;
2862                                 case Mode.I2_U4: ig.Emit (OpCodes.Conv_U4); break;
2863                                 case Mode.I2_U8: ig.Emit (OpCodes.Conv_I8); break;
2864                                 case Mode.I2_CH: ig.Emit (OpCodes.Conv_U2); break;
2865
2866                                 case Mode.U2_I1: ig.Emit (OpCodes.Conv_I1); break;
2867                                 case Mode.U2_U1: ig.Emit (OpCodes.Conv_U1); break;
2868                                 case Mode.U2_I2: ig.Emit (OpCodes.Conv_I2); break;
2869                                 case Mode.U2_CH: /* nothing */ break;
2870
2871                                 case Mode.I4_I1: ig.Emit (OpCodes.Conv_I1); break;
2872                                 case Mode.I4_U1: ig.Emit (OpCodes.Conv_U1); break;
2873                                 case Mode.I4_I2: ig.Emit (OpCodes.Conv_I2); break;
2874                                 case Mode.I4_U4: /* nothing */ break;
2875                                 case Mode.I4_U2: ig.Emit (OpCodes.Conv_U2); break;
2876                                 case Mode.I4_U8: ig.Emit (OpCodes.Conv_I8); break;
2877                                 case Mode.I4_CH: ig.Emit (OpCodes.Conv_U2); break;
2878
2879                                 case Mode.U4_I1: ig.Emit (OpCodes.Conv_I1); break;
2880                                 case Mode.U4_U1: ig.Emit (OpCodes.Conv_U1); break;
2881                                 case Mode.U4_I2: ig.Emit (OpCodes.Conv_I2); break;
2882                                 case Mode.U4_U2: ig.Emit (OpCodes.Conv_U2); break;
2883                                 case Mode.U4_I4: /* nothing */ break;
2884                                 case Mode.U4_CH: ig.Emit (OpCodes.Conv_U2); break;
2885
2886                                 case Mode.I8_I1: ig.Emit (OpCodes.Conv_I1); break;
2887                                 case Mode.I8_U1: ig.Emit (OpCodes.Conv_U1); break;
2888                                 case Mode.I8_I2: ig.Emit (OpCodes.Conv_I2); break;
2889                                 case Mode.I8_U2: ig.Emit (OpCodes.Conv_U2); break;
2890                                 case Mode.I8_I4: ig.Emit (OpCodes.Conv_I4); break;
2891                                 case Mode.I8_U4: ig.Emit (OpCodes.Conv_U4); break;
2892                                 case Mode.I8_U8: /* nothing */ break;
2893                                 case Mode.I8_CH: ig.Emit (OpCodes.Conv_U2); break;
2894
2895                                 case Mode.U8_I1: ig.Emit (OpCodes.Conv_I1); break;
2896                                 case Mode.U8_U1: ig.Emit (OpCodes.Conv_U1); break;
2897                                 case Mode.U8_I2: ig.Emit (OpCodes.Conv_I2); break;
2898                                 case Mode.U8_U2: ig.Emit (OpCodes.Conv_U2); break;
2899                                 case Mode.U8_I4: ig.Emit (OpCodes.Conv_I4); break;
2900                                 case Mode.U8_U4: ig.Emit (OpCodes.Conv_U4); break;
2901                                 case Mode.U8_I8: /* nothing */ break;
2902                                 case Mode.U8_CH: ig.Emit (OpCodes.Conv_U2); break;
2903
2904                                 case Mode.CH_I1: ig.Emit (OpCodes.Conv_I1); break;
2905                                 case Mode.CH_U1: ig.Emit (OpCodes.Conv_U1); break;
2906                                 case Mode.CH_I2: ig.Emit (OpCodes.Conv_I2); break;
2907
2908                                 case Mode.R4_I1: ig.Emit (OpCodes.Conv_I1); break;
2909                                 case Mode.R4_U1: ig.Emit (OpCodes.Conv_U1); break;
2910                                 case Mode.R4_I2: ig.Emit (OpCodes.Conv_I2); break;
2911                                 case Mode.R4_U2: ig.Emit (OpCodes.Conv_U2); break;
2912                                 case Mode.R4_I4: ig.Emit (OpCodes.Conv_I4); break;
2913                                 case Mode.R4_U4: ig.Emit (OpCodes.Conv_U4); break;
2914                                 case Mode.R4_I8: ig.Emit (OpCodes.Conv_I8); break;
2915                                 case Mode.R4_U8: ig.Emit (OpCodes.Conv_U8); break;
2916                                 case Mode.R4_CH: ig.Emit (OpCodes.Conv_U2); break;
2917
2918                                 case Mode.R8_I1: ig.Emit (OpCodes.Conv_I1); break;
2919                                 case Mode.R8_U1: ig.Emit (OpCodes.Conv_U1); break;
2920                                 case Mode.R8_I2: ig.Emit (OpCodes.Conv_I2); break;
2921                                 case Mode.R8_U2: ig.Emit (OpCodes.Conv_U2); break;
2922                                 case Mode.R8_I4: ig.Emit (OpCodes.Conv_I4); break;
2923                                 case Mode.R8_U4: ig.Emit (OpCodes.Conv_U4); break;
2924                                 case Mode.R8_I8: ig.Emit (OpCodes.Conv_I8); break;
2925                                 case Mode.R8_U8: ig.Emit (OpCodes.Conv_U8); break;
2926                                 case Mode.R8_CH: ig.Emit (OpCodes.Conv_U2); break;
2927                                 case Mode.R8_R4: ig.Emit (OpCodes.Conv_R4); break;
2928                                 }
2929                         }
2930                 }
2931         }
2932         
2933         public class OpcodeCast : EmptyCast {
2934                 OpCode op, op2;
2935                 bool second_valid;
2936                 
2937                 public OpcodeCast (Expression child, Type return_type, OpCode op)
2938                         : base (child, return_type)
2939                         
2940                 {
2941                         this.op = op;
2942                         second_valid = false;
2943                 }
2944
2945                 public OpcodeCast (Expression child, Type return_type, OpCode op, OpCode op2)
2946                         : base (child, return_type)
2947                         
2948                 {
2949                         this.op = op;
2950                         this.op2 = op2;
2951                         second_valid = true;
2952                 }
2953
2954                 public override Expression DoResolve (EmitContext ec)
2955                 {
2956                         // This should never be invoked, we are born in fully
2957                         // initialized state.
2958
2959                         return this;
2960                 }
2961
2962                 public override void Emit (EmitContext ec)
2963                 {
2964                         base.Emit (ec);
2965                         ec.ig.Emit (op);
2966
2967                         if (second_valid)
2968                                 ec.ig.Emit (op2);
2969                 }                       
2970         }
2971
2972         /// <summary>
2973         ///   This kind of cast is used to encapsulate a child and cast it
2974         ///   to the class requested
2975         /// </summary>
2976         public class ClassCast : EmptyCast {
2977                 public ClassCast (Expression child, Type return_type)
2978                         : base (child, return_type)
2979                         
2980                 {
2981                 }
2982
2983                 public override Expression DoResolve (EmitContext ec)
2984                 {
2985                         // This should never be invoked, we are born in fully
2986                         // initialized state.
2987
2988                         return this;
2989                 }
2990
2991                 public override void Emit (EmitContext ec)
2992                 {
2993                         base.Emit (ec);
2994
2995                         ec.ig.Emit (OpCodes.Castclass, type);
2996                 }                       
2997                 
2998         }
2999         
3000         /// <summary>
3001         ///   SimpleName expressions are initially formed of a single
3002         ///   word and it only happens at the beginning of the expression.
3003         /// </summary>
3004         ///
3005         /// <remarks>
3006         ///   The expression will try to be bound to a Field, a Method
3007         ///   group or a Property.  If those fail we pass the name to our
3008         ///   caller and the SimpleName is compounded to perform a type
3009         ///   lookup.  The idea behind this process is that we want to avoid
3010         ///   creating a namespace map from the assemblies, as that requires
3011         ///   the GetExportedTypes function to be called and a hashtable to
3012         ///   be constructed which reduces startup time.  If later we find
3013         ///   that this is slower, we should create a `NamespaceExpr' expression
3014         ///   that fully participates in the resolution process. 
3015         ///   
3016         ///   For example `System.Console.WriteLine' is decomposed into
3017         ///   MemberAccess (MemberAccess (SimpleName ("System"), "Console"), "WriteLine")
3018         ///   
3019         ///   The first SimpleName wont produce a match on its own, so it will
3020         ///   be turned into:
3021         ///   MemberAccess (SimpleName ("System.Console"), "WriteLine").
3022         ///   
3023         ///   System.Console will produce a TypeExpr match.
3024         ///   
3025         ///   The downside of this is that we might be hitting `LookupType' too many
3026         ///   times with this scheme.
3027         /// </remarks>
3028         public class SimpleName : Expression {
3029                 public readonly string Name;
3030                 public readonly Location Location;
3031                 
3032                 public SimpleName (string name, Location l)
3033                 {
3034                         Name = name;
3035                         Location = l;
3036                 }
3037
3038                 public static void Error120 (Location l, string name)
3039                 {
3040                         Report.Error (
3041                                 120, l,
3042                                 "An object reference is required " +
3043                                 "for the non-static field `"+name+"'");
3044                 }
3045                 
3046                 //
3047                 // Checks whether we are trying to access an instance
3048                 // property, method or field from a static body.
3049                 //
3050                 Expression MemberStaticCheck (Expression e)
3051                 {
3052                         if (e is FieldExpr){
3053                                 FieldInfo fi = ((FieldExpr) e).FieldInfo;
3054                                 
3055                                 if (!fi.IsStatic){
3056                                         Error120 (Location, Name);
3057                                         return null;
3058                                 }
3059                         } else if (e is MethodGroupExpr){
3060                                 MethodGroupExpr mg = (MethodGroupExpr) e;
3061
3062                                 if (!mg.RemoveInstanceMethods ()){
3063                                         Error120 (Location, mg.Methods [0].Name);
3064                                         return null;
3065                                 }
3066                                 return e;
3067                         } else if (e is PropertyExpr){
3068                                 if (!((PropertyExpr) e).IsStatic){
3069                                         Error120 (Location, Name);
3070                                         return null;
3071                                 }
3072                         } else if (e is EventExpr) {
3073                                 if (!((EventExpr) e).IsStatic) {
3074                                         Error120 (Location, Name);
3075                                         return null;
3076                                 }
3077                         }
3078
3079                         return e;
3080                 }
3081                 
3082                 public override Expression DoResolve (EmitContext ec)
3083                 {
3084                         return SimpleNameResolve (ec, false);
3085                 }
3086
3087                 public Expression DoResolveAllowStatic (EmitContext ec)
3088                 {
3089                         return SimpleNameResolve (ec, true);
3090                 }
3091
3092                 /// <remarks>
3093                 ///   7.5.2: Simple Names. 
3094                 ///
3095                 ///   Local Variables and Parameters are handled at
3096                 ///   parse time, so they never occur as SimpleNames.
3097                 ///
3098                 ///   The `allow_static' flag is used by MemberAccess only
3099                 ///   and it is used to inform us that it is ok for us to 
3100                 ///   avoid the static check, because MemberAccess might end
3101                 ///   up resolving the Name as a Type name and the access as
3102                 ///   a static type access.
3103                 ///
3104                 ///   ie: Type Type; .... { Type.GetType (""); }
3105                 ///
3106                 ///   Type is both an instance variable and a Type;  Type.GetType
3107                 ///   is the static method not an instance method of type.
3108                 /// </remarks>
3109                 Expression SimpleNameResolve (EmitContext ec, bool allow_static)
3110                 {
3111                         Expression e = null;
3112
3113                         //
3114                         // Stage 1: Performed by the parser (binding to locals or parameters).
3115                         //
3116                         if (!ec.OnlyLookupTypes){
3117                                 Block current_block = ec.CurrentBlock;
3118                                 if (current_block != null && current_block.IsVariableDefined (Name)){
3119                                         LocalVariableReference var;
3120                                         
3121                                         var = new LocalVariableReference (ec.CurrentBlock, Name, Location);
3122                                         
3123                                         return var.Resolve (ec);
3124                                 }
3125                         
3126                                 //
3127                                 // Stage 2: Lookup members 
3128                                 //
3129
3130                                 //
3131                                 // For enums, the TypeBuilder is not ec.DeclSpace.TypeBuilder
3132                                 // Hence we have two different cases
3133                                 //
3134
3135                                 DeclSpace lookup_ds = ec.DeclSpace;
3136                                 do {
3137                                         if (lookup_ds.TypeBuilder == null)
3138                                                 break;
3139
3140                                         e = MemberLookup (ec, lookup_ds.TypeBuilder, Name, Location);
3141                                         if (e != null)
3142                                                 break;
3143
3144                                         //
3145                                         // Classes/structs keep looking, enums break
3146                                         //
3147                                         if (lookup_ds is TypeContainer)
3148                                                 lookup_ds = ((TypeContainer) lookup_ds).Parent;
3149                                         else
3150                                                 break;
3151                                 } while (lookup_ds != null);
3152                                 
3153                                 if (e == null && ec.ContainerType != null)
3154                                         e = MemberLookup (ec, ec.ContainerType, Name, Location);
3155                         }
3156
3157                         // Continuation of stage 2
3158                         if (e == null){
3159                                 //
3160                                 // Stage 3: Lookup symbol in the various namespaces. 
3161                                 //
3162                                 DeclSpace ds = ec.DeclSpace;
3163                                 Type t;
3164                                 string alias_value;
3165
3166                                 if ((t = RootContext.LookupType (ds, Name, true, Location)) != null)
3167                                         return new TypeExpr (t);
3168                                 
3169                                 //
3170                                 // Stage 2 part b: Lookup up if we are an alias to a type
3171                                 // or a namespace.
3172                                 //
3173                                 // Since we are cheating: we only do the Alias lookup for
3174                                 // namespaces if the name does not include any dots in it
3175                                 //
3176                                 
3177                                 if (Name.IndexOf ('.') == -1 && (alias_value = ec.TypeContainer.LookupAlias (Name)) != null) {
3178                                 // System.Console.WriteLine (Name + " --> " + alias_value);
3179                                         if ((t = RootContext.LookupType (ds, alias_value, true, Location))
3180                                             != null)
3181                                                 return new TypeExpr (t);
3182                                         
3183                                 // we have alias value, but it isn't Type, so try if it's namespace
3184                                         return new SimpleName (alias_value, Location);
3185                                 }
3186                                 
3187                                 // No match, maybe our parent can compose us
3188                                 // into something meaningful.
3189                                 return this;
3190                         }
3191                         
3192                         //
3193                         // Stage 2 continues here. 
3194                         // 
3195                         if (e is TypeExpr)
3196                                 return e;
3197
3198                         if (ec.OnlyLookupTypes)
3199                                 return null;
3200                         
3201                         if (e is FieldExpr){
3202                                 FieldExpr fe = (FieldExpr) e;
3203                                 FieldInfo fi = fe.FieldInfo;
3204
3205                                 if (fi.FieldType.IsPointer && !ec.InUnsafe){
3206                                         UnsafeError (Location);
3207                                 }
3208                                 
3209                                 if (ec.IsStatic){
3210                                         if (!allow_static && !fi.IsStatic){
3211                                                 Error120 (Location, Name);
3212                                                 return null;
3213                                         }
3214                                 } else {
3215                                         // If we are not in static code and this
3216                                         // field is not static, set the instance to `this'.
3217
3218                                         if (!fi.IsStatic)
3219                                                 fe.InstanceExpression = ec.This;
3220                                 }
3221
3222                                 
3223                                 if (fi is FieldBuilder) {
3224                                         Const c = TypeManager.LookupConstant ((FieldBuilder) fi);
3225                                         
3226                                         if (c != null) {
3227                                                 object o = c.LookupConstantValue (ec);
3228                                                 object real_value = ((Constant)c.Expr).GetValue ();
3229                                                 return Constantify (real_value, fi.FieldType);
3230                                         }
3231                                 }
3232
3233                                 if (fi.IsLiteral) {
3234                                         Type t = fi.FieldType;
3235                                         Type decl_type = fi.DeclaringType;
3236                                         object o;
3237
3238                                         if (fi is FieldBuilder)
3239                                                 o = TypeManager.GetValue ((FieldBuilder) fi);
3240                                         else
3241                                                 o = fi.GetValue (fi);
3242                                         
3243                                         if (decl_type.IsSubclassOf (TypeManager.enum_type)) {
3244                                                 Expression enum_member = MemberLookup (
3245                                                         ec, decl_type, "value__", MemberTypes.Field,
3246                                                         AllBindingFlags, Location); 
3247
3248                                                 Enum en = TypeManager.LookupEnum (decl_type);
3249
3250                                                 Constant c;
3251                                                 if (en != null)
3252                                                         c = Constantify (o, en.UnderlyingType);
3253                                                 else 
3254                                                         c = Constantify (o, enum_member.Type);
3255                                                 
3256                                                 return new EnumConstant (c, decl_type);
3257                                         }
3258                                         
3259                                         Expression exp = Constantify (o, t);
3260                                 }
3261                                         
3262                                 return e;
3263                         }                               
3264
3265                         if (e is EventExpr) {
3266                                 //
3267                                 // If the event is local to this class, we transform ourselves into
3268                                 // a FieldExpr
3269                                 //
3270                                 EventExpr ee = (EventExpr) e;
3271
3272                                 Expression ml = MemberLookup (
3273                                         ec, ec.DeclSpace.TypeBuilder, ee.EventInfo.Name,
3274                                         MemberTypes.Event, AllBindingFlags, Location);
3275
3276                                 if (ml != null) {
3277                                         MemberInfo mi = ec.TypeContainer.GetFieldFromEvent ((EventExpr) ml);
3278
3279                                         if (mi == null) {
3280                                                 //
3281                                                 // If this happens, then we have an event with its own
3282                                                 // accessors and private field etc so there's no need
3283                                                 // to transform ourselves : we should instead flag an error
3284                                                 //
3285                                                 Assign.error70 (ee.EventInfo, Location);
3286                                                 return null;
3287                                         }
3288
3289                                         ml = ExprClassFromMemberInfo (ec, mi, Location);
3290                                         
3291                                         if (ml == null) {
3292                                                 Report.Error (-200, Location, "Internal error!!");
3293                                                 return null;
3294                                         }
3295
3296                                         Expression instance_expr;
3297                                         
3298                                         FieldInfo fi = ((FieldExpr) ml).FieldInfo;
3299
3300                                         if (fi.IsStatic)
3301                                                 instance_expr = null;
3302                                         else
3303                                                 instance_expr = ec.This;
3304
3305                                         instance_expr = instance_expr.Resolve (ec);
3306
3307                                         if (instance_expr != null)
3308                                                 instance_expr = instance_expr.Resolve (ec);
3309                                         
3310                                         return MemberAccess.ResolveMemberAccess (ec, ml, instance_expr, Location, null);
3311                                 }
3312                         }
3313                                 
3314                         
3315                         if (ec.IsStatic){
3316                                 if (allow_static)
3317                                         return e;
3318
3319                                 return MemberStaticCheck (e);
3320                         } else
3321                                 return e;
3322                 }
3323
3324                 public override void Emit (EmitContext ec)
3325                 {
3326                         //
3327                         // If this is ever reached, then we failed to
3328                         // find the name as a namespace
3329                         //
3330
3331                         Error (103, Location, "The name `" + Name +
3332                                "' does not exist in the class `" +
3333                                ec.DeclSpace.Name + "'");
3334                 }
3335         }
3336         
3337         /// <summary>
3338         ///   Fully resolved expression that evaluates to a type
3339         /// </summary>
3340         public class TypeExpr : Expression {
3341                 public TypeExpr (Type t)
3342                 {
3343                         Type = t;
3344                         eclass = ExprClass.Type;
3345                 }
3346
3347                 override public Expression DoResolve (EmitContext ec)
3348                 {
3349                         return this;
3350                 }
3351
3352                 override public void Emit (EmitContext ec)
3353                 {
3354                         throw new Exception ("Implement me");
3355                 }
3356         }
3357
3358         /// <summary>
3359         ///   MethodGroup Expression.
3360         ///  
3361         ///   This is a fully resolved expression that evaluates to a type
3362         /// </summary>
3363         public class MethodGroupExpr : Expression {
3364                 public MethodBase [] Methods;
3365                 Location loc;
3366                 Expression instance_expression = null;
3367                 
3368                 public MethodGroupExpr (MemberInfo [] mi, Location l)
3369                 {
3370                         Methods = new MethodBase [mi.Length];
3371                         mi.CopyTo (Methods, 0);
3372                         eclass = ExprClass.MethodGroup;
3373                         type = TypeManager.object_type;
3374                         loc = l;
3375                 }
3376
3377                 public MethodGroupExpr (ArrayList list, Location l)
3378                 {
3379                         Methods = new MethodBase [list.Count];
3380
3381                         try {
3382                                 list.CopyTo (Methods, 0);
3383                         } catch {
3384                                 foreach (MemberInfo m in list){
3385                                         if (!(m is MethodBase)){
3386                                                 Console.WriteLine ("Name " + m.Name);
3387                                                 Console.WriteLine ("Found a: " + m.GetType ().FullName);
3388                                         }
3389                                 }
3390                                 throw;
3391                         }
3392                         loc = l;
3393                         eclass = ExprClass.MethodGroup;
3394                         type = TypeManager.object_type;
3395                 }
3396                 
3397                 //
3398                 // `A method group may have associated an instance expression' 
3399                 // 
3400                 public Expression InstanceExpression {
3401                         get {
3402                                 return instance_expression;
3403                         }
3404
3405                         set {
3406                                 instance_expression = value;
3407                         }
3408                 }
3409                 
3410                 override public Expression DoResolve (EmitContext ec)
3411                 {
3412                         return this;
3413                 }
3414
3415                 public void ReportUsageError ()
3416                 {
3417                         Report.Error (654, loc, "Method `" + Methods [0].DeclaringType + "." +
3418                                       Methods [0].Name + "()' is referenced without parentheses");
3419                 }
3420
3421                 override public void Emit (EmitContext ec)
3422                 {
3423                         ReportUsageError ();
3424                 }
3425
3426                 bool RemoveMethods (bool keep_static)
3427                 {
3428                         ArrayList smethods = new ArrayList ();
3429
3430                         foreach (MethodBase mb in Methods){
3431                                 if (mb.IsStatic == keep_static)
3432                                         smethods.Add (mb);
3433                         }
3434
3435                         if (smethods.Count == 0)
3436                                 return false;
3437
3438                         Methods = new MethodBase [smethods.Count];
3439                         smethods.CopyTo (Methods, 0);
3440
3441                         return true;
3442                 }
3443                 
3444                 /// <summary>
3445                 ///   Removes any instance methods from the MethodGroup, returns
3446                 ///   false if the resulting set is empty.
3447                 /// </summary>
3448                 public bool RemoveInstanceMethods ()
3449                 {
3450                         return RemoveMethods (true);
3451                 }
3452
3453                 /// <summary>
3454                 ///   Removes any static methods from the MethodGroup, returns
3455                 ///   false if the resulting set is empty.
3456                 /// </summary>
3457                 public bool RemoveStaticMethods ()
3458                 {
3459                         return RemoveMethods (false);
3460                 }
3461         }
3462
3463         /// <summary>
3464         ///   Fully resolved expression that evaluates to a Field
3465         /// </summary>
3466         public class FieldExpr : Expression, IAssignMethod, IMemoryLocation {
3467                 public readonly FieldInfo FieldInfo;
3468                 public Expression InstanceExpression;
3469                 Location loc;
3470                 
3471                 public FieldExpr (FieldInfo fi, Location l)
3472                 {
3473                         FieldInfo = fi;
3474                         eclass = ExprClass.Variable;
3475                         type = fi.FieldType;
3476                         loc = l;
3477                 }
3478
3479                 override public Expression DoResolve (EmitContext ec)
3480                 {
3481                         if (!FieldInfo.IsStatic){
3482                                 if (InstanceExpression == null){
3483                                         throw new Exception ("non-static FieldExpr without instance var\n" +
3484                                                              "You have to assign the Instance variable\n" +
3485                                                              "Of the FieldExpr to set this\n");
3486                                 }
3487
3488                                 InstanceExpression = InstanceExpression.Resolve (ec);
3489                                 if (InstanceExpression == null)
3490                                         return null;
3491                         }
3492
3493                         return this;
3494                 }
3495
3496                 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
3497                 {
3498                         Expression e = DoResolve (ec);
3499
3500                         if (e == null)
3501                                 return null;
3502                         
3503                         if (!FieldInfo.IsInitOnly)
3504                                 return this;
3505
3506                         //
3507                         // InitOnly fields can only be assigned in constructors
3508                         //
3509
3510                         if (ec.IsConstructor)
3511                                 return this;
3512
3513                         Report.Error (191, loc,
3514                                       "Readonly field can not be assigned outside " +
3515                                       "of constructor or variable initializer");
3516                         
3517                         return null;
3518                 }
3519
3520                 override public void Emit (EmitContext ec)
3521                 {
3522                         ILGenerator ig = ec.ig;
3523                         bool is_volatile = false;
3524                                 
3525                         if (FieldInfo is FieldBuilder){
3526                                 FieldBase f = TypeManager.GetField (FieldInfo);
3527
3528                                 if ((f.ModFlags & Modifiers.VOLATILE) != 0)
3529                                         is_volatile = true;
3530                                 
3531                                 f.status |= Field.Status.USED;
3532                         }
3533                         
3534                         if (FieldInfo.IsStatic){
3535                                 if (is_volatile)
3536                                         ig.Emit (OpCodes.Volatile);
3537                                 
3538                                 ig.Emit (OpCodes.Ldsfld, FieldInfo);
3539                         } else {
3540                                 if (InstanceExpression.Type.IsValueType){
3541                                         IMemoryLocation ml;
3542                                         LocalTemporary tempo = null;
3543                                         
3544                                         if (!(InstanceExpression is IMemoryLocation)){
3545                                                 tempo = new LocalTemporary (
3546                                                         ec, InstanceExpression.Type);
3547
3548                                                 InstanceExpression.Emit (ec);
3549                                                 tempo.Store (ec);
3550                                                 ml = tempo;
3551                                         } else
3552                                                 ml = (IMemoryLocation) InstanceExpression;
3553
3554                                         ml.AddressOf (ec, AddressOp.Load);
3555                                 } else 
3556                                         InstanceExpression.Emit (ec);
3557
3558                                 if (is_volatile)
3559                                         ig.Emit (OpCodes.Volatile);
3560                                 
3561                                 ig.Emit (OpCodes.Ldfld, FieldInfo);
3562                         }
3563                 }
3564
3565                 public void EmitAssign (EmitContext ec, Expression source)
3566                 {
3567                         bool is_static = FieldInfo.IsStatic;
3568                         ILGenerator ig = ec.ig;
3569                         
3570                         if (!is_static){
3571                                 Expression instance = InstanceExpression;
3572
3573                                 if (instance.Type.IsValueType){
3574                                         if (instance is IMemoryLocation){
3575                                                 IMemoryLocation ml = (IMemoryLocation) instance;
3576
3577                                                 ml.AddressOf (ec, AddressOp.Store);
3578                                         } else
3579                                                 throw new Exception ("The " + instance + " of type " +
3580                                                                      instance.Type +
3581                                                                      " represents a ValueType and does " +
3582                                                                      "not implement IMemoryLocation");
3583                                 } else
3584                                         instance.Emit (ec);
3585                         }
3586                         source.Emit (ec);
3587
3588                         if (FieldInfo is FieldBuilder){
3589                                 FieldBase f = TypeManager.GetField (FieldInfo);
3590                                 
3591                                 if ((f.ModFlags & Modifiers.VOLATILE) != 0)
3592                                         ig.Emit (OpCodes.Volatile);
3593                         }
3594                         
3595                         if (is_static)
3596                                 ig.Emit (OpCodes.Stsfld, FieldInfo);
3597                         else 
3598                                 ig.Emit (OpCodes.Stfld, FieldInfo);
3599
3600                         if (FieldInfo is FieldBuilder){
3601                                 FieldBase f = TypeManager.GetField (FieldInfo);
3602
3603                                 f.status |= Field.Status.ASSIGNED;
3604                         }
3605                 }
3606                 
3607                 public void AddressOf (EmitContext ec, AddressOp mode)
3608                 {
3609                         ILGenerator ig = ec.ig;
3610                         
3611                         if (FieldInfo is FieldBuilder){
3612                                 FieldBase f = TypeManager.GetField (FieldInfo);
3613                                 if ((f.ModFlags & Modifiers.VOLATILE) != 0)
3614                                         ig.Emit (OpCodes.Volatile);
3615                         }
3616
3617                         if (FieldInfo is FieldBuilder){
3618                                 FieldBase f = TypeManager.GetField (FieldInfo);
3619
3620                                 if ((mode & AddressOp.Store) != 0)
3621                                         f.status |= Field.Status.ASSIGNED;
3622                                 if ((mode & AddressOp.Load) != 0)
3623                                         f.status |= Field.Status.USED;
3624                         }
3625
3626                         //
3627                         // Handle initonly fields specially: make a copy and then
3628                         // get the address of the copy.
3629                         //
3630                         if (FieldInfo.IsInitOnly){
3631                                 LocalBuilder local;
3632                                 
3633                                 Emit (ec);
3634                                 local = ig.DeclareLocal (type);
3635                                 ig.Emit (OpCodes.Stloc, local);
3636                                 ig.Emit (OpCodes.Ldloca, local);
3637                                 return;
3638                         } 
3639
3640                         if (FieldInfo.IsStatic)
3641                                 ig.Emit (OpCodes.Ldsflda, FieldInfo);
3642                         else {
3643                                 InstanceExpression.Emit (ec);
3644                                 ig.Emit (OpCodes.Ldflda, FieldInfo);
3645                         }
3646                 }
3647         }
3648         
3649         /// <summary>
3650         ///   Expression that evaluates to a Property.  The Assign class
3651         ///   might set the `Value' expression if we are in an assignment.
3652         ///
3653         ///   This is not an LValue because we need to re-write the expression, we
3654         ///   can not take data from the stack and store it.  
3655         /// </summary>
3656         public class PropertyExpr : ExpressionStatement, IAssignMethod {
3657                 public readonly PropertyInfo PropertyInfo;
3658                 public readonly bool IsStatic;
3659                 public bool IsBase;
3660                 MethodInfo [] Accessors;
3661                 Location loc;
3662                 
3663                 Expression instance_expr;
3664                 
3665                 public PropertyExpr (PropertyInfo pi, Location l)
3666                 {
3667                         PropertyInfo = pi;
3668                         eclass = ExprClass.PropertyAccess;
3669                         IsStatic = false;
3670                         loc = l;
3671                         Accessors = TypeManager.GetAccessors (pi);
3672
3673                         if (Accessors != null)
3674                                 foreach (MethodInfo mi in Accessors){
3675                                         if (mi != null)
3676                                                 if (mi.IsStatic)
3677                                                         IsStatic = true;
3678                                 }
3679                         else
3680                                 Accessors = new MethodInfo [2];
3681                         
3682                         type = pi.PropertyType;
3683                 }
3684
3685                 //
3686                 // The instance expression associated with this expression
3687                 //
3688                 public Expression InstanceExpression {
3689                         set {
3690                                 instance_expr = value;
3691                         }
3692
3693                         get {
3694                                 return instance_expr;
3695                         }
3696                 }
3697
3698                 public bool VerifyAssignable ()
3699                 {
3700                         if (!PropertyInfo.CanWrite){
3701                                 Report.Error (200, loc, 
3702                                               "The property `" + PropertyInfo.Name +
3703                                               "' can not be assigned to, as it has not set accessor");
3704                                 return false;
3705                         }
3706
3707                         return true;
3708                 }
3709
3710                 override public Expression DoResolve (EmitContext ec)
3711                 {
3712                         if (!PropertyInfo.CanRead){
3713                                 Report.Error (154, loc, 
3714                                               "The property `" + PropertyInfo.Name +
3715                                               "' can not be used in " +
3716                                               "this context because it lacks a get accessor");
3717                                 return null;
3718                         }
3719
3720                         type = PropertyInfo.PropertyType;
3721
3722                         return this;
3723                 }
3724
3725                 override public void Emit (EmitContext ec)
3726                 {
3727                         MethodInfo method = Accessors [0];
3728
3729                         //
3730                         // Special case: length of single dimension array is turned into ldlen
3731                         //
3732                         if (method == TypeManager.int_array_get_length){
3733                                 Type iet = instance_expr.Type;
3734
3735                                 if (iet.GetArrayRank () == 1){
3736                                         instance_expr.Emit (ec);
3737                                         ec.ig.Emit (OpCodes.Ldlen);
3738                                         return;
3739                                 }
3740                         }
3741
3742                         Invocation.EmitCall (ec, IsBase, IsStatic, instance_expr, method, null);
3743                         
3744                 }
3745
3746                 //
3747                 // Implements the IAssignMethod interface for assignments
3748                 //
3749                 public void EmitAssign (EmitContext ec, Expression source)
3750                 {
3751                         Argument arg = new Argument (source, Argument.AType.Expression);
3752                         ArrayList args = new ArrayList ();
3753
3754                         args.Add (arg);
3755                         Invocation.EmitCall (ec, false, IsStatic, instance_expr, Accessors [1], args);
3756                 }
3757
3758                 override public void EmitStatement (EmitContext ec)
3759                 {
3760                         Emit (ec);
3761                         ec.ig.Emit (OpCodes.Pop);
3762                 }
3763         }
3764
3765         /// <summary>
3766         ///   Fully resolved expression that evaluates to an Event
3767         /// </summary>
3768         public class EventExpr : Expression {
3769                 public readonly EventInfo EventInfo;
3770                 Location loc;
3771                 public Expression InstanceExpression;
3772
3773                 public readonly bool IsStatic;
3774
3775                 MethodInfo add_accessor, remove_accessor;
3776                 
3777                 public EventExpr (EventInfo ei, Location loc)
3778                 {
3779                         EventInfo = ei;
3780                         this.loc = loc;
3781                         eclass = ExprClass.EventAccess;
3782
3783                         add_accessor = TypeManager.GetAddMethod (ei);
3784                         remove_accessor = TypeManager.GetRemoveMethod (ei);
3785                         
3786                         if (add_accessor.IsStatic || remove_accessor.IsStatic)
3787                                         IsStatic = true;
3788
3789                         if (EventInfo is MyEventBuilder)
3790                                 type = ((MyEventBuilder) EventInfo).EventType;
3791                         else
3792                                 type = EventInfo.EventHandlerType;
3793                 }
3794
3795                 override public Expression DoResolve (EmitContext ec)
3796                 {
3797                         // We are born fully resolved
3798                         return this;
3799                 }
3800
3801                 override public void Emit (EmitContext ec)
3802                 {
3803                         throw new Exception ("Should not happen I think");
3804                 }
3805
3806                 public void EmitAddOrRemove (EmitContext ec, Expression source)
3807                 {
3808                         Expression handler = ((Binary) source).Right;
3809                         
3810                         Argument arg = new Argument (handler, Argument.AType.Expression);
3811                         ArrayList args = new ArrayList ();
3812                                 
3813                         args.Add (arg);
3814                         
3815                         if (((Binary) source).Oper == Binary.Operator.Addition)
3816                                 Invocation.EmitCall (
3817                                         ec, false, IsStatic, InstanceExpression, add_accessor, args);
3818                         else
3819                                 Invocation.EmitCall (
3820                                         ec, false, IsStatic, InstanceExpression, remove_accessor, args);
3821                 }
3822         }
3823 }