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