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