**** Merged from MCS ****
[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 IntConstant){
792                                 Expression e;
793                                 
794                                 e = TryImplicitIntConversion (target_type, (IntConstant) expr);
795
796                                 if (e != null)
797                                         return e;
798                         } else if (expr is LongConstant && target_type == TypeManager.uint64_type){
799                                 //
800                                 // Try the implicit constant expression conversion
801                                 // from long to ulong, instead of a nice routine,
802                                 // we just inline it
803                                 //
804                                 long v = ((LongConstant) expr).Value;
805                                 if (v > 0)
806                                         return new ULongConstant ((ulong) v);
807                         }
808
809                         Type real_target_type = target_type;
810
811                         if (expr_type == TypeManager.sbyte_type){
812                                 //
813                                 // From sbyte to short, int, long, float, double.
814                                 //
815                                 if (real_target_type == TypeManager.int32_type)
816                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_I4);
817                                 if (real_target_type == TypeManager.int64_type)
818                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_I8);
819                                 if (real_target_type == TypeManager.double_type)
820                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_R8);
821                                 if (real_target_type == TypeManager.float_type)
822                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_R4);
823                                 if (real_target_type == TypeManager.short_type)
824                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_I2);
825                         } else if (expr_type == TypeManager.byte_type){
826                                 //
827                                 // From byte to short, ushort, int, uint, long, ulong, float, double
828                                 // 
829                                 if ((real_target_type == TypeManager.short_type) ||
830                                     (real_target_type == TypeManager.ushort_type) ||
831                                     (real_target_type == TypeManager.int32_type) ||
832                                     (real_target_type == TypeManager.uint32_type))
833                                         return new EmptyCast (expr, target_type);
834
835                                 if (real_target_type == TypeManager.uint64_type)
836                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_U8);
837                                 if (real_target_type == TypeManager.int64_type)
838                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_I8);
839                                 if (real_target_type == TypeManager.float_type)
840                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_R4);
841                                 if (real_target_type == TypeManager.double_type)
842                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_R8);
843                         } else if (expr_type == TypeManager.short_type){
844                                 //
845                                 // From short to int, long, float, double
846                                 // 
847                                 if (real_target_type == TypeManager.int32_type)
848                                         return new EmptyCast (expr, target_type);
849                                 if (real_target_type == TypeManager.int64_type)
850                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_I8);
851                                 if (real_target_type == TypeManager.double_type)
852                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_R8);
853                                 if (real_target_type == TypeManager.float_type)
854                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_R4);
855                         } else if (expr_type == TypeManager.ushort_type){
856                                 //
857                                 // From ushort to int, uint, long, ulong, float, double
858                                 //
859                                 if (real_target_type == TypeManager.uint32_type)
860                                         return new EmptyCast (expr, target_type);
861
862                                 if (real_target_type == TypeManager.uint64_type)
863                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_U8);
864                                 if (real_target_type == TypeManager.int32_type)
865                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_I4);
866                                 if (real_target_type == TypeManager.int64_type)
867                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_I8);
868                                 if (real_target_type == TypeManager.double_type)
869                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_R8);
870                                 if (real_target_type == TypeManager.float_type)
871                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_R4);
872                         } else if (expr_type == TypeManager.int32_type){
873                                 //
874                                 // From int to long, float, double
875                                 //
876                                 if (real_target_type == TypeManager.int64_type)
877                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_I8);
878                                 if (real_target_type == TypeManager.double_type)
879                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_R8);
880                                 if (real_target_type == TypeManager.float_type)
881                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_R4);
882                         } else if (expr_type == TypeManager.uint32_type){
883                                 //
884                                 // From uint to long, ulong, float, double
885                                 //
886                                 if (real_target_type == TypeManager.int64_type)
887                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_U8);
888                                 if (real_target_type == TypeManager.uint64_type)
889                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_U8);
890                                 if (real_target_type == TypeManager.double_type)
891                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_R_Un,
892                                                                OpCodes.Conv_R8);
893                                 if (real_target_type == TypeManager.float_type)
894                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_R_Un,
895                                                                OpCodes.Conv_R4);
896                         } else if (expr_type == TypeManager.int64_type){
897                                 //
898                                 // From long/ulong to float, double
899                                 //
900                                 if (real_target_type == TypeManager.double_type)
901                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_R8);
902                                 if (real_target_type == TypeManager.float_type)
903                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_R4);     
904                         } else if (expr_type == TypeManager.uint64_type){
905                                 //
906                                 // From ulong to float, double
907                                 //
908                                 if (real_target_type == TypeManager.double_type)
909                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_R_Un,
910                                                                OpCodes.Conv_R8);
911                                 if (real_target_type == TypeManager.float_type)
912                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_R_Un,
913                                                                OpCodes.Conv_R4);        
914                         } else if (expr_type == TypeManager.char_type){
915                                 //
916                                 // From char to ushort, int, uint, long, ulong, float, double
917                                 // 
918                                 if ((real_target_type == TypeManager.ushort_type) ||
919                                     (real_target_type == TypeManager.int32_type) ||
920                                     (real_target_type == TypeManager.uint32_type))
921                                         return new EmptyCast (expr, target_type);
922                                 if (real_target_type == TypeManager.uint64_type)
923                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_U8);
924                                 if (real_target_type == TypeManager.int64_type)
925                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_I8);
926                                 if (real_target_type == TypeManager.float_type)
927                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_R4);
928                                 if (real_target_type == TypeManager.double_type)
929                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_R8);
930                         } else if (expr_type == TypeManager.float_type){
931                                 //
932                                 // float to double
933                                 //
934                                 if (real_target_type == TypeManager.double_type)
935                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_R8);
936                         }
937
938                         return null;
939                 }
940
941                 //
942                 // Tests whether an implicit reference conversion exists between expr_type
943                 // and target_type
944                 //
945                 public static bool ImplicitReferenceConversionExists (Expression expr, Type expr_type, Type target_type)
946                 {
947                         //
948                         // This is the boxed case.
949                         //
950                         if (target_type == TypeManager.object_type) {
951                                 if ((expr_type.IsClass) ||
952                                     (expr_type.IsValueType) ||
953                                     (expr_type.IsInterface))
954                                         return true;
955                                 
956                         } else if (expr_type.IsSubclassOf (target_type)) {
957                                 return true;
958                         } else {
959                                 // Please remember that all code below actually comes
960                                 // from ImplicitReferenceConversion so make sure code remains in sync
961                                 
962                                 // from any class-type S to any interface-type T.
963                                 if (target_type.IsInterface) {
964                                         if (TypeManager.ImplementsInterface (expr_type, target_type))
965                                                 return true;
966                                 }
967                                 
968                                 // from any interface type S to interface-type T.
969                                 if (expr_type.IsInterface && target_type.IsInterface)
970                                         if (TypeManager.ImplementsInterface (expr_type, target_type))
971                                                 return true;
972                                 
973                                 // from an array-type S to an array-type of type T
974                                 if (expr_type.IsArray && target_type.IsArray) {
975                                         if (expr_type.GetArrayRank () == target_type.GetArrayRank ()) {
976                                                 
977                                                 Type expr_element_type = expr_type.GetElementType ();
978
979                                                 if (MyEmptyExpr == null)
980                                                         MyEmptyExpr = new EmptyExpression ();
981                                                 
982                                                 MyEmptyExpr.SetType (expr_element_type);
983                                                 Type target_element_type = target_type.GetElementType ();
984                                                 
985                                                 if (!expr_element_type.IsValueType && !target_element_type.IsValueType)
986                                                         if (StandardConversionExists (MyEmptyExpr,
987                                                                                       target_element_type))
988                                                                 return true;
989                                         }
990                                 }
991                                 
992                                 // from an array-type to System.Array
993                                 if (expr_type.IsArray && (target_type == TypeManager.array_type))
994                                         return true;
995                                 
996                                 // from any delegate type to System.Delegate
997                                 if (expr_type.IsSubclassOf (TypeManager.delegate_type) &&
998                                     target_type == TypeManager.delegate_type)
999                                         if (target_type.IsAssignableFrom (expr_type))
1000                                                 return true;
1001                                         
1002                                 // from any array-type or delegate type into System.ICloneable.
1003                                 if (expr_type.IsArray || expr_type.IsSubclassOf (TypeManager.delegate_type))
1004                                         if (target_type == TypeManager.icloneable_type)
1005                                                 return true;
1006                                 
1007                                 // from the null type to any reference-type.
1008                                 if (expr is NullLiteral && !target_type.IsValueType &&
1009                                     !TypeManager.IsEnumType (target_type))
1010                                         return true;
1011                                 
1012                         }
1013
1014                         return false;
1015                 }
1016
1017                 /// <summary>
1018                 ///  Same as StandardConversionExists except that it also looks at
1019                 ///  implicit user defined conversions - needed for overload resolution
1020                 /// </summary>
1021                 public static bool ImplicitConversionExists (EmitContext ec, Expression expr, Type target_type)
1022                 {
1023                         if (StandardConversionExists (expr, target_type) == true)
1024                                 return true;
1025
1026 #if false
1027                         Expression dummy = ImplicitUserConversion (ec, expr, target_type, Location.Null);
1028
1029                         if (dummy != null)
1030                                 return true;
1031 #endif
1032
1033                         return false;
1034                 }
1035
1036                 /// <summary>
1037                 ///  Determines if a standard implicit conversion exists from
1038                 ///  expr_type to target_type
1039                 /// </summary>
1040                 public static bool StandardConversionExists (Expression expr, Type target_type)
1041                 {
1042                         return WideningConversionExists (expr, expr.type, target_type);
1043                 }
1044
1045                 public static bool WideningConversionExists (Type expr_type, Type target_type)
1046                 {
1047                         return WideningConversionExists (null, expr_type, target_type);
1048                 }
1049
1050                 public static bool WideningConversionExists (Expression expr, Type target_type)
1051                 {
1052                         return WideningConversionExists (expr, expr.Type, target_type);
1053                 }
1054
1055                 public static bool WideningConversionExists (Expression expr, Type expr_type, Type target_type)
1056                 {
1057                         if (expr_type == null || expr_type == TypeManager.void_type)
1058                                 return false;
1059                         
1060                         if (expr_type == target_type)
1061                                 return true;
1062
1063                         // Conversions from enum to underlying type are widening.
1064                         if (expr_type.IsSubclassOf (TypeManager.enum_type))
1065                                 expr_type = TypeManager.EnumToUnderlying (expr_type);
1066
1067                         if (expr_type == target_type)
1068                                 return true;
1069
1070                         // First numeric conversions 
1071
1072                         if (expr_type == TypeManager.sbyte_type){
1073                                 //
1074                                 // From sbyte to short, int, long, float, double.
1075                                 //
1076                                 if ((target_type == TypeManager.int32_type) || 
1077                                     (target_type == TypeManager.int64_type) ||
1078                                     (target_type == TypeManager.double_type) ||
1079                                     (target_type == TypeManager.float_type)  ||
1080                                     (target_type == TypeManager.short_type) ||
1081                                     (target_type == TypeManager.decimal_type))
1082                                         return true;
1083                                 
1084                         } else if (expr_type == TypeManager.byte_type){
1085                                 //
1086                                 // From byte to short, ushort, int, uint, long, ulong, float, double
1087                                 // 
1088                                 if ((target_type == TypeManager.short_type) ||
1089                                     (target_type == TypeManager.ushort_type) ||
1090                                     (target_type == TypeManager.int32_type) ||
1091                                     (target_type == TypeManager.uint32_type) ||
1092                                     (target_type == TypeManager.uint64_type) ||
1093                                     (target_type == TypeManager.int64_type) ||
1094                                     (target_type == TypeManager.float_type) ||
1095                                     (target_type == TypeManager.double_type) ||
1096                                     (target_type == TypeManager.decimal_type))
1097                                         return true;
1098         
1099                         } else if (expr_type == TypeManager.short_type){
1100                                 //
1101                                 // From short to int, long, float, double
1102                                 // 
1103                                 if ((target_type == TypeManager.int32_type) ||
1104                                     (target_type == TypeManager.int64_type) ||
1105                                     (target_type == TypeManager.double_type) ||
1106                                     (target_type == TypeManager.float_type) ||
1107                                     (target_type == TypeManager.decimal_type))
1108                                         return true;
1109                                         
1110                         } else if (expr_type == TypeManager.ushort_type){
1111                                 //
1112                                 // From ushort to int, uint, long, ulong, float, double
1113                                 //
1114                                 if ((target_type == TypeManager.uint32_type) ||
1115                                     (target_type == TypeManager.uint64_type) ||
1116                                     (target_type == TypeManager.int32_type) ||
1117                                     (target_type == TypeManager.int64_type) ||
1118                                     (target_type == TypeManager.double_type) ||
1119                                     (target_type == TypeManager.float_type) ||
1120                                     (target_type == TypeManager.decimal_type))
1121                                         return true;
1122                                     
1123                         } else if (expr_type == TypeManager.int32_type){
1124                                 //
1125                                 // From int to long, float, double
1126                                 //
1127                                 if ((target_type == TypeManager.int64_type) ||
1128                                     (target_type == TypeManager.double_type) ||
1129                                     (target_type == TypeManager.float_type) ||
1130                                     (target_type == TypeManager.decimal_type))
1131                                         return true;
1132                                         
1133                         } else if (expr_type == TypeManager.uint32_type){
1134                                 //
1135                                 // From uint to long, ulong, float, double
1136                                 //
1137                                 if ((target_type == TypeManager.int64_type) ||
1138                                     (target_type == TypeManager.uint64_type) ||
1139                                     (target_type == TypeManager.double_type) ||
1140                                     (target_type == TypeManager.float_type) ||
1141                                     (target_type == TypeManager.decimal_type))
1142                                         return true;
1143                                         
1144                         } else if ((expr_type == TypeManager.uint64_type) ||
1145                                    (expr_type == TypeManager.int64_type)) {
1146                                 //
1147                                 // From long/ulong to float, double
1148                                 //
1149                                 if ((target_type == TypeManager.double_type) ||
1150                                     (target_type == TypeManager.float_type) ||
1151                                     (target_type == TypeManager.decimal_type))
1152                                         return true;
1153                                     
1154                         } else if (expr_type == TypeManager.char_type){
1155                                 //
1156                                 // From char to ushort, int, uint, long, ulong, float, double
1157                                 // 
1158                                 if ((target_type == TypeManager.ushort_type) ||
1159                                     (target_type == TypeManager.int32_type) ||
1160                                     (target_type == TypeManager.uint32_type) ||
1161                                     (target_type == TypeManager.uint64_type) ||
1162                                     (target_type == TypeManager.int64_type) ||
1163                                     (target_type == TypeManager.float_type) ||
1164                                     (target_type == TypeManager.double_type) ||
1165                                     (target_type == TypeManager.decimal_type))
1166                                         return true;
1167
1168                         } else if (expr_type == TypeManager.float_type){
1169                                 //
1170                                 // float to double
1171                                 //
1172                                 if (target_type == TypeManager.double_type)
1173                                         return true;
1174                         }       
1175                         
1176                         if (ImplicitReferenceConversionExists (expr, expr_type, target_type))
1177                                 return true;
1178                         
1179                         if (expr is IntConstant){
1180                                 int value = ((IntConstant) expr).Value;
1181
1182                                 if (target_type == TypeManager.sbyte_type){
1183                                         if (value >= SByte.MinValue && value <= SByte.MaxValue)
1184                                                 return true;
1185                                 } else if (target_type == TypeManager.byte_type){
1186                                         if (Byte.MinValue >= 0 && value <= Byte.MaxValue)
1187                                                 return true;
1188                                 } else if (target_type == TypeManager.short_type){
1189                                         if (value >= Int16.MinValue && value <= Int16.MaxValue)
1190                                                 return true;
1191                                 } else if (target_type == TypeManager.ushort_type){
1192                                         if (value >= UInt16.MinValue && value <= UInt16.MaxValue)
1193                                                 return true;
1194                                 } else if (target_type == TypeManager.uint32_type){
1195                                         if (value >= 0)
1196                                                 return true;
1197                                 } else if (target_type == TypeManager.uint64_type){
1198                                          //
1199                                          // we can optimize this case: a positive int32
1200                                          // always fits on a uint64.  But we need an opcode
1201                                          // to do it.
1202                                          //
1203                                         if (value >= 0)
1204                                                 return true;
1205                                 }
1206                                 
1207                                 if (value == 0 && expr is IntLiteral && TypeManager.IsEnumType (target_type))
1208                                         return true;
1209                         }
1210
1211                         if (expr is LongConstant && target_type == TypeManager.uint64_type){
1212                                 //
1213                                 // Try the implicit constant expression conversion
1214                                 // from long to ulong, instead of a nice routine,
1215                                 // we just inline it
1216                                 //
1217                                 long v = ((LongConstant) expr).Value;
1218                                 if (v > 0)
1219                                         return true;
1220                         }
1221                         
1222                         if (target_type.IsSubclassOf (TypeManager.enum_type) && expr is IntLiteral){
1223                                 IntLiteral i = (IntLiteral) expr;
1224
1225                                 if (i.Value == 0)
1226                                         return true;
1227                         }
1228
1229                         if (target_type == TypeManager.void_ptr_type && expr_type.IsPointer)
1230                                 return true;
1231
1232                         return false;
1233                 }
1234
1235                 //
1236                 // Used internally by FindMostEncompassedType, this is used
1237                 // to avoid creating lots of objects in the tight loop inside
1238                 // FindMostEncompassedType
1239                 //
1240                 static EmptyExpression priv_fmet_param;
1241                 
1242                 /// <summary>
1243                 ///  Finds "most encompassed type" according to the spec (13.4.2)
1244                 ///  amongst the methods in the MethodGroupExpr
1245                 /// </summary>
1246                 static Type FindMostEncompassedType (ArrayList types)
1247                 {
1248                         Type best = null;
1249
1250                         if (priv_fmet_param == null)
1251                                 priv_fmet_param = new EmptyExpression ();
1252
1253                         foreach (Type t in types){
1254                                 priv_fmet_param.SetType (t);
1255                                 
1256                                 if (best == null) {
1257                                         best = t;
1258                                         continue;
1259                                 }
1260                                 
1261                                 if (StandardConversionExists (priv_fmet_param, best))
1262                                         best = t;
1263                         }
1264
1265                         return best;
1266                 }
1267
1268                 //
1269                 // Used internally by FindMostEncompassingType, this is used
1270                 // to avoid creating lots of objects in the tight loop inside
1271                 // FindMostEncompassingType
1272                 //
1273                 static EmptyExpression priv_fmee_ret;
1274                 
1275                 /// <summary>
1276                 ///  Finds "most encompassing type" according to the spec (13.4.2)
1277                 ///  amongst the types in the given set
1278                 /// </summary>
1279                 static Type FindMostEncompassingType (ArrayList types)
1280                 {
1281                         Type best = null;
1282
1283                         if (priv_fmee_ret == null)
1284                                 priv_fmee_ret = new EmptyExpression ();
1285
1286                         foreach (Type t in types){
1287                                 priv_fmee_ret.SetType (best);
1288
1289                                 if (best == null) {
1290                                         best = t;
1291                                         continue;
1292                                 }
1293
1294                                 if (StandardConversionExists (priv_fmee_ret, t))
1295                                         best = t;
1296                         }
1297                         
1298                         return best;
1299                 }
1300
1301                 //
1302                 // Used to avoid creating too many objects
1303                 //
1304                 static EmptyExpression priv_fms_expr;
1305                 
1306                 /// <summary>
1307                 ///   Finds the most specific source Sx according to the rules of the spec (13.4.4)
1308                 ///   by making use of FindMostEncomp* methods. Applies the correct rules separately
1309                 ///   for explicit and implicit conversion operators.
1310                 /// </summary>
1311                 static public Type FindMostSpecificSource (MethodGroupExpr me, Expression source,
1312                                                            bool apply_explicit_conv_rules,
1313                                                            Location loc)
1314                 {
1315                         ArrayList src_types_set = new ArrayList ();
1316                         
1317                         if (priv_fms_expr == null)
1318                                 priv_fms_expr = new EmptyExpression ();
1319
1320                         //
1321                         // If any operator converts from S then Sx = S
1322                         //
1323                         Type source_type = source.Type;
1324                         foreach (MethodBase mb in me.Methods){
1325                                 ParameterData pd = Invocation.GetParameterData (mb);
1326                                 Type param_type = pd.ParameterType (0);
1327
1328                                 if (param_type == source_type)
1329                                         return param_type;
1330
1331                                 if (apply_explicit_conv_rules) {
1332                                         //
1333                                         // From the spec :
1334                                         // Find the set of applicable user-defined conversion operators, U.  This set
1335                                         // consists of the
1336                                         // user-defined implicit or explicit conversion operators declared by
1337                                         // the classes or structs in D that convert from a type encompassing
1338                                         // or encompassed by S to a type encompassing or encompassed by T
1339                                         //
1340                                         priv_fms_expr.SetType (param_type);
1341                                         if (StandardConversionExists (priv_fms_expr, source_type))
1342                                                 src_types_set.Add (param_type);
1343                                         else {
1344                                                 if (StandardConversionExists (source, param_type))
1345                                                         src_types_set.Add (param_type);
1346                                         }
1347                                 } else {
1348                                         //
1349                                         // Only if S is encompassed by param_type
1350                                         //
1351                                         if (StandardConversionExists (source, param_type))
1352                                                 src_types_set.Add (param_type);
1353                                 }
1354                         }
1355                         
1356                         //
1357                         // Explicit Conv rules
1358                         //
1359                         if (apply_explicit_conv_rules) {
1360                                 ArrayList candidate_set = new ArrayList ();
1361
1362                                 foreach (Type param_type in src_types_set){
1363                                         if (StandardConversionExists (source, param_type))
1364                                                 candidate_set.Add (param_type);
1365                                 }
1366
1367                                 if (candidate_set.Count != 0)
1368                                         return FindMostEncompassedType (candidate_set);
1369                         }
1370
1371                         //
1372                         // Final case
1373                         //
1374                         if (apply_explicit_conv_rules)
1375                                 return FindMostEncompassingType (src_types_set);
1376                         else
1377                                 return FindMostEncompassedType (src_types_set);
1378                 }
1379
1380                 //
1381                 // Useful in avoiding proliferation of objects
1382                 //
1383                 static EmptyExpression priv_fmt_expr;
1384                 
1385                 /// <summary>
1386                 ///  Finds the most specific target Tx according to section 13.4.4
1387                 /// </summary>
1388                 static public Type FindMostSpecificTarget (MethodGroupExpr me, Type target,
1389                                                            bool apply_explicit_conv_rules,
1390                                                            Location loc)
1391                 {
1392                         ArrayList tgt_types_set = new ArrayList ();
1393                         
1394                         if (priv_fmt_expr == null)
1395                                 priv_fmt_expr = new EmptyExpression ();
1396                         
1397                         //
1398                         // If any operator converts to T then Tx = T
1399                         //
1400                         foreach (MethodInfo mi in me.Methods){
1401                                 Type ret_type = mi.ReturnType;
1402
1403                                 if (ret_type == target)
1404                                         return ret_type;
1405
1406                                 if (apply_explicit_conv_rules) {
1407                                         //
1408                                         // From the spec :
1409                                         // Find the set of applicable user-defined conversion operators, U.
1410                                         //
1411                                         // This set consists of the
1412                                         // user-defined implicit or explicit conversion operators declared by
1413                                         // the classes or structs in D that convert from a type encompassing
1414                                         // or encompassed by S to a type encompassing or encompassed by T
1415                                         //
1416                                         priv_fms_expr.SetType (ret_type);
1417                                         if (StandardConversionExists (priv_fms_expr, target))
1418                                                 tgt_types_set.Add (ret_type);
1419                                         else {
1420                                                 priv_fms_expr.SetType (target);
1421                                                 if (StandardConversionExists (priv_fms_expr, ret_type))
1422                                                         tgt_types_set.Add (ret_type);
1423                                         }
1424                                 } else {
1425                                         //
1426                                         // Only if T is encompassed by param_type
1427                                         //
1428                                         priv_fms_expr.SetType (ret_type);
1429                                         if (StandardConversionExists (priv_fms_expr, target))
1430                                                 tgt_types_set.Add (ret_type);
1431                                 }
1432                         }
1433
1434                         //
1435                         // Explicit conv rules
1436                         //
1437                         if (apply_explicit_conv_rules) {
1438                                 ArrayList candidate_set = new ArrayList ();
1439
1440                                 foreach (Type ret_type in tgt_types_set){
1441                                         priv_fmt_expr.SetType (ret_type);
1442                                         
1443                                         if (StandardConversionExists (priv_fmt_expr, target))
1444                                                 candidate_set.Add (ret_type);
1445                                 }
1446
1447                                 if (candidate_set.Count != 0)
1448                                         return FindMostEncompassingType (candidate_set);
1449                         }
1450                         
1451                         //
1452                         // Okay, final case !
1453                         //
1454                         if (apply_explicit_conv_rules)
1455                                 return FindMostEncompassedType (tgt_types_set);
1456                         else 
1457                                 return FindMostEncompassingType (tgt_types_set);
1458                 }
1459                 
1460                 /// <summary>
1461                 ///  User-defined Implicit conversions
1462                 /// </summary>
1463                 static public Expression ImplicitUserConversion (EmitContext ec, Expression source,
1464                                                                  Type target, Location loc)
1465                 {
1466                         return UserDefinedConversion (ec, source, target, loc, false);
1467                 }
1468
1469                 /// <summary>
1470                 ///  User-defined Explicit conversions
1471                 /// </summary>
1472                 static public Expression ExplicitUserConversion (EmitContext ec, Expression source,
1473                                                                  Type target, Location loc)
1474                 {
1475                         return UserDefinedConversion (ec, source, target, loc, true);
1476                 }
1477
1478                 /// <summary>
1479                 ///   Computes the MethodGroup for the user-defined conversion
1480                 ///   operators from source_type to target_type.  'look_for_explicit'
1481                 ///   controls whether we should also include the list of explicit
1482                 ///   operators
1483                 /// </summary>
1484                 static MethodGroupExpr GetConversionOperators (EmitContext ec,
1485                                                                Type source_type, Type target_type,
1486                                                                Location loc, bool look_for_explicit)
1487                 {
1488                         Expression mg1 = null, mg2 = null;
1489                         Expression mg5 = null, mg6 = null, mg7 = null, mg8 = null;
1490                         string op_name;
1491
1492                         //
1493                         // FIXME : How does the False operator come into the picture ?
1494                         // This doesn't look complete and very correct !
1495                         //
1496                         if (target_type == TypeManager.bool_type && !look_for_explicit)
1497                                 op_name = "op_True";
1498                         else
1499                                 op_name = "op_Implicit";
1500
1501                         MethodGroupExpr union3;
1502                         
1503                         mg1 = MethodLookup (ec, source_type, op_name, loc);
1504                         if (source_type.BaseType != null)
1505                                 mg2 = MethodLookup (ec, source_type.BaseType, op_name, loc);
1506
1507                         if (mg1 == null)
1508                                 union3 = (MethodGroupExpr) mg2;
1509                         else if (mg2 == null)
1510                                 union3 = (MethodGroupExpr) mg1;
1511                         else
1512                                 union3 = Invocation.MakeUnionSet (mg1, mg2, loc);
1513
1514                         mg1 = MethodLookup (ec, target_type, op_name, loc);
1515                         if (mg1 != null){
1516                                 if (union3 != null)
1517                                         union3 = Invocation.MakeUnionSet (union3, mg1, loc);
1518                                 else
1519                                         union3 = (MethodGroupExpr) mg1;
1520                         }
1521
1522                         if (target_type.BaseType != null)
1523                                 mg1 = MethodLookup (ec, target_type.BaseType, op_name, loc);
1524                         
1525                         if (mg1 != null){
1526                                 if (union3 != null)
1527                                         union3 = Invocation.MakeUnionSet (union3, mg1, loc);
1528                                 else
1529                                         union3 = (MethodGroupExpr) mg1;
1530                         }
1531
1532                         MethodGroupExpr union4 = null;
1533
1534                         if (look_for_explicit) {
1535                                 op_name = "op_Explicit";
1536
1537                                 mg5 = MemberLookup (ec, source_type, op_name, loc);
1538                                 if (source_type.BaseType != null)
1539                                         mg6 = MethodLookup (ec, source_type.BaseType, op_name, loc);
1540                                 
1541                                 mg7 = MemberLookup (ec, target_type, op_name, loc);
1542                                 if (target_type.BaseType != null)
1543                                         mg8 = MethodLookup (ec, target_type.BaseType, op_name, loc);
1544                                 
1545                                 MethodGroupExpr union5 = Invocation.MakeUnionSet (mg5, mg6, loc);
1546                                 MethodGroupExpr union6 = Invocation.MakeUnionSet (mg7, mg8, loc);
1547
1548                                 union4 = Invocation.MakeUnionSet (union5, union6, loc);
1549                         }
1550                         
1551                         return Invocation.MakeUnionSet (union3, union4, loc);
1552                 }
1553                 
1554                 /// <summary>
1555                 ///   User-defined conversions
1556                 /// </summary>
1557                 static public Expression UserDefinedConversion (EmitContext ec, Expression source,
1558                                                                 Type target, Location loc,
1559                                                                 bool look_for_explicit)
1560                 {
1561                         MethodGroupExpr union;
1562                         Type source_type = source.Type;
1563                         MethodBase method = null;
1564                         
1565                         union = GetConversionOperators (ec, source_type, target, loc, look_for_explicit);
1566                         if (union == null)
1567                                 return null;
1568                         
1569                         Type most_specific_source, most_specific_target;
1570
1571 #if BLAH
1572                         foreach (MethodBase m in union.Methods){
1573                                 Console.WriteLine ("Name: " + m.Name);
1574                                 Console.WriteLine ("    : " + ((MethodInfo)m).ReturnType);
1575                         }
1576 #endif
1577                         
1578                         most_specific_source = FindMostSpecificSource (union, source, look_for_explicit, loc);
1579                         if (most_specific_source == null)
1580                                 return null;
1581
1582                         most_specific_target = FindMostSpecificTarget (union, target, look_for_explicit, loc);
1583                         if (most_specific_target == null) 
1584                                 return null;
1585
1586                         int count = 0;
1587
1588                         foreach (MethodBase mb in union.Methods){
1589                                 ParameterData pd = Invocation.GetParameterData (mb);
1590                                 MethodInfo mi = (MethodInfo) mb;
1591                                 
1592                                 if (pd.ParameterType (0) == most_specific_source &&
1593                                     mi.ReturnType == most_specific_target) {
1594                                         method = mb;
1595                                         count++;
1596                                 }
1597                         }
1598                         
1599                         if (method == null || count > 1)
1600                                 return null;
1601                         
1602                         
1603                         //
1604                         // This will do the conversion to the best match that we
1605                         // found.  Now we need to perform an implict standard conversion
1606                         // if the best match was not the type that we were requested
1607                         // by target.
1608                         //
1609                         if (look_for_explicit)
1610                                 source = ConvertExplicitStandard (ec, source, most_specific_source, loc);
1611                         else
1612                                 source = ConvertImplicitStandard (ec, source, most_specific_source, loc);
1613
1614                         if (source == null)
1615                                 return null;
1616
1617                         Expression e;
1618                         e =  new UserCast ((MethodInfo) method, source, loc);
1619                         if (e.Type != target){
1620                                 if (!look_for_explicit)
1621                                         e = ConvertImplicitStandard (ec, e, target, loc);
1622                                 else
1623                                         e = ConvertExplicitStandard (ec, e, target, loc);
1624                         } 
1625                         return e;
1626                 }
1627                 
1628                 /// <summary>
1629                 ///   Converts implicitly the resolved expression 'expr' into the
1630                 ///   'target_type'.  It returns a new expression that can be used
1631                 ///   in a context that expects a 'target_type'. 
1632                 /// </summary>
1633                 static public Expression ConvertImplicit (EmitContext ec, Expression expr,
1634                                                           Type target_type, Location loc)
1635                 {
1636                         Type expr_type = expr.Type;
1637                         Expression e;
1638
1639                         if (expr_type == target_type)
1640                                 return expr;
1641
1642                         if (target_type == null)
1643                                 throw new Exception ("Target type is null");
1644
1645                         e = ConvertImplicitStandard (ec, expr, target_type, loc);
1646                         if (e != null)
1647                                 return e;
1648
1649                         e = ImplicitUserConversion (ec, expr, target_type, loc);
1650                         if (e != null)
1651                                 return e;
1652                                 
1653                         e = NarrowingConversion (ec, expr, target_type, loc);
1654                         if (e != null)
1655                                 return e;                               
1656
1657                         return null;
1658                 }
1659
1660                 /// <summary>
1661                 ///   Converts the resolved expression 'expr' into the
1662                 ///   'target_type' using the Microsoft.VisualBasic runtime.
1663                 ///   It returns a new expression that can be used
1664                 ///   in a context that expects a 'target_type'. 
1665                 /// </summary>
1666                 static private Expression RTConversionExpression (EmitContext ec, string s, Expression expr, Location loc)
1667                 {
1668                         Expression etmp, e;
1669                         ArrayList args;
1670                         Argument arg;
1671                         
1672                         etmp = Mono.MonoBASIC.Parser.DecomposeQI("Microsoft.VisualBasic.CompilerServices." + s, loc);
1673                         args = new ArrayList();
1674                         arg = new Argument (expr, Argument.AType.Expression);
1675                         args.Add (arg);
1676                         e = (Expression) new Invocation (etmp, args, loc);
1677                         e = e.Resolve(ec);      
1678                         return (e);             
1679                 }
1680                 
1681                 static public bool NarrowingConversionExists (EmitContext ec, Expression expr, Type target_type)
1682                 {
1683                         Type expr_type = expr.Type;
1684
1685                         if (target_type == TypeManager.sbyte_type){
1686                                 //
1687                                 // To sbyte from short, int, long, float, double.
1688                                 //
1689                                 if ((expr_type == TypeManager.int32_type) || 
1690                                     (expr_type == TypeManager.int64_type) ||
1691                                     (expr_type == TypeManager.double_type) ||
1692                                     (expr_type == TypeManager.float_type)  ||
1693                                     (expr_type == TypeManager.short_type) ||
1694                                     (expr_type == TypeManager.decimal_type))
1695                                         return true;
1696                                 
1697                         } else if (target_type == TypeManager.byte_type){
1698                                 //
1699                                 // To byte from short, ushort, int, uint, long, ulong, float, double
1700                                 // 
1701                                 if ((expr_type == TypeManager.short_type) ||
1702                                     (expr_type == TypeManager.ushort_type) ||
1703                                     (expr_type == TypeManager.int32_type) ||
1704                                     (expr_type == TypeManager.uint32_type) ||
1705                                     (expr_type == TypeManager.uint64_type) ||
1706                                     (expr_type == TypeManager.int64_type) ||
1707                                     (expr_type == TypeManager.float_type) ||
1708                                     (expr_type == TypeManager.double_type) ||
1709                                     (expr_type == TypeManager.decimal_type))
1710                                         return true;
1711         
1712                         } else if (target_type == TypeManager.short_type){
1713                                 //
1714                                 // To short from int, long, float, double
1715                                 // 
1716                                 if ((expr_type == TypeManager.int32_type) ||
1717                                     (expr_type == TypeManager.int64_type) ||
1718                                     (expr_type == TypeManager.double_type) ||
1719                                     (expr_type == TypeManager.float_type) ||
1720                                     (expr_type == TypeManager.decimal_type))
1721                                         return true;
1722                                         
1723                         } else if (target_type == TypeManager.ushort_type){
1724                                 //
1725                                 // To ushort from int, uint, long, ulong, float, double
1726                                 //
1727                                 if ((expr_type == TypeManager.uint32_type) ||
1728                                     (expr_type == TypeManager.uint64_type) ||
1729                                     (expr_type == TypeManager.int32_type) ||
1730                                     (expr_type == TypeManager.int64_type) ||
1731                                     (expr_type == TypeManager.double_type) ||
1732                                     (expr_type == TypeManager.float_type) ||
1733                                     (expr_type == TypeManager.decimal_type))
1734                                         return true;
1735                                     
1736                         } else if (target_type == TypeManager.int32_type){
1737                                 //
1738                                 // To int from long, float, double
1739                                 //
1740                                 if ((expr_type == TypeManager.int64_type) ||
1741                                     (expr_type == TypeManager.double_type) ||
1742                                     (expr_type == TypeManager.float_type) ||
1743                                     (expr_type == TypeManager.decimal_type))
1744                                         return true;
1745                                         
1746                         } else if (target_type == TypeManager.uint32_type){
1747                                 //
1748                                 // To uint from long, ulong, float, double
1749                                 //
1750                                 if ((expr_type == TypeManager.int64_type) ||
1751                                     (expr_type == TypeManager.uint64_type) ||
1752                                     (expr_type == TypeManager.double_type) ||
1753                                     (expr_type == TypeManager.float_type) ||
1754                                     (expr_type == TypeManager.decimal_type))
1755                                         return true;
1756                                         
1757                         } else if ((target_type == TypeManager.uint64_type) ||
1758                                    (target_type == TypeManager.int64_type)) {
1759                                 //
1760                                 // To long/ulong from float, double
1761                                 //
1762                                 if ((expr_type == TypeManager.double_type) ||
1763                                     (expr_type == TypeManager.float_type) ||
1764                                     (expr_type == TypeManager.decimal_type))
1765                                         return true;
1766                                     
1767                         } else if (target_type == TypeManager.char_type){
1768                                 //
1769                                 // To char from ushort, int, uint, long, ulong, float, double
1770                                 // 
1771                                 if ((expr_type == TypeManager.ushort_type) ||
1772                                     (expr_type == TypeManager.int32_type) ||
1773                                     (expr_type == TypeManager.uint32_type) ||
1774                                     (expr_type == TypeManager.uint64_type) ||
1775                                     (expr_type == TypeManager.int64_type) ||
1776                                     (expr_type == TypeManager.float_type) ||
1777                                     (expr_type == TypeManager.double_type) ||
1778                                     (expr_type == TypeManager.decimal_type))
1779                                         return true;
1780
1781                         } else if (target_type == TypeManager.float_type){
1782                                 //
1783                                 // To float from double
1784                                 //
1785                                 if (expr_type == TypeManager.double_type)
1786                                         return true;
1787                         }       
1788
1789                         return (NarrowingConversion (ec, expr, target_type,Location.Null)) != null;     
1790                 }
1791                 
1792                 static public Expression NarrowingConversion (EmitContext ec, Expression expr,
1793                                                                 Type target_type, Location loc)
1794                 {
1795                         Type expr_type = expr.Type;
1796
1797                         if (target_type == TypeManager.sbyte_type){
1798                                 //
1799                                 // To sbyte from short, int, long, float, double.
1800                                 //
1801                                 if ((expr_type == TypeManager.int32_type) || 
1802                                     (expr_type == TypeManager.int64_type) ||
1803                                     (expr_type == TypeManager.double_type) ||
1804                                     (expr_type == TypeManager.float_type)  ||
1805                                     (expr_type == TypeManager.short_type) ||
1806                                     (expr_type == TypeManager.decimal_type))
1807                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_I1);
1808                                 
1809                         } else if (target_type == TypeManager.byte_type){
1810                                 //
1811                                 // To byte from short, ushort, int, uint, long, ulong, float, double
1812                                 // 
1813                                 if ((expr_type == TypeManager.short_type) ||
1814                                     (expr_type == TypeManager.ushort_type) ||
1815                                     (expr_type == TypeManager.int32_type) ||
1816                                     (expr_type == TypeManager.uint32_type) ||
1817                                     (expr_type == TypeManager.uint64_type) ||
1818                                     (expr_type == TypeManager.int64_type) ||
1819                                     (expr_type == TypeManager.float_type) ||
1820                                     (expr_type == TypeManager.double_type) ||
1821                                     (expr_type == TypeManager.decimal_type))
1822                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_U1);
1823         
1824                         } else if (target_type == TypeManager.short_type){
1825                                 //
1826                                 // To short from int, long, float, double
1827                                 // 
1828                                 if ((expr_type == TypeManager.int32_type) ||
1829                                     (expr_type == TypeManager.int64_type) ||
1830                                     (expr_type == TypeManager.double_type) ||
1831                                     (expr_type == TypeManager.float_type) ||
1832                                     (expr_type == TypeManager.decimal_type))
1833                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_I2);
1834                                         
1835                         } else if (target_type == TypeManager.ushort_type){
1836                                 //
1837                                 // To ushort from int, uint, long, ulong, float, double
1838                                 //
1839                                 if ((expr_type == TypeManager.uint32_type) ||
1840                                     (expr_type == TypeManager.uint64_type) ||
1841                                     (expr_type == TypeManager.int32_type) ||
1842                                     (expr_type == TypeManager.int64_type) ||
1843                                     (expr_type == TypeManager.double_type) ||
1844                                     (expr_type == TypeManager.float_type) ||
1845                                     (expr_type == TypeManager.decimal_type))
1846                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_U2);
1847                                     
1848                         } else if (target_type == TypeManager.int32_type){
1849                                 //
1850                                 // To int from long, float, double
1851                                 //
1852                                 if ((expr_type == TypeManager.int64_type) ||
1853                                     (expr_type == TypeManager.double_type) ||
1854                                     (expr_type == TypeManager.float_type) ||
1855                                     (expr_type == TypeManager.decimal_type))
1856                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_I4);
1857                                         
1858                         } else if (target_type == TypeManager.uint32_type){
1859                                 //
1860                                 // To uint from long, ulong, float, double
1861                                 //
1862                                 if ((expr_type == TypeManager.int64_type) ||
1863                                     (expr_type == TypeManager.uint64_type) ||
1864                                     (expr_type == TypeManager.double_type) ||
1865                                     (expr_type == TypeManager.float_type) ||
1866                                     (expr_type == TypeManager.decimal_type))
1867                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_U4);
1868                                         
1869                         } else if ((target_type == TypeManager.uint64_type) ||
1870                                    (target_type == TypeManager.int64_type)) {
1871                                 //
1872                                 // To long/ulong from float, double
1873                                 //
1874                                 if ((expr_type == TypeManager.double_type) ||
1875                                     (expr_type == TypeManager.float_type) ||
1876                                     (expr_type == TypeManager.decimal_type))
1877                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_I8);
1878                                     
1879                         } else if (target_type == TypeManager.char_type){
1880                                 //
1881                                 // To char from ushort, int, uint, long, ulong, float, double
1882                                 // 
1883                                 if ((expr_type == TypeManager.ushort_type) ||
1884                                     (expr_type == TypeManager.int32_type) ||
1885                                     (expr_type == TypeManager.uint32_type) ||
1886                                     (expr_type == TypeManager.uint64_type) ||
1887                                     (expr_type == TypeManager.int64_type) ||
1888                                     (expr_type == TypeManager.float_type) ||
1889                                     (expr_type == TypeManager.double_type) ||
1890                                     (expr_type == TypeManager.decimal_type))
1891                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_U2);
1892
1893                         } else if (target_type == TypeManager.float_type){
1894                                 //
1895                                 // To float from double
1896                                 //
1897                                 if (expr_type == TypeManager.double_type)
1898                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_R4);
1899                         }       
1900
1901                         TypeCode dest_type = Type.GetTypeCode (target_type);
1902                         TypeCode src_type = Type.GetTypeCode (expr_type);
1903                         Expression e = null;
1904
1905                         // VB.NET Objects can be converted to anything by default
1906                         // unless, that is, an exception at runtime blows it all
1907                         if (src_type == TypeCode.Object) {
1908                                 Expression cast_type = Mono.MonoBASIC.Parser.DecomposeQI(target_type.ToString(), loc);
1909                                 Cast ce = new Cast (cast_type, expr, loc);
1910                                 ce.IsRuntimeCast = true;
1911                                 return ce.Resolve (ec);
1912                         }
1913
1914                         switch (dest_type) {
1915                                 case TypeCode.String:
1916                                         switch (src_type) {
1917                                                 case TypeCode.SByte:                                            
1918                                                 case TypeCode.Byte:
1919                                                         e = RTConversionExpression(ec, "StringType.FromByte", expr, loc);
1920                                                         break;  
1921                                                 case TypeCode.UInt16:
1922                                                 case TypeCode.Int16:
1923                                                         e = RTConversionExpression(ec, "StringType.FromShort", expr, loc);
1924                                                         break;          
1925                                                 case TypeCode.UInt32:                                   
1926                                                 case TypeCode.Int32:
1927                                                         e = RTConversionExpression(ec, "StringType.FromInteger", expr, loc);
1928                                                         break;                                                  
1929                                                 case TypeCode.UInt64:   
1930                                                 case TypeCode.Int64:
1931                                                         e = RTConversionExpression(ec, "StringType.FromLong", expr, loc);
1932                                                         break;                                                  
1933                                                 case TypeCode.Char:
1934                                                         e = RTConversionExpression(ec, "StringType.FromChar", expr, loc);
1935                                                         break;                                                          
1936                                                 case TypeCode.Single:
1937                                                         e = RTConversionExpression(ec, "StringType.FromSingle", expr, loc);
1938                                                         break;          
1939                                                 case TypeCode.Double:
1940                                                         e = RTConversionExpression(ec, "StringType.FromDouble", expr, loc);
1941                                                         break;                                                                                                                                                  
1942                                                 case TypeCode.Boolean:
1943                                                         e = RTConversionExpression(ec, "StringType.FromBoolean", expr, loc);
1944                                                         break;  
1945                                                 case TypeCode.DateTime:
1946                                                         e = RTConversionExpression(ec, "StringType.FromDate", expr, loc);
1947                                                         break;          
1948                                                 case TypeCode.Decimal:
1949                                                         e = RTConversionExpression(ec, "StringType.FromDecimal", expr, loc);
1950                                                         break;          
1951                                                 case TypeCode.Object:
1952                                                         e = RTConversionExpression(ec, "StringType.FromObject", expr, loc);
1953                                                         break;                                                                                                                                                                                                                          
1954                                         }
1955                                         break;
1956                                         
1957                                 case TypeCode.Int32:
1958                                 case TypeCode.UInt32:   
1959                                         switch (src_type) {                                             
1960                                                 case TypeCode.String:                           
1961                                                         e = RTConversionExpression(ec, "IntegerType.FromString", expr, loc);
1962                                                         break;          
1963                                                 case TypeCode.Object:                           
1964                                                         e = RTConversionExpression(ec, "IntegerType.FromObject", expr, loc);
1965                                                         break;                                                                                  
1966                                         }
1967                                         break;  
1968
1969                                 case TypeCode.Int16:
1970                                 case TypeCode.UInt16:   
1971                                         switch (src_type) {                                             
1972                                                 case TypeCode.String:                           
1973                                                         e = RTConversionExpression(ec, "ShortType.FromString", expr, loc);
1974                                                         break;          
1975                                                 case TypeCode.Object:                           
1976                                                         e = RTConversionExpression(ec, "ShortType.FromObject", expr, loc);
1977                                                         break;                                                                                  
1978                                         }
1979                                         break;  
1980                                 case TypeCode.Byte:
1981                                         // Ok, this *is* broken
1982                                         e = RTConversionExpression(ec, "ByteType.FromObject", expr, loc);
1983                                         break;  
1984                                 case TypeCode.DateTime: 
1985                                         switch (src_type) {                                             
1986                                                 case TypeCode.String:                           
1987                                                         e = RTConversionExpression(ec, "DateType.FromString", expr, loc);
1988                                                         break;          
1989                                                 case TypeCode.Object:                           
1990                                                         e = RTConversionExpression(ec, "DateType.FromObject", expr, loc);
1991                                                         break;                                                                                  
1992                                         }
1993                                         break;                                                                                                          
1994                         }
1995                         
1996                         // We must examine separately some types that
1997                         // don't have a TypeCode but are supported 
1998                         // in the runtime
1999                         if (expr_type == typeof(System.String) && target_type == typeof (System.Char[])) {
2000                                 e = RTConversionExpression(ec, "CharArrayType.FromString", expr, loc);
2001                         }
2002                         
2003                         return e;
2004                 }
2005                                                                                                 
2006                 /// <summary>
2007                 ///   Attempts to apply the 'Standard Implicit
2008                 ///   Conversion' rules to the expression 'expr' into
2009                 ///   the 'target_type'.  It returns a new expression
2010                 ///   that can be used in a context that expects a
2011                 ///   'target_type'.
2012                 ///
2013                 ///   This is different from 'ConvertImplicit' in that the
2014                 ///   user defined implicit conversions are excluded. 
2015                 /// </summary>
2016                 static public Expression ConvertImplicitStandard (EmitContext ec, Expression expr,
2017                                                                   Type target_type, Location loc)
2018                 {
2019                         Type expr_type = expr.Type;
2020                         Expression e;
2021
2022                         if (expr_type == target_type)
2023                                 return expr;
2024
2025                         e = ImplicitNumericConversion (ec, expr, target_type, loc);
2026                         if (e != null)
2027                                 return e;
2028
2029                         e = ImplicitReferenceConversion (expr, target_type);
2030                         if (e != null)
2031                                 return e;
2032
2033                         if (expr.Type.IsSubclassOf (TypeManager.enum_type)) {
2034                                 expr_type = TypeManager.EnumToUnderlying (expr.Type);
2035                                 expr = new EmptyCast (expr, expr_type);
2036                                 if (expr_type == target_type)
2037                                         return expr;
2038                                 e = ImplicitNumericConversion (ec, expr, target_type, loc);
2039                                 if (e != null)
2040                                         return e;
2041                         }
2042
2043                         if (ec.InUnsafe) {
2044                                 if (expr_type.IsPointer){
2045                                         if (target_type == TypeManager.void_ptr_type)
2046                                                 return new EmptyCast (expr, target_type);
2047
2048                                         //
2049                                         // yep, comparing pointer types cant be done with
2050                                         // t1 == t2, we have to compare their element types.
2051                                         //
2052                                         if (target_type.IsPointer){
2053                                                 if (target_type.GetElementType()==expr_type.GetElementType())
2054                                                         return expr;
2055                                         }
2056                                 }
2057                                 
2058                                 if (target_type.IsPointer){
2059                                         if (expr is NullLiteral)
2060                                                 return new EmptyCast (expr, target_type);
2061                                 }
2062                         }
2063
2064                         return null;
2065                 }
2066
2067                 /// <summary>
2068                 ///   Attemps to perform an implict constant conversion of the IntConstant
2069                 ///   into a different data type using casts (See Implicit Constant
2070                 ///   Expression Conversions)
2071                 /// </summary>
2072                 static protected Expression TryImplicitIntConversion (Type target_type, IntConstant ic)
2073                 {
2074                         int value = ic.Value;
2075
2076                         //
2077                         // FIXME: This could return constants instead of EmptyCasts
2078                         //
2079                         if (target_type == TypeManager.sbyte_type){
2080                                 if (value >= SByte.MinValue && value <= SByte.MaxValue)
2081                                         return new SByteConstant ((sbyte) value);
2082                         } else if (target_type == TypeManager.byte_type){
2083                                 if (Byte.MinValue >= 0 && value <= Byte.MaxValue)
2084                                         return new ByteConstant ((byte) value);
2085                         } else if (target_type == TypeManager.short_type){
2086                                 if (value >= Int16.MinValue && value <= Int16.MaxValue)
2087                                         return new ShortConstant ((short) value);
2088                         } else if (target_type == TypeManager.ushort_type){
2089                                 if (value >= UInt16.MinValue && value <= UInt16.MaxValue)
2090                                         return new UShortConstant ((ushort) value);
2091                         } else if (target_type == TypeManager.uint32_type){
2092                                 if (value >= 0)
2093                                         return new UIntConstant ((uint) value);
2094                         } else if (target_type == TypeManager.uint64_type){
2095                                 //
2096                                 // we can optimize this case: a positive int32
2097                                 // always fits on a uint64.  But we need an opcode
2098                                 // to do it.
2099                                 //
2100                                 if (value >= 0)
2101                                         return new ULongConstant ((ulong) value);
2102                         }
2103                         
2104                         if (value == 0 && ic is IntLiteral && TypeManager.IsEnumType (target_type)){
2105                                 Type underlying = TypeManager.EnumToUnderlying (target_type);
2106                                 Constant e = (Constant) ic;
2107                                 
2108                                 //
2109                                 // Possibly, we need to create a different 0 literal before passing
2110                                 // to EnumConstant
2111                                 //n
2112                                 if (underlying == TypeManager.int64_type)
2113                                         e = new LongLiteral (0);
2114                                 else if (underlying == TypeManager.uint64_type)
2115                                         e = new ULongLiteral (0);
2116
2117                                 return new EnumConstant (e, target_type);
2118                         }
2119                         return null;
2120                 }
2121
2122                 static public void Error_CannotConvertImplicit (Location loc, Type source, Type target)
2123                 {
2124                         string msg = "Cannot convert implicitly from '"+
2125                                 TypeManager.MonoBASIC_Name (source) + "' to '" +
2126                                 TypeManager.MonoBASIC_Name (target) + "'";
2127
2128                         Report.Error (29, loc, msg);
2129                 }
2130
2131                 /// <summary>
2132                 ///   Attemptes to implicityly convert 'target' into 'type', using
2133                 ///   ConvertImplicit.  If there is no implicit conversion, then
2134                 ///   an error is signaled
2135                 /// </summary>
2136                 static public Expression ConvertImplicitRequired (EmitContext ec, Expression source,
2137                                                                   Type target_type, Location loc)
2138                 {
2139                         Expression e;
2140                         
2141                         e = ConvertImplicit (ec, source, target_type, loc);
2142                         if (e != null)
2143                                 return e;
2144
2145                         if (source is DoubleLiteral && target_type == TypeManager.float_type){
2146                                 Report.Error (664, loc,
2147                                               "Double literal cannot be implicitly converted to " +
2148                                               "float type, use F suffix to create a float literal");
2149                         }
2150
2151                         Error_CannotConvertImplicit (loc, source.Type, target_type);
2152
2153                         return null;
2154                 }
2155
2156                 /// <summary>
2157                 ///   Performs the explicit numeric conversions
2158                 /// </summary>
2159                 static Expression ConvertNumericExplicit (EmitContext ec, Expression expr, Type target_type, Location loc)
2160                 {
2161                         Type expr_type = expr.Type;
2162
2163                         //
2164                         // If we have an enumeration, extract the underlying type,
2165                         // use this during the comparison, but wrap around the original
2166                         // target_type
2167                         //
2168                         Type real_target_type = target_type;
2169
2170                         if (TypeManager.IsEnumType (real_target_type))
2171                                 real_target_type = TypeManager.EnumToUnderlying (real_target_type);
2172
2173                         if (StandardConversionExists (expr, real_target_type)){
2174                                 Expression ce = ConvertImplicitStandard (ec, expr, real_target_type, loc);
2175
2176                                 if (real_target_type != target_type)
2177                                         return new EmptyCast (ce, target_type);
2178                                 return ce;
2179                         }
2180                         
2181                         if (expr_type == TypeManager.sbyte_type){
2182                                 //
2183                                 // From sbyte to byte, ushort, uint, ulong, char
2184                                 //
2185                                 if (real_target_type == TypeManager.byte_type)
2186                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.I1_U1);
2187                                 if (real_target_type == TypeManager.ushort_type)
2188                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.I1_U2);
2189                                 if (real_target_type == TypeManager.uint32_type)
2190                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.I1_U4);
2191                                 if (real_target_type == TypeManager.uint64_type)
2192                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.I1_U8);
2193                                 if (real_target_type == TypeManager.char_type)
2194                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.I1_CH);
2195                         } else if (expr_type == TypeManager.byte_type){
2196                                 //
2197                                 // From byte to sbyte and char
2198                                 //
2199                                 if (real_target_type == TypeManager.sbyte_type)
2200                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.U1_I1);
2201                                 if (real_target_type == TypeManager.char_type)
2202                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.U1_CH);
2203                         } else if (expr_type == TypeManager.short_type){
2204                                 //
2205                                 // From short to sbyte, byte, ushort, uint, ulong, char
2206                                 //
2207                                 if (real_target_type == TypeManager.sbyte_type)
2208                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.I2_I1);
2209                                 if (real_target_type == TypeManager.byte_type)
2210                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.I2_U1);
2211                                 if (real_target_type == TypeManager.ushort_type)
2212                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.I2_U2);
2213                                 if (real_target_type == TypeManager.uint32_type)
2214                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.I2_U4);
2215                                 if (real_target_type == TypeManager.uint64_type)
2216                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.I2_U8);
2217                                 if (real_target_type == TypeManager.char_type)
2218                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.I2_CH);
2219                         } else if (expr_type == TypeManager.ushort_type){
2220                                 //
2221                                 // From ushort to sbyte, byte, short, char
2222                                 //
2223                                 if (real_target_type == TypeManager.sbyte_type)
2224                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.U2_I1);
2225                                 if (real_target_type == TypeManager.byte_type)
2226                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.U2_U1);
2227                                 if (real_target_type == TypeManager.short_type)
2228                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.U2_I2);
2229                                 if (real_target_type == TypeManager.char_type)
2230                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.U2_CH);
2231                         } else if (expr_type == TypeManager.int32_type){
2232                                 //
2233                                 // From int to sbyte, byte, short, ushort, uint, ulong, char
2234                                 //
2235                                 if (real_target_type == TypeManager.sbyte_type)
2236                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.I4_I1);
2237                                 if (real_target_type == TypeManager.byte_type)
2238                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.I4_U1);
2239                                 if (real_target_type == TypeManager.short_type)
2240                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.I4_I2);
2241                                 if (real_target_type == TypeManager.ushort_type)
2242                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.I4_U2);
2243                                 if (real_target_type == TypeManager.uint32_type)
2244                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.I4_U4);
2245                                 if (real_target_type == TypeManager.uint64_type)
2246                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.I4_U8);
2247                                 if (real_target_type == TypeManager.char_type)
2248                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.I4_CH);
2249                         } else if (expr_type == TypeManager.uint32_type){
2250                                 //
2251                                 // From uint to sbyte, byte, short, ushort, int, char
2252                                 //
2253                                 if (real_target_type == TypeManager.sbyte_type)
2254                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.U4_I1);
2255                                 if (real_target_type == TypeManager.byte_type)
2256                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.U4_U1);
2257                                 if (real_target_type == TypeManager.short_type)
2258                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.U4_I2);
2259                                 if (real_target_type == TypeManager.ushort_type)
2260                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.U4_U2);
2261                                 if (real_target_type == TypeManager.int32_type)
2262                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.U4_I4);
2263                                 if (real_target_type == TypeManager.char_type)
2264                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.U4_CH);
2265                         } else if (expr_type == TypeManager.int64_type){
2266                                 //
2267                                 // From long to sbyte, byte, short, ushort, int, uint, ulong, char
2268                                 //
2269                                 if (real_target_type == TypeManager.sbyte_type)
2270                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.I8_I1);
2271                                 if (real_target_type == TypeManager.byte_type)
2272                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.I8_U1);
2273                                 if (real_target_type == TypeManager.short_type)
2274                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.I8_I2);
2275                                 if (real_target_type == TypeManager.ushort_type)
2276                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.I8_U2);
2277                                 if (real_target_type == TypeManager.int32_type)
2278                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.I8_I4);
2279                                 if (real_target_type == TypeManager.uint32_type)
2280                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.I8_U4);
2281                                 if (real_target_type == TypeManager.uint64_type)
2282                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.I8_U8);
2283                                 if (real_target_type == TypeManager.char_type)
2284                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.I8_CH);
2285                         } else if (expr_type == TypeManager.uint64_type){
2286                                 //
2287                                 // From ulong to sbyte, byte, short, ushort, int, uint, long, char
2288                                 //
2289                                 if (real_target_type == TypeManager.sbyte_type)
2290                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.U8_I1);
2291                                 if (real_target_type == TypeManager.byte_type)
2292                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.U8_U1);
2293                                 if (real_target_type == TypeManager.short_type)
2294                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.U8_I2);
2295                                 if (real_target_type == TypeManager.ushort_type)
2296                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.U8_U2);
2297                                 if (real_target_type == TypeManager.int32_type)
2298                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.U8_I4);
2299                                 if (real_target_type == TypeManager.uint32_type)
2300                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.U8_U4);
2301                                 if (real_target_type == TypeManager.int64_type)
2302                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.U8_I8);
2303                                 if (real_target_type == TypeManager.char_type)
2304                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.U8_CH);
2305                         } else if (expr_type == TypeManager.char_type){
2306                                 //
2307                                 // From char to sbyte, byte, short
2308                                 //
2309                                 if (real_target_type == TypeManager.sbyte_type)
2310                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.CH_I1);
2311                                 if (real_target_type == TypeManager.byte_type)
2312                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.CH_U1);
2313                                 if (real_target_type == TypeManager.short_type)
2314                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.CH_I2);
2315                         } else if (expr_type == TypeManager.float_type){
2316                                 //
2317                                 // From float to sbyte, byte, short,
2318                                 // ushort, int, uint, long, ulong, char
2319                                 // or decimal
2320                                 //
2321                                 if (real_target_type == TypeManager.sbyte_type)
2322                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.R4_I1);
2323                                 if (real_target_type == TypeManager.byte_type)
2324                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.R4_U1);
2325                                 if (real_target_type == TypeManager.short_type)
2326                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.R4_I2);
2327                                 if (real_target_type == TypeManager.ushort_type)
2328                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.R4_U2);
2329                                 if (real_target_type == TypeManager.int32_type)
2330                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.R4_I4);
2331                                 if (real_target_type == TypeManager.uint32_type)
2332                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.R4_U4);
2333                                 if (real_target_type == TypeManager.int64_type)
2334                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.R4_I8);
2335                                 if (real_target_type == TypeManager.uint64_type)
2336                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.R4_U8);
2337                                 if (real_target_type == TypeManager.char_type)
2338                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.R4_CH);
2339                         } else if (expr_type == TypeManager.double_type){
2340                                 //
2341                                 // From double to byte, byte, short,
2342                                 // ushort, int, uint, long, ulong,
2343                                 // char, float or decimal
2344                                 //
2345                                 if (real_target_type == TypeManager.sbyte_type)
2346                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.R8_I1);
2347                                 if (real_target_type == TypeManager.byte_type)
2348                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.R8_U1);
2349                                 if (real_target_type == TypeManager.short_type)
2350                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.R8_I2);
2351                                 if (real_target_type == TypeManager.ushort_type)
2352                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.R8_U2);
2353                                 if (real_target_type == TypeManager.int32_type)
2354                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.R8_I4);
2355                                 if (real_target_type == TypeManager.uint32_type)
2356                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.R8_U4);
2357                                 if (real_target_type == TypeManager.int64_type)
2358                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.R8_I8);
2359                                 if (real_target_type == TypeManager.uint64_type)
2360                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.R8_U8);
2361                                 if (real_target_type == TypeManager.char_type)
2362                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.R8_CH);
2363                                 if (real_target_type == TypeManager.float_type)
2364                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.R8_R4);
2365                         } 
2366
2367                         // decimal is taken care of by the op_Explicit methods.
2368
2369                         return null;
2370                 }
2371
2372                 /// <summary>
2373                 ///  Returns whether an explicit reference conversion can be performed
2374                 ///  from source_type to target_type
2375                 /// </summary>
2376                 public static bool ExplicitReferenceConversionExists (Type source_type, Type target_type)
2377                 {
2378                         bool target_is_value_type = target_type.IsValueType;
2379                         
2380                         if (source_type == target_type)
2381                                 return true;
2382                         
2383                         //
2384                         // From object to any reference type
2385                         //
2386                         if (source_type == TypeManager.object_type && !target_is_value_type)
2387                                 return true;
2388                                         
2389                         //
2390                         // From any class S to any class-type T, provided S is a base class of T
2391                         //
2392                         if (target_type.IsSubclassOf (source_type))
2393                                 return true;
2394
2395                         //
2396                         // From any interface type S to any interface T provided S is not derived from T
2397                         //
2398                         if (source_type.IsInterface && target_type.IsInterface){
2399                                 if (!target_type.IsSubclassOf (source_type))
2400                                         return true;
2401                         }
2402                             
2403                         //
2404                         // From any class type S to any interface T, provided S is not sealed
2405                         // and provided S does not implement T.
2406                         //
2407                         if (target_type.IsInterface && !source_type.IsSealed &&
2408                             !TypeManager.ImplementsInterface (source_type, target_type))
2409                                 return true;
2410
2411                         //
2412                         // From any interface-type S to to any class type T, provided T is not
2413                         // sealed, or provided T implements S.
2414                         //
2415                         if (source_type.IsInterface &&
2416                             (!target_type.IsSealed || TypeManager.ImplementsInterface (target_type, source_type)))
2417                                 return true;
2418                         
2419                         
2420                         // From an array type S with an element type Se to an array type T with an 
2421                         // element type Te provided all the following are true:
2422                         //     * S and T differe only in element type, in other words, S and T
2423                         //       have the same number of dimensions.
2424                         //     * Both Se and Te are reference types
2425                         //     * An explicit referenc conversions exist from Se to Te
2426                         //
2427                         if (source_type.IsArray && target_type.IsArray) {
2428                                 if (source_type.GetArrayRank () == target_type.GetArrayRank ()) {
2429                                         
2430                                         Type source_element_type = source_type.GetElementType ();
2431                                         Type target_element_type = target_type.GetElementType ();
2432                                         
2433                                         if (!source_element_type.IsValueType && !target_element_type.IsValueType)
2434                                                 if (ExplicitReferenceConversionExists (source_element_type,
2435                                                                                        target_element_type))
2436                                                         return true;
2437                                 }
2438                         }
2439                         
2440
2441                         // From System.Array to any array-type
2442                         if (source_type == TypeManager.array_type &&
2443                             target_type.IsArray){
2444                                 return true;
2445                         }
2446
2447                         //
2448                         // From System delegate to any delegate-type
2449                         //
2450                         if (source_type == TypeManager.delegate_type &&
2451                             target_type.IsSubclassOf (TypeManager.delegate_type))
2452                                 return true;
2453
2454                         //
2455                         // From ICloneable to Array or Delegate types
2456                         //
2457                         if (source_type == TypeManager.icloneable_type &&
2458                             (target_type == TypeManager.array_type ||
2459                              target_type == TypeManager.delegate_type))
2460                                 return true;
2461                         
2462                         return false;
2463                 }
2464
2465                 /// <summary>
2466                 ///   Implements Explicit Reference conversions
2467                 /// </summary>
2468                 static Expression ConvertReferenceExplicit (Expression source, Type target_type)
2469                 {
2470                         Type source_type = source.Type;
2471                         bool target_is_value_type = target_type.IsValueType;
2472
2473                         //
2474                         // From object to any reference type
2475                         //
2476                         if (source_type == TypeManager.object_type && !target_is_value_type)
2477                                 return new ClassCast (source, target_type);
2478
2479
2480                         //
2481                         // From any class S to any class-type T, provided S is a base class of T
2482                         //
2483                         if (target_type.IsSubclassOf (source_type))
2484                                 return new ClassCast (source, target_type);
2485
2486                         //
2487                         // From any interface type S to any interface T provided S is not derived from T
2488                         //
2489                         if (source_type.IsInterface && target_type.IsInterface){
2490                                 if (TypeManager.ImplementsInterface (source_type, target_type))
2491                                         return null;
2492                                 else
2493                                         return new ClassCast (source, target_type);
2494                         }
2495                             
2496                         //
2497                         // From any class type S to any interface T, provides S is not sealed
2498                         // and provided S does not implement T.
2499                         //
2500                         if (target_type.IsInterface && !source_type.IsSealed) {
2501                                 if (TypeManager.ImplementsInterface (source_type, target_type))
2502                                         return null;
2503                                 else
2504                                         return new ClassCast (source, target_type);
2505                                 
2506                         }
2507
2508                         //
2509                         // From any interface-type S to to any class type T, provided T is not
2510                         // sealed, or provided T implements S.
2511                         //
2512                         if (source_type.IsInterface) {
2513                                 if (!target_type.IsSealed || TypeManager.ImplementsInterface (target_type, source_type))
2514                                         return new ClassCast (source, target_type);
2515                                 else
2516                                         return null;
2517                         }
2518                         
2519                         // From an array type S with an element type Se to an array type T with an 
2520                         // element type Te provided all the following are true:
2521                         //     * S and T differe only in element type, in other words, S and T
2522                         //       have the same number of dimensions.
2523                         //     * Both Se and Te are reference types
2524                         //     * An explicit referenc conversions exist from Se to Te
2525                         //
2526                         if (source_type.IsArray && target_type.IsArray) {
2527                                 if (source_type.GetArrayRank () == target_type.GetArrayRank ()) {
2528                                         
2529                                         Type source_element_type = source_type.GetElementType ();
2530                                         Type target_element_type = target_type.GetElementType ();
2531                                         
2532                                         if (!source_element_type.IsValueType && !target_element_type.IsValueType)
2533                                                 if (ExplicitReferenceConversionExists (source_element_type,
2534                                                                                        target_element_type))
2535                                                         return new ClassCast (source, target_type);
2536                                 }
2537                         }
2538                         
2539
2540                         // From System.Array to any array-type
2541                         if (source_type == TypeManager.array_type &&
2542                             target_type.IsArray) {
2543                                 return new ClassCast (source, target_type);
2544                         }
2545
2546                         //
2547                         // From System delegate to any delegate-type
2548                         //
2549                         if (source_type == TypeManager.delegate_type &&
2550                             target_type.IsSubclassOf (TypeManager.delegate_type))
2551                                 return new ClassCast (source, target_type);
2552
2553                         //
2554                         // From ICloneable to Array or Delegate types
2555                         //
2556                         if (source_type == TypeManager.icloneable_type &&
2557                             (target_type == TypeManager.array_type ||
2558                              target_type == TypeManager.delegate_type))
2559                                 return new ClassCast (source, target_type);
2560                         
2561                         return null;
2562                 }
2563                 
2564                 /// <summary>
2565                 ///   Performs an explicit conversion of the expression 'expr' whose
2566                 ///   type is expr.Type to 'target_type'.
2567                 /// </summary>
2568                 static public Expression ConvertExplicit (EmitContext ec, Expression expr,
2569                                                           Type target_type, bool runtimeconv, Location loc)
2570                 {
2571                         Type expr_type = expr.Type;
2572                         Expression ne = ConvertImplicitStandard (ec, expr, target_type, loc);
2573
2574                         if (ne != null)
2575                                 return ne;
2576
2577                         ne = ConvertNumericExplicit (ec, expr, target_type, loc);
2578                         if (ne != null)
2579                                 return ne;
2580
2581                         //
2582                         // Unboxing conversion.
2583                         //
2584                         if (expr_type == TypeManager.object_type && target_type.IsValueType)
2585                                 return new UnboxCast (expr, target_type);
2586
2587                         //
2588                         // Enum types
2589                         //
2590                         if (expr_type.IsSubclassOf (TypeManager.enum_type)) {
2591                                 Expression e;
2592
2593                                 //
2594                                 // FIXME: Is there any reason we should have EnumConstant
2595                                 // dealt with here instead of just using always the
2596                                 // UnderlyingSystemType to wrap the type?
2597                                 //
2598                                 if (expr is EnumConstant)
2599                                         e = ((EnumConstant) expr).Child;
2600                                 else {
2601                                         e = new EmptyCast (expr, TypeManager.EnumToUnderlying (expr_type));
2602                                 }
2603                                 
2604                                 Expression t = ConvertImplicit (ec, e, target_type, loc);
2605                                 if (t != null)
2606                                         return t;
2607                                 
2608                                 t = ConvertNumericExplicit (ec, e, target_type, loc);
2609                                 if (t != null)
2610                                         return t;
2611                                 
2612                                 t = NarrowingConversion (ec, e, target_type, loc);
2613                                 if (t != null)
2614                                         return t;       
2615                                                                 
2616                                 Error_CannotConvertType (loc, expr_type, target_type);
2617                                 return null;
2618                         }
2619                         
2620                         ne = ConvertReferenceExplicit (expr, target_type);
2621                         if (ne != null)
2622                                 return ne;
2623
2624                         if (ec.InUnsafe){
2625                                 if (target_type.IsPointer){
2626                                         if (expr_type.IsPointer)
2627                                                 return new EmptyCast (expr, target_type);
2628                                         
2629                                         if (expr_type == TypeManager.sbyte_type ||
2630                                             expr_type == TypeManager.byte_type ||
2631                                             expr_type == TypeManager.short_type ||
2632                                             expr_type == TypeManager.ushort_type ||
2633                                             expr_type == TypeManager.int32_type ||
2634                                             expr_type == TypeManager.uint32_type ||
2635                                             expr_type == TypeManager.uint64_type ||
2636                                             expr_type == TypeManager.int64_type)
2637                                                 return new OpcodeCast (expr, target_type, OpCodes.Conv_U);
2638                                 }
2639                                 if (expr_type.IsPointer){
2640                                         if (target_type == TypeManager.sbyte_type ||
2641                                             target_type == TypeManager.byte_type ||
2642                                             target_type == TypeManager.short_type ||
2643                                             target_type == TypeManager.ushort_type ||
2644                                             target_type == TypeManager.int32_type ||
2645                                             target_type == TypeManager.uint32_type ||
2646                                             target_type == TypeManager.uint64_type ||
2647                                             target_type == TypeManager.int64_type){
2648                                                 Expression e = new EmptyCast (expr, TypeManager.uint32_type);
2649                                                 Expression ci, ce;
2650
2651                                                 ci = ConvertImplicitStandard (ec, e, target_type, loc);
2652
2653                                                 if (ci != null)
2654                                                         return ci;
2655
2656                                                 ce = ConvertNumericExplicit (ec, e, target_type, loc);
2657                                                 if (ce != null)
2658                                                         return ce;
2659                                                 //
2660                                                 // We should always be able to go from an uint32
2661                                                 // implicitly or explicitly to the other integral
2662                                                 // types
2663                                                 //
2664                                                 throw new Exception ("Internal compiler error");
2665                                         }
2666                                 }
2667                         }
2668                         
2669                         ne = ExplicitUserConversion (ec, expr, target_type, loc);
2670                         if (ne != null)
2671                                 return ne;
2672
2673                         if (!(runtimeconv))     {
2674                                 ne = NarrowingConversion (ec, expr, target_type, loc);
2675                                 if (ne != null)
2676                                         return ne;
2677                                 
2678                                 Error_CannotConvertType (loc, expr_type, target_type);
2679                         }
2680                         return null;
2681                 }
2682
2683                 /// <summary>
2684                 ///   Same as ConvertExplicit, only it doesn't include user defined conversions
2685                 /// </summary>
2686                 static public Expression ConvertExplicitStandard (EmitContext ec, Expression expr,
2687                                                                   Type target_type, Location l)
2688                 {
2689                         Expression ne = ConvertImplicitStandard (ec, expr, target_type, l);
2690
2691                         if (ne != null)
2692                                 return ne;
2693
2694                         ne = ConvertNumericExplicit (ec, expr, target_type, l);
2695                         if (ne != null)
2696                                 return ne;
2697
2698                         ne = ConvertReferenceExplicit (expr, target_type);
2699                         if (ne != null)
2700                                 return ne;
2701
2702                         ne = NarrowingConversion (ec, expr, target_type, l);
2703                         if (ne != null)
2704                                 return ne;                              
2705
2706                         Error_CannotConvertType (l, expr.Type, target_type);
2707                         return null;
2708                 }
2709
2710                 static string ExprClassName (ExprClass c)
2711                 {
2712                         switch (c){
2713                         case ExprClass.Invalid:
2714                                 return "Invalid";
2715                         case ExprClass.Value:
2716                                 return "value";
2717                         case ExprClass.Variable:
2718                                 return "variable";
2719                         case ExprClass.Namespace:
2720                                 return "namespace";
2721                         case ExprClass.Type:
2722                                 return "type";
2723                         case ExprClass.MethodGroup:
2724                                 return "method group";
2725                         case ExprClass.PropertyAccess:
2726                                 return "property access";
2727                         case ExprClass.EventAccess:
2728                                 return "event access";
2729                         case ExprClass.IndexerAccess:
2730                                 return "indexer access";
2731                         case ExprClass.Nothing:
2732                                 return "null";
2733                         }
2734                         throw new Exception ("Should not happen");
2735                 }
2736                 
2737                 /// <summary>
2738                 ///   Reports that we were expecting 'expr' to be of class 'expected'
2739                 /// </summary>
2740                 public void Error118 (string expected)
2741                 {
2742                         string kind = "Unknown";
2743                         
2744                         kind = ExprClassName (eclass);
2745
2746                         Error (118, "Expression denotes a '" + kind +
2747                                "' where a '" + expected + "' was expected");
2748                 }
2749
2750                 public void Error118 (ResolveFlags flags)
2751                 {
2752                         ArrayList valid = new ArrayList (10);
2753
2754                         if ((flags & ResolveFlags.VariableOrValue) != 0) {
2755                                 valid.Add ("variable");
2756                                 valid.Add ("value");
2757                         }
2758
2759                         if ((flags & ResolveFlags.Type) != 0)
2760                                 valid.Add ("type");
2761
2762                         if ((flags & ResolveFlags.MethodGroup) != 0)
2763                                 valid.Add ("method group");
2764
2765                         if ((flags & ResolveFlags.SimpleName) != 0)
2766                                 valid.Add ("simple name");
2767
2768                         if (valid.Count == 0)
2769                                 valid.Add ("unknown");
2770
2771                         StringBuilder sb = new StringBuilder ();
2772                         for (int i = 0; i < valid.Count; i++) {
2773                                 if (i > 0)
2774                                         sb.Append (", ");
2775                                 else if (i == valid.Count)
2776                                         sb.Append (" or ");
2777                                 sb.Append (valid [i]);
2778                         }
2779
2780                         string kind = ExprClassName (eclass);
2781
2782                         Error (119, "Expression denotes a '" + kind + "' where " +
2783                                "a '" + sb.ToString () + "' was expected");
2784                 }
2785                 
2786                 static void Error_ConstantValueCannotBeConverted (Location l, string val, Type t)
2787                 {
2788                         Report.Error (31, l, "Constant value '" + val + "' cannot be converted to " +
2789                                       TypeManager.MonoBASIC_Name (t));
2790                 }
2791
2792                 public static void UnsafeError (Location loc)
2793                 {
2794                         Report.Error (214, loc, "Pointers may only be used in an unsafe context");
2795                 }
2796                 
2797                 /// <summary>
2798                 ///   Converts the IntConstant, UIntConstant, LongConstant or
2799                 ///   ULongConstant into the integral target_type.   Notice
2800                 ///   that we do not return an 'Expression' we do return
2801                 ///   a boxed integral type.
2802                 ///
2803                 ///   FIXME: Since I added the new constants, we need to
2804                 ///   also support conversions from CharConstant, ByteConstant,
2805                 ///   SByteConstant, UShortConstant, ShortConstant
2806                 ///
2807                 ///   This is used by the switch statement, so the domain
2808                 ///   of work is restricted to the literals above, and the
2809                 ///   targets are int32, uint32, char, byte, sbyte, ushort,
2810                 ///   short, uint64 and int64
2811                 /// </summary>
2812                 public static object ConvertIntLiteral (Constant c, Type target_type, Location loc)
2813                 {
2814                         string s = "";
2815
2816                         if (c.Type == target_type)
2817                                 return ((Constant) c).GetValue ();
2818
2819                         //
2820                         // Make into one of the literals we handle, we dont really care
2821                         // about this value as we will just return a few limited types
2822                         // 
2823                         if (c is EnumConstant)
2824                                 c = ((EnumConstant)c).WidenToCompilerConstant ();
2825
2826                         if (c is IntConstant){
2827                                 int v = ((IntConstant) c).Value;
2828                                 
2829                                 if (target_type == TypeManager.uint32_type){
2830                                         if (v >= 0)
2831                                                 return (uint) v;
2832                                 } else if (target_type == TypeManager.char_type){
2833                                         if (v >= Char.MinValue && v <= Char.MaxValue)
2834                                                 return (char) v;
2835                                 } else if (target_type == TypeManager.byte_type){
2836                                         if (v >= Byte.MinValue && v <= Byte.MaxValue)
2837                                                 return (byte) v;
2838                                 } else if (target_type == TypeManager.sbyte_type){
2839                                         if (v >= SByte.MinValue && v <= SByte.MaxValue)
2840                                                 return (sbyte) v;
2841                                 } else if (target_type == TypeManager.short_type){
2842                                         if (v >= Int16.MinValue && v <= UInt16.MaxValue)
2843                                                 return (short) v;
2844                                 } else if (target_type == TypeManager.ushort_type){
2845                                         if (v >= UInt16.MinValue && v <= UInt16.MaxValue)
2846                                                 return (ushort) v;
2847                                 } else if (target_type == TypeManager.int64_type)
2848                                         return (long) v;
2849                                 else if (target_type == TypeManager.uint64_type){
2850                                         if (v > 0)
2851                                                 return (ulong) v;
2852                                 }
2853
2854                                 s = v.ToString ();
2855                         } else if (c is UIntConstant){
2856                                 uint v = ((UIntConstant) c).Value;
2857
2858                                 if (target_type == TypeManager.int32_type){
2859                                         if (v <= Int32.MaxValue)
2860                                                 return (int) v;
2861                                 } else if (target_type == TypeManager.char_type){
2862                                         if (v >= Char.MinValue && v <= Char.MaxValue)
2863                                                 return (char) v;
2864                                 } else if (target_type == TypeManager.byte_type){
2865                                         if (v <= Byte.MaxValue)
2866                                                 return (byte) v;
2867                                 } else if (target_type == TypeManager.sbyte_type){
2868                                         if (v <= SByte.MaxValue)
2869                                                 return (sbyte) v;
2870                                 } else if (target_type == TypeManager.short_type){
2871                                         if (v <= UInt16.MaxValue)
2872                                                 return (short) v;
2873                                 } else if (target_type == TypeManager.ushort_type){
2874                                         if (v <= UInt16.MaxValue)
2875                                                 return (ushort) v;
2876                                 } else if (target_type == TypeManager.int64_type)
2877                                         return (long) v;
2878                                 else if (target_type == TypeManager.uint64_type)
2879                                         return (ulong) v;
2880                                 s = v.ToString ();
2881                         } else if (c is LongConstant){ 
2882                                 long v = ((LongConstant) c).Value;
2883
2884                                 if (target_type == TypeManager.int32_type){
2885                                         if (v >= UInt32.MinValue && v <= UInt32.MaxValue)
2886                                                 return (int) v;
2887                                 } else if (target_type == TypeManager.uint32_type){
2888                                         if (v >= 0 && v <= UInt32.MaxValue)
2889                                                 return (uint) v;
2890                                 } else if (target_type == TypeManager.char_type){
2891                                         if (v >= Char.MinValue && v <= Char.MaxValue)
2892                                                 return (char) v;
2893                                 } else if (target_type == TypeManager.byte_type){
2894                                         if (v >= Byte.MinValue && v <= Byte.MaxValue)
2895                                                 return (byte) v;
2896                                 } else if (target_type == TypeManager.sbyte_type){
2897                                         if (v >= SByte.MinValue && v <= SByte.MaxValue)
2898                                                 return (sbyte) v;
2899                                 } else if (target_type == TypeManager.short_type){
2900                                         if (v >= Int16.MinValue && v <= UInt16.MaxValue)
2901                                                 return (short) v;
2902                                 } else if (target_type == TypeManager.ushort_type){
2903                                         if (v >= UInt16.MinValue && v <= UInt16.MaxValue)
2904                                                 return (ushort) v;
2905                                 } else if (target_type == TypeManager.uint64_type){
2906                                         if (v > 0)
2907                                                 return (ulong) v;
2908                                 }
2909                                 s = v.ToString ();
2910                         } else if (c is ULongConstant){
2911                                 ulong v = ((ULongConstant) c).Value;
2912
2913                                 if (target_type == TypeManager.int32_type){
2914                                         if (v <= Int32.MaxValue)
2915                                                 return (int) v;
2916                                 } else if (target_type == TypeManager.uint32_type){
2917                                         if (v <= UInt32.MaxValue)
2918                                                 return (uint) v;
2919                                 } else if (target_type == TypeManager.char_type){
2920                                         if (v >= Char.MinValue && v <= Char.MaxValue)
2921                                                 return (char) v;
2922                                 } else if (target_type == TypeManager.byte_type){
2923                                         if (v >= Byte.MinValue && v <= Byte.MaxValue)
2924                                                 return (byte) v;
2925                                 } else if (target_type == TypeManager.sbyte_type){
2926                                         if (v <= (int) SByte.MaxValue)
2927                                                 return (sbyte) v;
2928                                 } else if (target_type == TypeManager.short_type){
2929                                         if (v <= UInt16.MaxValue)
2930                                                 return (short) v;
2931                                 } else if (target_type == TypeManager.ushort_type){
2932                                         if (v <= UInt16.MaxValue)
2933                                                 return (ushort) v;
2934                                 } else if (target_type == TypeManager.int64_type){
2935                                         if (v <= Int64.MaxValue)
2936                                                 return (long) v;
2937                                 }
2938                                 s = v.ToString ();
2939                         } else if (c is ByteConstant){
2940                                 byte v = ((ByteConstant) c).Value;
2941                                 
2942                                 if (target_type == TypeManager.int32_type)
2943                                         return (int) v;
2944                                 else if (target_type == TypeManager.uint32_type)
2945                                         return (uint) v;
2946                                 else if (target_type == TypeManager.char_type)
2947                                         return (char) v;
2948                                 else if (target_type == TypeManager.sbyte_type){
2949                                         if (v <= SByte.MaxValue)
2950                                                 return (sbyte) v;
2951                                 } else if (target_type == TypeManager.short_type)
2952                                         return (short) v;
2953                                 else if (target_type == TypeManager.ushort_type)
2954                                         return (ushort) v;
2955                                 else if (target_type == TypeManager.int64_type)
2956                                         return (long) v;
2957                                 else if (target_type == TypeManager.uint64_type)
2958                                         return (ulong) v;
2959                                 s = v.ToString ();
2960                         } else if (c is SByteConstant){
2961                                 sbyte v = ((SByteConstant) c).Value;
2962                                 
2963                                 if (target_type == TypeManager.int32_type)
2964                                         return (int) v;
2965                                 else if (target_type == TypeManager.uint32_type){
2966                                         if (v >= 0)
2967                                                 return (uint) v;
2968                                 } else if (target_type == TypeManager.char_type){
2969                                         if (v >= 0)
2970                                                 return (char) v;
2971                                 } else if (target_type == TypeManager.byte_type){
2972                                         if (v >= 0)
2973                                                 return (byte) v;
2974                                 } else if (target_type == TypeManager.short_type)
2975                                         return (short) v;
2976                                 else if (target_type == TypeManager.ushort_type){
2977                                         if (v >= 0)
2978                                                 return (ushort) v;
2979                                 } else if (target_type == TypeManager.int64_type)
2980                                         return (long) v;
2981                                 else if (target_type == TypeManager.uint64_type){
2982                                         if (v >= 0)
2983                                                 return (ulong) v;
2984                                 }
2985                                 s = v.ToString ();
2986                         } else if (c is ShortConstant){
2987                                 short v = ((ShortConstant) c).Value;
2988                                 
2989                                 if (target_type == TypeManager.int32_type){
2990                                         return (int) v;
2991                                 } else if (target_type == TypeManager.uint32_type){
2992                                         if (v >= 0)
2993                                                 return (uint) v;
2994                                 } else if (target_type == TypeManager.char_type){
2995                                         if (v >= 0)
2996                                                 return (char) v;
2997                                 } else if (target_type == TypeManager.byte_type){
2998                                         if (v >= Byte.MinValue && v <= Byte.MaxValue)
2999                                                 return (byte) v;
3000                                 } else if (target_type == TypeManager.sbyte_type){
3001                                         if (v >= SByte.MinValue && v <= SByte.MaxValue)
3002                                                 return (sbyte) v;
3003                                 } else if (target_type == TypeManager.ushort_type){
3004                                         if (v >= 0)
3005                                                 return (ushort) v;
3006                                 } else if (target_type == TypeManager.int64_type)
3007                                         return (long) v;
3008                                 else if (target_type == TypeManager.uint64_type)
3009                                         return (ulong) v;
3010
3011                                 s = v.ToString ();
3012                         } else if (c is UShortConstant){
3013                                 ushort v = ((UShortConstant) c).Value;
3014                                 
3015                                 if (target_type == TypeManager.int32_type)
3016                                         return (int) v;
3017                                 else if (target_type == TypeManager.uint32_type)
3018                                         return (uint) v;
3019                                 else if (target_type == TypeManager.char_type){
3020                                         if (v >= Char.MinValue && v <= Char.MaxValue)
3021                                                 return (char) v;
3022                                 } else if (target_type == TypeManager.byte_type){
3023                                         if (v >= Byte.MinValue && v <= Byte.MaxValue)
3024                                                 return (byte) v;
3025                                 } else if (target_type == TypeManager.sbyte_type){
3026                                         if (v <= SByte.MaxValue)
3027                                                 return (byte) v;
3028                                 } else if (target_type == TypeManager.short_type){
3029                                         if (v <= Int16.MaxValue)
3030                                                 return (short) v;
3031                                 } else if (target_type == TypeManager.int64_type)
3032                                         return (long) v;
3033                                 else if (target_type == TypeManager.uint64_type)
3034                                         return (ulong) v;
3035
3036                                 s = v.ToString ();
3037                         } else if (c is CharConstant){
3038                                 char v = ((CharConstant) c).Value;
3039                                 
3040                                 if (target_type == TypeManager.int32_type)
3041                                         return (int) v;
3042                                 else if (target_type == TypeManager.uint32_type)
3043                                         return (uint) v;
3044                                 else if (target_type == TypeManager.byte_type){
3045                                         if (v >= Byte.MinValue && v <= Byte.MaxValue)
3046                                                 return (byte) v;
3047                                 } else if (target_type == TypeManager.sbyte_type){
3048                                         if (v <= SByte.MaxValue)
3049                                                 return (sbyte) v;
3050                                 } else if (target_type == TypeManager.short_type){
3051                                         if (v <= Int16.MaxValue)
3052                                                 return (short) v;
3053                                 } else if (target_type == TypeManager.ushort_type)
3054                                         return (short) v;
3055                                 else if (target_type == TypeManager.int64_type)
3056                                         return (long) v;
3057                                 else if (target_type == TypeManager.uint64_type)
3058                                         return (ulong) v;
3059
3060                                 s = v.ToString ();
3061                         }
3062                         Error_ConstantValueCannotBeConverted (loc, s, target_type);
3063                         return null;
3064                 }
3065
3066                 //
3067                 // Load the object from the pointer.  
3068                 //
3069                 public static void LoadFromPtr (ILGenerator ig, Type t)
3070                 {
3071                         if (t == TypeManager.int32_type)
3072                                 ig.Emit (OpCodes.Ldind_I4);
3073                         else if (t == TypeManager.uint32_type)
3074                                 ig.Emit (OpCodes.Ldind_U4);
3075                         else if (t == TypeManager.short_type)
3076                                 ig.Emit (OpCodes.Ldind_I2);
3077                         else if (t == TypeManager.ushort_type)
3078                                 ig.Emit (OpCodes.Ldind_U2);
3079                         else if (t == TypeManager.char_type)
3080                                 ig.Emit (OpCodes.Ldind_U2);
3081                         else if (t == TypeManager.byte_type)
3082                                 ig.Emit (OpCodes.Ldind_U1);
3083                         else if (t == TypeManager.sbyte_type)
3084                                 ig.Emit (OpCodes.Ldind_I1);
3085                         else if (t == TypeManager.uint64_type)
3086                                 ig.Emit (OpCodes.Ldind_I8);
3087                         else if (t == TypeManager.int64_type)
3088                                 ig.Emit (OpCodes.Ldind_I8);
3089                         else if (t == TypeManager.float_type)
3090                                 ig.Emit (OpCodes.Ldind_R4);
3091                         else if (t == TypeManager.double_type)
3092                                 ig.Emit (OpCodes.Ldind_R8);
3093                         else if (t == TypeManager.bool_type)
3094                                 ig.Emit (OpCodes.Ldind_I1);
3095                         else if (t == TypeManager.intptr_type)
3096                                 ig.Emit (OpCodes.Ldind_I);
3097                         else if (TypeManager.IsEnumType (t)) {
3098                                 if (t == TypeManager.enum_type)
3099                                         ig.Emit (OpCodes.Ldind_Ref);
3100                                 else
3101                                         LoadFromPtr (ig, TypeManager.EnumToUnderlying (t));
3102                         } else if (t.IsValueType)
3103                                 ig.Emit (OpCodes.Ldobj, t);
3104                         else
3105                                 ig.Emit (OpCodes.Ldind_Ref);
3106                 }
3107
3108                 //
3109                 // The stack contains the pointer and the value of type 'type'
3110                 //
3111                 public static void StoreFromPtr (ILGenerator ig, Type type)
3112                 {
3113                         if (TypeManager.IsEnumType (type))
3114                                 type = TypeManager.EnumToUnderlying (type);
3115                         if (type == TypeManager.int32_type || type == TypeManager.uint32_type)
3116                                 ig.Emit (OpCodes.Stind_I4);
3117                         else if (type == TypeManager.int64_type || type == TypeManager.uint64_type)
3118                                 ig.Emit (OpCodes.Stind_I8);
3119                         else if (type == TypeManager.char_type || type == TypeManager.short_type ||
3120                                  type == TypeManager.ushort_type)
3121                                 ig.Emit (OpCodes.Stind_I2);
3122                         else if (type == TypeManager.float_type)
3123                                 ig.Emit (OpCodes.Stind_R4);
3124                         else if (type == TypeManager.double_type)
3125                                 ig.Emit (OpCodes.Stind_R8);
3126                         else if (type == TypeManager.byte_type || type == TypeManager.sbyte_type ||
3127                                  type == TypeManager.bool_type)
3128                                 ig.Emit (OpCodes.Stind_I1);
3129                         else if (type == TypeManager.intptr_type)
3130                                 ig.Emit (OpCodes.Stind_I);
3131                         else if (type.IsValueType)
3132                                 ig.Emit (OpCodes.Stobj, type);
3133                         else
3134                                 ig.Emit (OpCodes.Stind_Ref);
3135                 }
3136                 
3137                 //
3138                 // Returns the size of type 't' if known, otherwise, 0
3139                 //
3140                 public static int GetTypeSize (Type t)
3141                 {
3142                         t = TypeManager.TypeToCoreType (t);
3143                         if (t == TypeManager.int32_type ||
3144                             t == TypeManager.uint32_type ||
3145                             t == TypeManager.float_type)
3146                                 return 4;
3147                         else if (t == TypeManager.int64_type ||
3148                                  t == TypeManager.uint64_type ||
3149                                  t == TypeManager.double_type)
3150                                 return 8;
3151                         else if (t == TypeManager.byte_type ||
3152                                  t == TypeManager.sbyte_type ||
3153                                  t == TypeManager.bool_type)    
3154                                 return 1;
3155                         else if (t == TypeManager.short_type ||
3156                                  t == TypeManager.char_type ||
3157                                  t == TypeManager.ushort_type)
3158                                 return 2;
3159                         else if (t == TypeManager.decimal_type)
3160                                 return 16;
3161                         else
3162                                 return 0;
3163                 }
3164
3165                 //
3166                 // Default implementation of IAssignMethod.CacheTemporaries
3167                 //
3168                 public void CacheTemporaries (EmitContext ec)
3169                 {
3170                 }
3171
3172                 static void Error_NegativeArrayIndex (Location loc)
3173                 {
3174                         Report.Error (284, loc, "Can not create array with a negative size");
3175                 }
3176                 
3177                 //
3178                 // Converts 'source' to an int, uint, long or ulong.
3179                 //
3180                 public Expression ExpressionToArrayArgument (EmitContext ec, Expression source, Location loc)
3181                 {
3182                         Expression target;
3183                         
3184                         bool old_checked = ec.CheckState;
3185                         ec.CheckState = true;
3186                         
3187                         target = ConvertImplicit (ec, source, TypeManager.int32_type, loc);
3188                         if (target == null){
3189                                 target = ConvertImplicit (ec, source, TypeManager.uint32_type, loc);
3190                                 if (target == null){
3191                                         target = ConvertImplicit (ec, source, TypeManager.int64_type, loc);
3192                                         if (target == null){
3193                                                 target = ConvertImplicit (ec, source, TypeManager.uint64_type, loc);
3194                                                 if (target == null)
3195                                                         Expression.Error_CannotConvertImplicit (loc, source.Type, TypeManager.int32_type);
3196                                         }
3197                                 }
3198                         } 
3199                         ec.CheckState = old_checked;
3200
3201                         //
3202                         // Only positive constants are allowed at compile time
3203                         //
3204                         if (target is Constant){
3205                                 if (target is IntConstant){
3206                                         if (((IntConstant) target).Value < 0){
3207                                                 Error_NegativeArrayIndex (loc);
3208                                                 return null;
3209                                         }
3210                                 }
3211
3212                                 if (target is LongConstant){
3213                                         if (((LongConstant) target).Value < 0){
3214                                                 Error_NegativeArrayIndex (loc);
3215                                                 return null;
3216                                         }
3217                                 }
3218                                 
3219                         }
3220
3221                         return target;
3222                 }
3223                 
3224         }
3225
3226         /// <summary>
3227         ///   This is just a base class for expressions that can
3228         ///   appear on statements (invocations, object creation,
3229         ///   assignments, post/pre increment and decrement).  The idea
3230         ///   being that they would support an extra Emition interface that
3231         ///   does not leave a result on the stack.
3232         /// </summary>
3233         public abstract class ExpressionStatement : Expression {
3234
3235                 /// <summary>
3236                 ///   Requests the expression to be emitted in a 'statement'
3237                 ///   context.  This means that no new value is left on the
3238                 ///   stack after invoking this method (constrasted with
3239                 ///   Emit that will always leave a value on the stack).
3240                 /// </summary>
3241                 public abstract void EmitStatement (EmitContext ec);
3242         }
3243
3244         /// <summary>
3245         ///   This kind of cast is used to encapsulate the child
3246         ///   whose type is child.Type into an expression that is
3247         ///   reported to return "return_type".  This is used to encapsulate
3248         ///   expressions which have compatible types, but need to be dealt
3249         ///   at higher levels with.
3250         ///
3251         ///   For example, a "byte" expression could be encapsulated in one
3252         ///   of these as an "unsigned int".  The type for the expression
3253         ///   would be "unsigned int".
3254         ///
3255         /// </summary>
3256         public class EmptyCast : Expression {
3257                 protected Expression child;
3258
3259                 public EmptyCast (Expression child, Type return_type)
3260                 {
3261                         eclass = child.eclass;
3262                         type = return_type;
3263                         this.child = child;
3264                 }
3265
3266                 public override Expression DoResolve (EmitContext ec)
3267                 {
3268                         // This should never be invoked, we are born in fully
3269                         // initialized state.
3270
3271                         return this;
3272                 }
3273
3274                 public override void Emit (EmitContext ec)
3275                 {
3276                         child.Emit (ec);
3277                 }
3278         }
3279
3280         /// <summary>
3281         ///  This class is used to wrap literals which belong inside Enums
3282         /// </summary>
3283         public class EnumConstant : Constant {
3284                 public Constant Child;
3285
3286                 public EnumConstant (Constant child, Type enum_type)
3287                 {
3288                         eclass = child.eclass;
3289                         this.Child = child;
3290                         type = enum_type;
3291                 }
3292                 
3293                 public override Expression DoResolve (EmitContext ec)
3294                 {
3295                         // This should never be invoked, we are born in fully
3296                         // initialized state.
3297
3298                         return this;
3299                 }
3300
3301                 public override void Emit (EmitContext ec)
3302                 {
3303                         Child.Emit (ec);
3304                 }
3305
3306                 public override object GetValue ()
3307                 {
3308                         return Child.GetValue ();
3309                 }
3310
3311                 //
3312                 // Converts from one of the valid underlying types for an enumeration
3313                 // (int32, uint32, int64, uint64, short, ushort, byte, sbyte) to
3314                 // one of the internal compiler literals: Int/UInt/Long/ULong Literals.
3315                 //
3316                 public Constant WidenToCompilerConstant ()
3317                 {
3318                         Type t = TypeManager.EnumToUnderlying (Child.Type);
3319                         object v = ((Constant) Child).GetValue ();;
3320                         
3321                         if (t == TypeManager.int32_type)
3322                                 return new IntConstant ((int) v);
3323                         if (t == TypeManager.uint32_type)
3324                                 return new UIntConstant ((uint) v);
3325                         if (t == TypeManager.int64_type)
3326                                 return new LongConstant ((long) v);
3327                         if (t == TypeManager.uint64_type)
3328                                 return new ULongConstant ((ulong) v);
3329                         if (t == TypeManager.short_type)
3330                                 return new ShortConstant ((short) v);
3331                         if (t == TypeManager.ushort_type)
3332                                 return new UShortConstant ((ushort) v);
3333                         if (t == TypeManager.byte_type)
3334                                 return new ByteConstant ((byte) v);
3335                         if (t == TypeManager.sbyte_type)
3336                                 return new SByteConstant ((sbyte) v);
3337
3338                         throw new Exception ("Invalid enumeration underlying type: " + t);
3339                 }
3340
3341                 //
3342                 // Extracts the value in the enumeration on its native representation
3343                 //
3344                 public object GetPlainValue ()
3345                 {
3346                         Type t = TypeManager.EnumToUnderlying (Child.Type);
3347                         object v = ((Constant) Child).GetValue ();;
3348                         
3349                         if (t == TypeManager.int32_type)
3350                                 return (int) v;
3351                         if (t == TypeManager.uint32_type)
3352                                 return (uint) v;
3353                         if (t == TypeManager.int64_type)
3354                                 return (long) v;
3355                         if (t == TypeManager.uint64_type)
3356                                 return (ulong) v;
3357                         if (t == TypeManager.short_type)
3358                                 return (short) v;
3359                         if (t == TypeManager.ushort_type)
3360                                 return (ushort) v;
3361                         if (t == TypeManager.byte_type)
3362                                 return (byte) v;
3363                         if (t == TypeManager.sbyte_type)
3364                                 return (sbyte) v;
3365
3366                         return null;
3367                 }
3368                 
3369                 public override string AsString ()
3370                 {
3371                         return Child.AsString ();
3372                 }
3373
3374                 public override DoubleConstant ConvertToDouble ()
3375                 {
3376                         return Child.ConvertToDouble ();
3377                 }
3378
3379                 public override FloatConstant ConvertToFloat ()
3380                 {
3381                         return Child.ConvertToFloat ();
3382                 }
3383
3384                 public override ULongConstant ConvertToULong ()
3385                 {
3386                         return Child.ConvertToULong ();
3387                 }
3388
3389                 public override LongConstant ConvertToLong ()
3390                 {
3391                         return Child.ConvertToLong ();
3392                 }
3393
3394                 public override UIntConstant ConvertToUInt ()
3395                 {
3396                         return Child.ConvertToUInt ();
3397                 }
3398
3399                 public override IntConstant ConvertToInt ()
3400                 {
3401                         return Child.ConvertToInt ();
3402                 }
3403         }
3404
3405         /// <summary>
3406         ///   This kind of cast is used to encapsulate Value Types in objects.
3407         ///
3408         ///   The effect of it is to box the value type emitted by the previous
3409         ///   operation.
3410         /// </summary>
3411         public class BoxedCast : EmptyCast {
3412
3413                 public BoxedCast (Expression expr)
3414                         : base (expr, TypeManager.object_type)
3415                 {
3416                 }
3417
3418                 public override Expression DoResolve (EmitContext ec)
3419                 {
3420                         // This should never be invoked, we are born in fully
3421                         // initialized state.
3422
3423                         return this;
3424                 }
3425
3426                 public override void Emit (EmitContext ec)
3427                 {
3428                         base.Emit (ec);
3429                         
3430                         ec.ig.Emit (OpCodes.Box, child.Type);
3431                 }
3432         }
3433
3434         public class UnboxCast : EmptyCast {
3435                 public UnboxCast (Expression expr, Type return_type)
3436                         : base (expr, return_type)
3437                 {
3438                 }
3439
3440                 public override Expression DoResolve (EmitContext ec)
3441                 {
3442                         // This should never be invoked, we are born in fully
3443                         // initialized state.
3444
3445                         return this;
3446                 }
3447
3448                 public override void Emit (EmitContext ec)
3449                 {
3450                         Type t = type;
3451                         ILGenerator ig = ec.ig;
3452                         
3453                         base.Emit (ec);
3454                         ig.Emit (OpCodes.Unbox, t);
3455
3456                         LoadFromPtr (ig, t);
3457                 }
3458         }
3459         
3460         /// <summary>
3461         ///   This is used to perform explicit numeric conversions.
3462         ///
3463         ///   Explicit numeric conversions might trigger exceptions in a checked
3464         ///   context, so they should generate the conv.ovf opcodes instead of
3465         ///   conv opcodes.
3466         /// </summary>
3467         public class ConvCast : EmptyCast {
3468                 public enum Mode : byte {
3469                         I1_U1, I1_U2, I1_U4, I1_U8, I1_CH,
3470                         U1_I1, U1_CH,
3471                         I2_I1, I2_U1, I2_U2, I2_U4, I2_U8, I2_CH,
3472                         U2_I1, U2_U1, U2_I2, U2_CH,
3473                         I4_I1, I4_U1, I4_I2, I4_U2, I4_U4, I4_U8, I4_CH,
3474                         U4_I1, U4_U1, U4_I2, U4_U2, U4_I4, U4_CH,
3475                         I8_I1, I8_U1, I8_I2, I8_U2, I8_I4, I8_U4, I8_U8, I8_CH,
3476                         U8_I1, U8_U1, U8_I2, U8_U2, U8_I4, U8_U4, U8_I8, U8_CH,
3477                         CH_I1, CH_U1, CH_I2,
3478                         R4_I1, R4_U1, R4_I2, R4_U2, R4_I4, R4_U4, R4_I8, R4_U8, R4_CH,
3479                         R8_I1, R8_U1, R8_I2, R8_U2, R8_I4, R8_U4, R8_I8, R8_U8, R8_CH, R8_R4
3480                 }
3481
3482                 Mode mode;
3483                 bool checked_state;
3484                 
3485                 public ConvCast (EmitContext ec, Expression child, Type return_type, Mode m)
3486                         : base (child, return_type)
3487                 {
3488                         checked_state = ec.CheckState;
3489                         mode = m;
3490                 }
3491
3492                 public override Expression DoResolve (EmitContext ec)
3493                 {
3494                         // This should never be invoked, we are born in fully
3495                         // initialized state.
3496
3497                         return this;
3498                 }
3499
3500                 public override void Emit (EmitContext ec)
3501                 {
3502                         ILGenerator ig = ec.ig;
3503                         
3504                         base.Emit (ec);
3505
3506                         if (checked_state){
3507                                 switch (mode){
3508                                 case Mode.I1_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
3509                                 case Mode.I1_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
3510                                 case Mode.I1_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
3511                                 case Mode.I1_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
3512                                 case Mode.I1_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
3513
3514                                 case Mode.U1_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
3515                                 case Mode.U1_CH: /* nothing */ break;
3516
3517                                 case Mode.I2_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
3518                                 case Mode.I2_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
3519                                 case Mode.I2_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
3520                                 case Mode.I2_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
3521                                 case Mode.I2_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
3522                                 case Mode.I2_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
3523
3524                                 case Mode.U2_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
3525                                 case Mode.U2_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
3526                                 case Mode.U2_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
3527                                 case Mode.U2_CH: /* nothing */ break;
3528
3529                                 case Mode.I4_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
3530                                 case Mode.I4_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
3531                                 case Mode.I4_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
3532                                 case Mode.I4_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
3533                                 case Mode.I4_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
3534                                 case Mode.I4_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
3535                                 case Mode.I4_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
3536
3537                                 case Mode.U4_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
3538                                 case Mode.U4_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
3539                                 case Mode.U4_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
3540                                 case Mode.U4_U2: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
3541                                 case Mode.U4_I4: ig.Emit (OpCodes.Conv_Ovf_I4_Un); break;
3542                                 case Mode.U4_CH: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
3543
3544                                 case Mode.I8_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
3545                                 case Mode.I8_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
3546                                 case Mode.I8_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
3547                                 case Mode.I8_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
3548                                 case Mode.I8_I4: ig.Emit (OpCodes.Conv_Ovf_I4); break;
3549                                 case Mode.I8_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
3550                                 case Mode.I8_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
3551                                 case Mode.I8_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
3552
3553                                 case Mode.U8_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
3554                                 case Mode.U8_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
3555                                 case Mode.U8_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
3556                                 case Mode.U8_U2: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
3557                                 case Mode.U8_I4: ig.Emit (OpCodes.Conv_Ovf_I4_Un); break;
3558                                 case Mode.U8_U4: ig.Emit (OpCodes.Conv_Ovf_U4_Un); break;
3559                                 case Mode.U8_I8: ig.Emit (OpCodes.Conv_Ovf_I8_Un); break;
3560                                 case Mode.U8_CH: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
3561
3562                                 case Mode.CH_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
3563                                 case Mode.CH_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
3564                                 case Mode.CH_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
3565
3566                                 case Mode.R4_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
3567                                 case Mode.R4_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
3568                                 case Mode.R4_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
3569                                 case Mode.R4_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
3570                                 case Mode.R4_I4: ig.Emit (OpCodes.Conv_Ovf_I4); break;
3571                                 case Mode.R4_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
3572                                 case Mode.R4_I8: ig.Emit (OpCodes.Conv_Ovf_I8); break;
3573                                 case Mode.R4_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
3574                                 case Mode.R4_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
3575
3576                                 case Mode.R8_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
3577                                 case Mode.R8_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
3578                                 case Mode.R8_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
3579                                 case Mode.R8_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
3580                                 case Mode.R8_I4: ig.Emit (OpCodes.Conv_Ovf_I4); break;
3581                                 case Mode.R8_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
3582                                 case Mode.R8_I8: ig.Emit (OpCodes.Conv_Ovf_I8); break;
3583                                 case Mode.R8_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
3584                                 case Mode.R8_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
3585                                 case Mode.R8_R4: ig.Emit (OpCodes.Conv_R4); break;
3586                                 }
3587                         } else {
3588                                 switch (mode){
3589                                 case Mode.I1_U1: ig.Emit (OpCodes.Conv_U1); break;
3590                                 case Mode.I1_U2: ig.Emit (OpCodes.Conv_U2); break;
3591                                 case Mode.I1_U4: ig.Emit (OpCodes.Conv_U4); break;
3592                                 case Mode.I1_U8: ig.Emit (OpCodes.Conv_I8); break;
3593                                 case Mode.I1_CH: ig.Emit (OpCodes.Conv_U2); break;
3594
3595                                 case Mode.U1_I1: ig.Emit (OpCodes.Conv_I1); break;
3596                                 case Mode.U1_CH: ig.Emit (OpCodes.Conv_U2); break;
3597
3598                                 case Mode.I2_I1: ig.Emit (OpCodes.Conv_I1); break;
3599                                 case Mode.I2_U1: ig.Emit (OpCodes.Conv_U1); break;
3600                                 case Mode.I2_U2: ig.Emit (OpCodes.Conv_U2); break;
3601                                 case Mode.I2_U4: ig.Emit (OpCodes.Conv_U4); break;
3602                                 case Mode.I2_U8: ig.Emit (OpCodes.Conv_I8); break;
3603                                 case Mode.I2_CH: ig.Emit (OpCodes.Conv_U2); break;
3604
3605                                 case Mode.U2_I1: ig.Emit (OpCodes.Conv_I1); break;
3606                                 case Mode.U2_U1: ig.Emit (OpCodes.Conv_U1); break;
3607                                 case Mode.U2_I2: ig.Emit (OpCodes.Conv_I2); break;
3608                                 case Mode.U2_CH: /* nothing */ break;
3609
3610                                 case Mode.I4_I1: ig.Emit (OpCodes.Conv_I1); break;
3611                                 case Mode.I4_U1: ig.Emit (OpCodes.Conv_U1); break;
3612                                 case Mode.I4_I2: ig.Emit (OpCodes.Conv_I2); break;
3613                                 case Mode.I4_U4: /* nothing */ break;
3614                                 case Mode.I4_U2: ig.Emit (OpCodes.Conv_U2); break;
3615                                 case Mode.I4_U8: ig.Emit (OpCodes.Conv_I8); break;
3616                                 case Mode.I4_CH: ig.Emit (OpCodes.Conv_U2); break;
3617
3618                                 case Mode.U4_I1: ig.Emit (OpCodes.Conv_I1); break;
3619                                 case Mode.U4_U1: ig.Emit (OpCodes.Conv_U1); break;
3620                                 case Mode.U4_I2: ig.Emit (OpCodes.Conv_I2); break;
3621                                 case Mode.U4_U2: ig.Emit (OpCodes.Conv_U2); break;
3622                                 case Mode.U4_I4: /* nothing */ break;
3623                                 case Mode.U4_CH: ig.Emit (OpCodes.Conv_U2); break;
3624
3625                                 case Mode.I8_I1: ig.Emit (OpCodes.Conv_I1); break;
3626                                 case Mode.I8_U1: ig.Emit (OpCodes.Conv_U1); break;
3627                                 case Mode.I8_I2: ig.Emit (OpCodes.Conv_I2); break;
3628                                 case Mode.I8_U2: ig.Emit (OpCodes.Conv_U2); break;
3629                                 case Mode.I8_I4: ig.Emit (OpCodes.Conv_I4); break;
3630                                 case Mode.I8_U4: ig.Emit (OpCodes.Conv_U4); break;
3631                                 case Mode.I8_U8: /* nothing */ break;
3632                                 case Mode.I8_CH: ig.Emit (OpCodes.Conv_U2); break;
3633
3634                                 case Mode.U8_I1: ig.Emit (OpCodes.Conv_I1); break;
3635                                 case Mode.U8_U1: ig.Emit (OpCodes.Conv_U1); break;
3636                                 case Mode.U8_I2: ig.Emit (OpCodes.Conv_I2); break;
3637                                 case Mode.U8_U2: ig.Emit (OpCodes.Conv_U2); break;
3638                                 case Mode.U8_I4: ig.Emit (OpCodes.Conv_I4); break;
3639                                 case Mode.U8_U4: ig.Emit (OpCodes.Conv_U4); break;
3640                                 case Mode.U8_I8: /* nothing */ break;
3641                                 case Mode.U8_CH: ig.Emit (OpCodes.Conv_U2); break;
3642
3643                                 case Mode.CH_I1: ig.Emit (OpCodes.Conv_I1); break;
3644                                 case Mode.CH_U1: ig.Emit (OpCodes.Conv_U1); break;
3645                                 case Mode.CH_I2: ig.Emit (OpCodes.Conv_I2); break;
3646
3647                                 case Mode.R4_I1: ig.Emit (OpCodes.Conv_I1); break;
3648                                 case Mode.R4_U1: ig.Emit (OpCodes.Conv_U1); break;
3649                                 case Mode.R4_I2: ig.Emit (OpCodes.Conv_I2); break;
3650                                 case Mode.R4_U2: ig.Emit (OpCodes.Conv_U2); break;
3651                                 case Mode.R4_I4: ig.Emit (OpCodes.Conv_I4); break;
3652                                 case Mode.R4_U4: ig.Emit (OpCodes.Conv_U4); break;
3653                                 case Mode.R4_I8: ig.Emit (OpCodes.Conv_I8); break;
3654                                 case Mode.R4_U8: ig.Emit (OpCodes.Conv_U8); break;
3655                                 case Mode.R4_CH: ig.Emit (OpCodes.Conv_U2); break;
3656
3657                                 case Mode.R8_I1: ig.Emit (OpCodes.Conv_I1); break;
3658                                 case Mode.R8_U1: ig.Emit (OpCodes.Conv_U1); break;
3659                                 case Mode.R8_I2: ig.Emit (OpCodes.Conv_I2); break;
3660                                 case Mode.R8_U2: ig.Emit (OpCodes.Conv_U2); break;
3661                                 case Mode.R8_I4: ig.Emit (OpCodes.Conv_I4); break;
3662                                 case Mode.R8_U4: ig.Emit (OpCodes.Conv_U4); break;
3663                                 case Mode.R8_I8: ig.Emit (OpCodes.Conv_I8); break;
3664                                 case Mode.R8_U8: ig.Emit (OpCodes.Conv_U8); break;
3665                                 case Mode.R8_CH: ig.Emit (OpCodes.Conv_U2); break;
3666                                 case Mode.R8_R4: ig.Emit (OpCodes.Conv_R4); break;
3667                                 }
3668                         }
3669                 }
3670         }
3671         
3672         public class OpcodeCast : EmptyCast {
3673                 OpCode op, op2;
3674                 bool second_valid;
3675                 
3676                 public OpcodeCast (Expression child, Type return_type, OpCode op)
3677                         : base (child, return_type)
3678                         
3679                 {
3680                         this.op = op;
3681                         second_valid = false;
3682                 }
3683
3684                 public OpcodeCast (Expression child, Type return_type, OpCode op, OpCode op2)
3685                         : base (child, return_type)
3686                         
3687                 {
3688                         this.op = op;
3689                         this.op2 = op2;
3690                         second_valid = true;
3691                 }
3692
3693                 public override Expression DoResolve (EmitContext ec)
3694                 {
3695                         // This should never be invoked, we are born in fully
3696                         // initialized state.
3697
3698                         return this;
3699                 }
3700
3701                 public override void Emit (EmitContext ec)
3702                 {
3703                         base.Emit (ec);
3704                         ec.ig.Emit (op);
3705
3706                         if (second_valid)
3707                                 ec.ig.Emit (op2);
3708                 }                       
3709         }
3710
3711         /// <summary>
3712         ///   This kind of cast is used to encapsulate a child and cast it
3713         ///   to the class requested
3714         /// </summary>
3715         public class ClassCast : EmptyCast {
3716                 public ClassCast (Expression child, Type return_type)
3717                         : base (child, return_type)
3718                         
3719                 {
3720                 }
3721
3722                 public override Expression DoResolve (EmitContext ec)
3723                 {
3724                         // This should never be invoked, we are born in fully
3725                         // initialized state.
3726
3727                         return this;
3728                 }
3729
3730                 public override void Emit (EmitContext ec)
3731                 {
3732                         base.Emit (ec);
3733
3734                         ec.ig.Emit (OpCodes.Castclass, type);
3735                 }                       
3736                 
3737         }
3738         
3739         /// <summary>
3740         ///   SimpleName expressions are initially formed of a single
3741         ///   word and it only happens at the beginning of the expression.
3742         /// </summary>
3743         ///
3744         /// <remarks>
3745         ///   The expression will try to be bound to a Field, a Method
3746         ///   group or a Property.  If those fail we pass the name to our
3747         ///   caller and the SimpleName is compounded to perform a type
3748         ///   lookup.  The idea behind this process is that we want to avoid
3749         ///   creating a namespace map from the assemblies, as that requires
3750         ///   the GetExportedTypes function to be called and a hashtable to
3751         ///   be constructed which reduces startup time.  If later we find
3752         ///   that this is slower, we should create a 'NamespaceExpr' expression
3753         ///   that fully participates in the resolution process. 
3754         ///   
3755         ///   For example 'System.Console.WriteLine' is decomposed into
3756         ///   MemberAccess (MemberAccess (SimpleName ("System"), "Console"), "WriteLine")
3757         ///   
3758         ///   The first SimpleName wont produce a match on its own, so it will
3759         ///   be turned into:
3760         ///   MemberAccess (SimpleName ("System.Console"), "WriteLine").
3761         ///   
3762         ///   System.Console will produce a TypeExpr match.
3763         ///   
3764         ///   The downside of this is that we might be hitting 'LookupType' too many
3765         ///   times with this scheme.
3766         /// </remarks>
3767         public class SimpleName : Expression, ITypeExpression {
3768                 public readonly string Name;
3769                 
3770                 public SimpleName (string name, Location l)
3771                 {
3772                         Name = name;
3773                         loc = l;
3774                 }
3775
3776                 public static void Error_ObjectRefRequired (EmitContext ec, Location l, string name)
3777                 {
3778                         if (ec.IsFieldInitializer)
3779                                 Report.Error (
3780                                         236, l,
3781                                         "A field initializer cannot reference the non-static field, " +
3782                                         "method or property '"+name+"'");
3783                         else
3784                                 Report.Error (
3785                                         120, l,
3786                                         "An object reference is required " +
3787                                         "for the non-static field '"+name+"'");
3788                 }
3789                 
3790                 //
3791                 // Checks whether we are trying to access an instance
3792                 // property, method or field from a static body.
3793                 //
3794                 Expression MemberStaticCheck (EmitContext ec, Expression e)
3795                 {
3796                         if (e is IMemberExpr){
3797                                 IMemberExpr member = (IMemberExpr) e;
3798                                 
3799                                 if (!member.IsStatic){
3800                                         Error_ObjectRefRequired (ec, loc, Name);
3801                                         return null;
3802                                 }
3803                         }
3804
3805                         return e;
3806                 }
3807                 
3808                 public override Expression DoResolve (EmitContext ec)
3809                 {
3810                         return SimpleNameResolve (ec, null, false);
3811                 }
3812
3813                 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
3814                 {
3815                         return SimpleNameResolve (ec, right_side, false);
3816                 }
3817                 
3818
3819                 public Expression DoResolveAllowStatic (EmitContext ec)
3820                 {
3821                         return SimpleNameResolve (ec, null, true);
3822                 }
3823
3824                 public Expression DoResolveType (EmitContext ec)
3825                 {
3826                         //
3827                         // Stage 3: Lookup symbol in the various namespaces. 
3828                         //
3829                         DeclSpace ds = ec.DeclSpace;
3830                         Type t;
3831                         string alias_value;
3832
3833                         if (ec.ResolvingTypeTree){
3834                                 int errors = Report.Errors;
3835                                 Type dt = ec.DeclSpace.FindType (loc, Name);
3836                                 if (Report.Errors != errors)
3837                                         return null;
3838                                 
3839                                 if (dt != null)
3840                                         return new TypeExpr (dt, loc);
3841                         }
3842
3843                         if ((t = RootContext.LookupType (ds, Name, true, loc)) != null)
3844                                 return new TypeExpr (t, loc);
3845                                 
3846
3847                         //
3848                         // Stage 2 part b: Lookup up if we are an alias to a type
3849                         // or a namespace.
3850                         //
3851                         // Since we are cheating: we only do the Alias lookup for
3852                         // namespaces if the name does not include any dots in it
3853                         //
3854                                 
3855                         alias_value = ec.DeclSpace.LookupAlias (Name);
3856                                 
3857                         if (Name.IndexOf ('.') == -1 && alias_value != null) {
3858                                 if ((t = RootContext.LookupType (ds, alias_value, true, loc)) != null)
3859                                         return new TypeExpr (t, loc);
3860                                         
3861                                 // we have alias value, but it isn't Type, so try if it's namespace
3862                                 return new SimpleName (alias_value, loc);
3863                         }
3864                                 
3865                         // No match, maybe our parent can compose us
3866                         // into something meaningful.
3867                         return this;
3868                 }
3869
3870                 /// <remarks>
3871                 ///   7.5.2: Simple Names. 
3872                 ///
3873                 ///   Local Variables and Parameters are handled at
3874                 ///   parse time, so they never occur as SimpleNames.
3875                 ///
3876                 ///   The 'allow_static' flag is used by MemberAccess only
3877                 ///   and it is used to inform us that it is ok for us to 
3878                 ///   avoid the static check, because MemberAccess might end
3879                 ///   up resolving the Name as a Type name and the access as
3880                 ///   a static type access.
3881                 ///
3882                 ///   ie: Type Type; .... { Type.GetType (""); }
3883                 ///
3884                 ///   Type is both an instance variable and a Type;  Type.GetType
3885                 ///   is the static method not an instance method of type.
3886                 /// </remarks>
3887                 Expression SimpleNameResolve (EmitContext ec, Expression right_side, bool allow_static)
3888                 {
3889                         Expression e = null;
3890                         
3891                         //
3892                         // Stage 1: Performed by the parser (binding to locals or parameters).
3893                         //
3894                         Block current_block = ec.CurrentBlock;
3895                         if (ec.InvokingOwnOverload == false && current_block != null && current_block.IsVariableDefined (Name)){
3896                                 LocalVariableReference var;
3897
3898                                 var = new LocalVariableReference (ec.CurrentBlock, Name, loc);
3899
3900                                 if (right_side != null)
3901                                         return var.ResolveLValue (ec, right_side);
3902                                 else
3903                                         return var.Resolve (ec);
3904                         }
3905
3906                         if (current_block != null){
3907                                 int idx = -1;
3908                                 Parameter par = null;
3909                                 Parameters pars = current_block.Parameters;
3910                                 if (pars != null)
3911                                         par = pars.GetParameterByName (Name, out idx);
3912
3913                                 if (par != null) {
3914                                         ParameterReference param;
3915                                         
3916                                         param = new ParameterReference (pars, idx, Name, loc);
3917
3918                                         if (right_side != null)
3919                                                 return param.ResolveLValue (ec, right_side);
3920                                         else
3921                                                 return param.Resolve (ec);
3922                                 }
3923                         }
3924
3925                         //
3926                         // Stage 2: Lookup members 
3927                         //
3928
3929                         //
3930                         // For enums, the TypeBuilder is not ec.DeclSpace.TypeBuilder
3931                         // Hence we have two different cases
3932                         //
3933
3934                         DeclSpace lookup_ds = ec.DeclSpace;
3935                         do {
3936                                 if (lookup_ds.TypeBuilder == null)
3937                                         break;
3938
3939                                 e = MemberLookup (ec, lookup_ds.TypeBuilder, Name, loc);
3940                                 if (e != null)
3941                                         break;
3942
3943                                 //
3944                                 // Classes/structs keep looking, enums break
3945                                 //
3946                                 if (lookup_ds is TypeContainer)
3947                                         lookup_ds = ((TypeContainer) lookup_ds).Parent;
3948                                 else
3949                                         break;
3950                         } while (lookup_ds != null);
3951                                 
3952                         if (e == null && ec.ContainerType != null)
3953                                 e = MemberLookup (ec, ec.ContainerType, Name, loc);
3954
3955 // #52067 - Start - Trying to solve
3956
3957                         if (e == null) {
3958                                 
3959                                 ArrayList lookups = new ArrayList();
3960                                 ArrayList typelookups = new ArrayList();
3961                                 
3962                                 int split = Name.LastIndexOf('.');
3963                                 if (split != -1) {
3964                                         String nameSpacePart = Name.Substring(0, split);
3965                                         String memberNamePart = Name.Substring(split + 1);
3966                                         foreach(Type type in TypeManager.GetPertinentStandardModules(nameSpacePart)) {
3967                                                 e = MemberLookup(ec, type, memberNamePart, loc);
3968                                                 if (e != null) {
3969                                                         lookups.Add(e);
3970                                                         typelookups.Add(type);
3971                                                 }
3972                                         }
3973                                 }
3974                                 
3975                                 string[] NamespacesInScope = RootContext.SourceBeingCompiled.GetNamespacesInScope(ec.DeclSpace.Namespace.Name);
3976                                 foreach(Type type in TypeManager.GetPertinentStandardModules(NamespacesInScope)) {
3977                                         e = MemberLookup(ec, type, Name, loc);
3978                                         if (e != null) {
3979                                                 lookups.Add(e);
3980                                                 typelookups.Add(type);
3981                                         }
3982                                 }
3983                                 if (lookups.Count == 1) { 
3984                                         e = (Expression)lookups[0];
3985                                 } else {
3986                                         if (lookups.Count > 1) {
3987                                                 StringBuilder sb = new StringBuilder();
3988                                                 foreach(Type type in typelookups)
3989                                                         sb.Append("'" + type.FullName + "'");                                           
3990                                                 Error (-1, "The name '" + Name + "' can be resolved to a member of more than one standard module: " + sb.ToString() + ". Please fully qualify it.");
3991                                                 return null;
3992                                         }
3993                                 }
3994                         }
3995
3996 // #52067 - End
3997
3998                         if (e == null)
3999                                 return DoResolveType (ec);
4000
4001                         if (e is TypeExpr)
4002                                 return e;
4003
4004                         if (e is IMemberExpr) {
4005                                 e = MemberAccess.ResolveMemberAccess (ec, e, null, loc, this);
4006                                 if (e == null)
4007                                         return null;
4008
4009                                 IMemberExpr me = e as IMemberExpr;
4010                                 if (me == null)
4011                                         return e;
4012
4013                                 // This fails if ResolveMemberAccess() was unable to decide whether
4014                                 // it's a field or a type of the same name.
4015                                 if (!me.IsStatic && (me.InstanceExpression == null))
4016                                         return e;
4017
4018 /* FIXME    If this is not commented out, it seems that it's not possible to reach class members in mBas.
4019             Maybe a grammar-related problem?
4020
4021                                 if (!me.IsStatic &&
4022                                     TypeManager.IsNestedChildOf (me.InstanceExpression.Type, me.DeclaringType)) {
4023                                         Error (38, "Cannot access nonstatic member '" + me.Name + "' of " +
4024                                                "outer type '" + me.DeclaringType + "' via nested type '" +
4025                                                me.InstanceExpression.Type + "'");
4026                                         return null;
4027                                 }
4028 */
4029                                 if (right_side != null)
4030                                         e = e.DoResolveLValue (ec, right_side);
4031                                 else
4032                                         e = e.DoResolve (ec);
4033
4034                                 return e;
4035                         }
4036
4037                         if (ec.IsStatic || ec.IsFieldInitializer){
4038                                 if (allow_static)
4039                                         return e;
4040
4041                                 return MemberStaticCheck (ec, e);
4042                         } else
4043                                 return e;
4044                 }
4045                 
4046                 public override void Emit (EmitContext ec)
4047                 {
4048                         //
4049                         // If this is ever reached, then we failed to
4050                         // find the name as a namespace
4051                         //
4052
4053                         Error (30451, "The name '" + Name +
4054                                "' does not exist in the class '" +
4055                                ec.DeclSpace.Name + "'");
4056                 }
4057
4058                 public override string ToString ()
4059                 {
4060                         return Name;
4061                 }
4062         }
4063         
4064         /// <summary>
4065         ///   Fully resolved expression that evaluates to a type
4066         /// </summary>
4067         public class TypeExpr : Expression, ITypeExpression {
4068                 public TypeExpr (Type t, Location l)
4069                 {
4070                         Type = t;
4071                         eclass = ExprClass.Type;
4072                         loc = l;
4073                 }
4074
4075                 public virtual Expression DoResolveType (EmitContext ec)
4076                 {
4077                         return this;
4078                 }
4079
4080                 override public Expression DoResolve (EmitContext ec)
4081                 {
4082                         return this;
4083                 }
4084
4085                 override public void Emit (EmitContext ec)
4086                 {
4087                         throw new Exception ("Should never be called");
4088                 }
4089
4090                 public override string ToString ()
4091                 {
4092                         return Type.ToString ();
4093                 }
4094         }
4095
4096         /// <summary>
4097         ///   Used to create types from a fully qualified name.  These are just used
4098         ///   by the parser to setup the core types.  A TypeLookupExpression is always
4099         ///   classified as a type.
4100         /// </summary>
4101         public class TypeLookupExpression : TypeExpr {
4102                 string name;
4103                 
4104                 public TypeLookupExpression (string name) : base (null, Location.Null)
4105                 {
4106                         this.name = name;
4107                 }
4108
4109                 public override Expression DoResolveType (EmitContext ec)
4110                 {
4111                         if (type == null)
4112                                 type = RootContext.LookupType (ec.DeclSpace, name, false, Location.Null);
4113                         return this;
4114                 }
4115
4116                 public override Expression DoResolve (EmitContext ec)
4117                 {
4118                         return DoResolveType (ec);
4119                 }
4120
4121                 public override void Emit (EmitContext ec)
4122                 {
4123                         throw new Exception ("Should never be called");
4124                 }
4125
4126                 public override string ToString ()
4127                 {
4128                         return name;
4129                 }
4130         }
4131
4132         /// <summary>
4133         ///   MethodGroup Expression.
4134         ///  
4135         ///   This is a fully resolved expression that evaluates to a type
4136         /// </summary>
4137         public class MethodGroupExpr : Expression, IMemberExpr {
4138                 public MethodBase [] Methods;
4139                 Expression instance_expression = null;
4140                 bool is_explicit_impl = false;
4141                 
4142                 public MethodGroupExpr (MemberInfo [] mi, Location l)
4143                 {
4144                         Methods = new MethodBase [mi.Length];
4145                         mi.CopyTo (Methods, 0);
4146                         eclass = ExprClass.MethodGroup;
4147                         type = TypeManager.object_type;
4148                         loc = l;
4149                 }
4150
4151                 public MethodGroupExpr (ArrayList list, Location l)
4152                 {
4153                         Methods = new MethodBase [list.Count];
4154
4155                         try {
4156                                 list.CopyTo (Methods, 0);
4157                         } catch {
4158                                 foreach (MemberInfo m in list){
4159                                         if (!(m is MethodBase)){
4160                                                 Console.WriteLine ("Name " + m.Name);
4161                                                 Console.WriteLine ("Found a: " + m.GetType ().FullName);
4162                                         }
4163                                 }
4164                                 throw;
4165                         }
4166                         loc = l;
4167                         eclass = ExprClass.MethodGroup;
4168                         type = TypeManager.object_type;
4169                 }
4170
4171                 public Type DeclaringType {
4172                         get {
4173                                 return Methods [0].DeclaringType;
4174                         }
4175                 }
4176                 
4177                 //
4178                 // 'A method group may have associated an instance expression' 
4179                 // 
4180                 public Expression InstanceExpression {
4181                         get {
4182                                 return instance_expression;
4183                         }
4184
4185                         set {
4186                                 instance_expression = value;
4187                         }
4188                 }
4189
4190                 public bool IsExplicitImpl {
4191                         get {
4192                                 return is_explicit_impl;
4193                         }
4194
4195                         set {
4196                                 is_explicit_impl = value;
4197                         }
4198                 }
4199
4200                 public string Name {
4201                         get {
4202                                 return Methods [0].Name;
4203                         }
4204                 }
4205
4206                 public bool IsInstance {
4207                         get {
4208                                 foreach (MethodBase mb in Methods)
4209                                         if (!mb.IsStatic)
4210                                                 return true;
4211
4212                                 return false;
4213                         }
4214                 }
4215
4216                 public bool IsStatic {
4217                         get {
4218                                 foreach (MethodBase mb in Methods)
4219                                         if (mb.IsStatic)
4220                                                 return true;
4221
4222                                 return false;
4223                         }
4224                 }
4225                 
4226                 override public Expression DoResolve (EmitContext ec)
4227                 {
4228                         if (instance_expression != null) {
4229                                 instance_expression = instance_expression.DoResolve (ec);
4230                                 if (instance_expression == null)
4231                                         return null;
4232                         }
4233
4234                         return this;
4235                 }
4236
4237                 public void ReportUsageError ()
4238                 {
4239                         Report.Error (654, loc, "Method '" + Methods [0].DeclaringType + "." +
4240                                       Methods [0].Name + "()' is referenced without parentheses");
4241                 }
4242
4243                 override public void Emit (EmitContext ec)
4244                 {
4245                         ReportUsageError ();
4246                 }
4247
4248                 bool RemoveMethods (bool keep_static)
4249                 {
4250                         ArrayList smethods = new ArrayList ();
4251
4252                         foreach (MethodBase mb in Methods){
4253                                 if (mb.IsStatic == keep_static)
4254                                         smethods.Add (mb);
4255                         }
4256
4257                         if (smethods.Count == 0)
4258                                 return false;
4259
4260                         Methods = new MethodBase [smethods.Count];
4261                         smethods.CopyTo (Methods, 0);
4262
4263                         return true;
4264                 }
4265                 
4266                 /// <summary>
4267                 ///   Removes any instance methods from the MethodGroup, returns
4268                 ///   false if the resulting set is empty.
4269                 /// </summary>
4270                 public bool RemoveInstanceMethods ()
4271                 {
4272                         return RemoveMethods (true);
4273                 }
4274
4275                 /// <summary>
4276                 ///   Removes any static methods from the MethodGroup, returns
4277                 ///   false if the resulting set is empty.
4278                 /// </summary>
4279                 public bool RemoveStaticMethods ()
4280                 {
4281                         return RemoveMethods (false);
4282                 }
4283         }
4284
4285         /// <summary>
4286         ///   Fully resolved expression that evaluates to a Field
4287         /// </summary>
4288         public class FieldExpr : Expression, IAssignMethod, IMemoryLocation, IMemberExpr {
4289                 public readonly FieldInfo FieldInfo;
4290                 Expression instance_expr;
4291                 
4292                 public FieldExpr (FieldInfo fi, Location l)
4293                 {
4294                         FieldInfo = fi;
4295                         eclass = ExprClass.Variable;
4296                         type = fi.FieldType;
4297                         loc = l;
4298                 }
4299
4300                 public string Name {
4301                         get {
4302                                 return FieldInfo.Name;
4303                         }
4304                 }
4305
4306                 public bool IsInstance {
4307                         get {
4308                                 return !FieldInfo.IsStatic;
4309                         }
4310                 }
4311
4312                 public bool IsStatic {
4313                         get {
4314                                 return FieldInfo.IsStatic;
4315                         }
4316                 }
4317
4318                 public Type DeclaringType {
4319                         get {
4320                                 return FieldInfo.DeclaringType;
4321                         }
4322                 }
4323
4324                 public Expression InstanceExpression {
4325                         get {
4326                                 return instance_expr;
4327                         }
4328
4329                         set {
4330                                 instance_expr = value;
4331                         }
4332                 }
4333
4334                 override public Expression DoResolve (EmitContext ec)
4335                 {
4336                         if (!FieldInfo.IsStatic){
4337                                 if (instance_expr == null){
4338                                         throw new Exception ("non-static FieldExpr without instance var\n" +
4339                                                              "You have to assign the Instance variable\n" +
4340                                                              "Of the FieldExpr to set this\n");
4341                                 }
4342
4343                                 // Resolve the field's instance expression while flow analysis is turned
4344                                 // off: when accessing a field "a.b", we must check whether the field
4345                                 // "a.b" is initialized, not whether the whole struct "a" is initialized.
4346                                 instance_expr = instance_expr.Resolve (ec, ResolveFlags.VariableOrValue |
4347                                                                        ResolveFlags.DisableFlowAnalysis);
4348                                 if (instance_expr == null)
4349                                         return null;
4350                         }
4351
4352                         // If the instance expression is a local variable or parameter.
4353                         IVariable var = instance_expr as IVariable;
4354                         if ((var != null) && !var.IsFieldAssigned (ec, FieldInfo.Name, loc))
4355                                 return null;
4356
4357                         return this;
4358                 }
4359
4360                 void Report_AssignToReadonly (bool is_instance)
4361                 {
4362                         string msg;
4363                         
4364                         if (is_instance)
4365                                 msg = "Readonly field can not be assigned outside " +
4366                                 "of constructor or variable initializer";
4367                         else
4368                                 msg = "A static readonly field can only be assigned in " +
4369                                 "a static constructor";
4370
4371                         Report.Error (is_instance ? 191 : 198, loc, msg);
4372                 }
4373                 
4374                 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
4375                 {
4376                         IVariable var = instance_expr as IVariable;
4377                         if (var != null)
4378                                 var.SetFieldAssigned (ec, FieldInfo.Name);
4379
4380                         Expression e = DoResolve (ec);
4381
4382                         if (e == null)
4383                                 return null;
4384                         
4385                         if (!FieldInfo.IsInitOnly)
4386                                 return this;
4387
4388                         //
4389                         // InitOnly fields can only be assigned in constructors
4390                         //
4391
4392                         if (ec.IsConstructor)
4393                                 return this;
4394
4395                         Report_AssignToReadonly (true);
4396                         
4397                         return null;
4398                 }
4399
4400                 override public void Emit (EmitContext ec)
4401                 {
4402                         ILGenerator ig = ec.ig;
4403                         bool is_volatile = false;
4404
4405                         if (FieldInfo is FieldBuilder){
4406                                 FieldBase f = TypeManager.GetField (FieldInfo);
4407
4408                                 if ((f.ModFlags & Modifiers.VOLATILE) != 0)
4409                                         is_volatile = true;
4410                                 
4411                                 f.status |= Field.Status.USED;
4412                         }
4413                         
4414                         if (FieldInfo.IsStatic){
4415                                 if (is_volatile)
4416                                         ig.Emit (OpCodes.Volatile);
4417                                 
4418                                 ig.Emit (OpCodes.Ldsfld, FieldInfo);
4419                         } else {
4420                                 if (instance_expr.Type.IsValueType){
4421                                         IMemoryLocation ml;
4422                                         LocalTemporary tempo = null;
4423                                         
4424                                         if (!(instance_expr is IMemoryLocation)){
4425                                                 tempo = new LocalTemporary (
4426                                                         ec, instance_expr.Type);
4427
4428                                                 InstanceExpression.Emit (ec);
4429                                                 tempo.Store (ec);
4430                                                 ml = tempo;
4431                                         } else
4432                                                 ml = (IMemoryLocation) instance_expr;
4433
4434                                         ml.AddressOf (ec, AddressOp.Load);
4435                                 } else 
4436                                         instance_expr.Emit (ec);
4437
4438                                 if (is_volatile)
4439                                         ig.Emit (OpCodes.Volatile);
4440                                 
4441                                 ig.Emit (OpCodes.Ldfld, FieldInfo);
4442                         }
4443                 }
4444
4445                 public void EmitAssign (EmitContext ec, Expression source)
4446                 {
4447                         FieldAttributes fa = FieldInfo.Attributes;
4448                         bool is_static = (fa & FieldAttributes.Static) != 0;
4449                         bool is_readonly = (fa & FieldAttributes.InitOnly) != 0;
4450                         ILGenerator ig = ec.ig;
4451
4452                         if (is_readonly && !ec.IsConstructor){
4453                                 Report_AssignToReadonly (!is_static);
4454                                 return;
4455                         }
4456                         
4457                         if (!is_static){
4458                                 Expression instance = instance_expr;
4459
4460                                 if (instance.Type.IsValueType){
4461                                         if (instance is IMemoryLocation){
4462                                                 IMemoryLocation ml = (IMemoryLocation) instance;
4463
4464                                                 ml.AddressOf (ec, AddressOp.Store);
4465                                         } else
4466                                                 throw new Exception ("The " + instance + " of type " +
4467                                                                      instance.Type +
4468                                                                      " represents a ValueType and does " +
4469                                                                      "not implement IMemoryLocation");
4470                                 } else
4471                                         instance.Emit (ec);
4472                         }
4473                         source.Emit (ec);
4474
4475                         if (FieldInfo is FieldBuilder){
4476                                 FieldBase f = TypeManager.GetField (FieldInfo);
4477                                 
4478                                 if ((f.ModFlags & Modifiers.VOLATILE) != 0)
4479                                         ig.Emit (OpCodes.Volatile);
4480                         }
4481                         
4482                         if (is_static)
4483                                 ig.Emit (OpCodes.Stsfld, FieldInfo);
4484                         else 
4485                                 ig.Emit (OpCodes.Stfld, FieldInfo);
4486
4487                         if (FieldInfo is FieldBuilder){
4488                                 FieldBase f = TypeManager.GetField (FieldInfo);
4489
4490                                 f.status |= Field.Status.ASSIGNED;
4491                         }
4492                 }
4493                 
4494                 public void AddressOf (EmitContext ec, AddressOp mode)
4495                 {
4496                         ILGenerator ig = ec.ig;
4497                         
4498                         if (FieldInfo is FieldBuilder){
4499                                 FieldBase f = TypeManager.GetField (FieldInfo);
4500                                 if ((f.ModFlags & Modifiers.VOLATILE) != 0)
4501                                         ig.Emit (OpCodes.Volatile);
4502                         }
4503
4504                         if (FieldInfo is FieldBuilder){
4505                                 FieldBase f = TypeManager.GetField (FieldInfo);
4506
4507                                 if ((mode & AddressOp.Store) != 0)
4508                                         f.status |= Field.Status.ASSIGNED;
4509                                 if ((mode & AddressOp.Load) != 0)
4510                                         f.status |= Field.Status.USED;
4511                         }
4512
4513                         //
4514                         // Handle initonly fields specially: make a copy and then
4515                         // get the address of the copy.
4516                         //
4517                         if (FieldInfo.IsInitOnly && !ec.IsConstructor){
4518                                 LocalBuilder local;
4519                                 
4520                                 Emit (ec);
4521                                 local = ig.DeclareLocal (type);
4522                                 ig.Emit (OpCodes.Stloc, local);
4523                                 ig.Emit (OpCodes.Ldloca, local);
4524                                 return;
4525                         }
4526
4527                         if (FieldInfo.IsStatic)
4528                                 ig.Emit (OpCodes.Ldsflda, FieldInfo);
4529                         else {
4530                                 if (instance_expr is IMemoryLocation)
4531                                         ((IMemoryLocation)instance_expr).AddressOf (ec, AddressOp.LoadStore);
4532                                 else
4533                                         instance_expr.Emit (ec);
4534                                 ig.Emit (OpCodes.Ldflda, FieldInfo);
4535                         }
4536                 }
4537         }
4538         
4539         /// <summary>
4540         ///   Expression that evaluates to a Property.  The Assign class
4541         ///   might set the 'Value' expression if we are in an assignment.
4542         ///
4543         ///   This is not an LValue because we need to re-write the expression, we
4544         ///   can not take data from the stack and store it.  
4545         /// </summary>
4546         public class PropertyExpr : ExpressionStatement, IAssignMethod, IMemberExpr {
4547                 public readonly PropertyInfo PropertyInfo;
4548                 public bool IsBase;
4549                 MethodInfo getter, setter;
4550                 bool is_static;
4551                 public ArrayList PropertyArgs;
4552
4553                 Expression instance_expr;
4554
4555                 public PropertyExpr (EmitContext ec, PropertyInfo pi, Location l)
4556                 {
4557                         PropertyInfo = pi;
4558                         eclass = ExprClass.PropertyAccess;
4559                         PropertyArgs = new ArrayList();
4560                         is_static = false;
4561                         loc = l;
4562
4563                         type = TypeManager.TypeToCoreType (pi.PropertyType);
4564
4565                         ResolveAccessors (ec);
4566                 }
4567
4568                 public string Name {
4569                         get {
4570                                 return PropertyInfo.Name;
4571                         }
4572                 }
4573
4574                 public bool IsInstance {
4575                         get {
4576                                 return !is_static;
4577                         }
4578                 }
4579
4580                 public bool IsStatic {
4581                         get {
4582                                 return is_static;
4583                         }
4584                 }
4585                 
4586                 public Type DeclaringType {
4587                         get {
4588                                 return PropertyInfo.DeclaringType;
4589                         }
4590                 }
4591
4592                 //
4593                 // The instance expression associated with this expression
4594                 //
4595                 public Expression InstanceExpression {
4596                         set {
4597                                 instance_expr = value;
4598                         }
4599
4600                         get {
4601                                 return instance_expr;
4602                         }
4603                 }
4604
4605                 public bool VerifyAssignable ()
4606                 {
4607                         if (!PropertyInfo.CanWrite){
4608                                 Report.Error (200, loc, 
4609                                               "The property '" + PropertyInfo.Name +
4610                                               "' can not be assigned to, as it has not set accessor");
4611                                 return false;
4612                         }
4613
4614                         return true;
4615                 }
4616
4617                 void ResolveAccessors (EmitContext ec)
4618                 {
4619                         BindingFlags flags = BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance;
4620                         MemberInfo [] group;
4621                         
4622                         group = TypeManager.MemberLookup (ec.ContainerType, PropertyInfo.DeclaringType,
4623                                                               MemberTypes.Method, flags, "get_" + PropertyInfo.Name);
4624
4625                         //
4626                         // The first method is the closest to us
4627                         //
4628                         if (group != null && group.Length > 0){
4629                                 getter = (MethodInfo) group [0];
4630
4631                                 if (getter.IsStatic)
4632                                         is_static = true;
4633                         }                       
4634
4635                         //
4636                         // The first method is the closest to us
4637                         //
4638                         group = TypeManager.MemberLookup (ec.ContainerType, PropertyInfo.DeclaringType,
4639                                                           MemberTypes.Method, flags, "set_" + PropertyInfo.Name);
4640                         if (group != null && group.Length > 0){
4641                                 setter = (MethodInfo) group [0];
4642                                 if (setter.IsStatic)
4643                                         is_static = true;
4644                         }
4645                 }
4646
4647                 override public Expression DoResolve (EmitContext ec)
4648                 {
4649                         if (getter == null){
4650                                 Report.Error (154, loc, 
4651                                               "The property '" + PropertyInfo.Name +
4652                                               "' can not be used in " +
4653                                               "this context because it lacks a get accessor");
4654                                 return null;
4655                         }
4656
4657                         if ((instance_expr == null) && ec.IsStatic && !is_static) {
4658                                 SimpleName.Error_ObjectRefRequired (ec, loc, PropertyInfo.Name);
4659                                 return null;
4660                         }
4661
4662                         if (instance_expr != null) {
4663                                 instance_expr = instance_expr.DoResolve (ec);
4664                                 if (instance_expr == null)
4665                                         return null;
4666                         }
4667
4668                         return this;
4669                 }
4670
4671                 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
4672                 {
4673                         if (setter == null){
4674                                 Report.Error (154, loc, 
4675                                               "The property '" + PropertyInfo.Name +
4676                                               "' can not be used in " +
4677                                               "this context because it lacks a set accessor");
4678                                 return null;
4679                         }
4680
4681                         if (instance_expr != null) {
4682                                 instance_expr = instance_expr.DoResolve (ec);
4683                                 if (instance_expr == null)
4684                                         return null;
4685                         }
4686
4687                         return this;
4688                 }
4689
4690                 override public void Emit (EmitContext ec)
4691                 {
4692                         //
4693                         // Special case: length of single dimension array property is turned into ldlen
4694                         //
4695                         if ((getter == TypeManager.system_int_array_get_length) ||
4696                             (getter == TypeManager.int_array_get_length)){
4697                                 Type iet = instance_expr.Type;
4698
4699                                 //
4700                                 // System.Array.Length can be called, but the Type does not
4701                                 // support invoking GetArrayRank, so test for that case first
4702                                 //
4703                                 if (iet != TypeManager.array_type && (iet.GetArrayRank () == 1)){
4704                                         instance_expr.Emit (ec);
4705                                         ec.ig.Emit (OpCodes.Ldlen);
4706                                         return;
4707                                 }
4708                         }
4709                         Invocation.EmitCall (ec, IsBase, IsStatic, instance_expr, getter, null, PropertyArgs, loc);
4710                 }
4711
4712                 //
4713                 // Implements the IAssignMethod interface for assignments
4714                 //
4715                 public void EmitAssign (EmitContext ec, Expression source)
4716                 {
4717                         Argument arg = new Argument (source, Argument.AType.Expression);
4718                         ArrayList args = new ArrayList ();
4719 //HERE
4720                         args.Add (arg);
4721                         Invocation.EmitCall (ec, IsBase, IsStatic, instance_expr, setter, args, PropertyArgs,loc);
4722                 }
4723
4724                 override public void EmitStatement (EmitContext ec)
4725                 {
4726                         Emit (ec);
4727                         ec.ig.Emit (OpCodes.Pop);
4728                 }
4729         }
4730
4731         /// <summary>
4732         ///   Fully resolved expression that evaluates to an Event
4733         /// </summary>
4734         public class EventExpr : Expression, IMemberExpr {
4735                 public readonly EventInfo EventInfo;
4736                 public Expression instance_expr;
4737
4738                 bool is_static;
4739                 MethodInfo add_accessor, remove_accessor;
4740                 
4741                 public EventExpr (EventInfo ei, Location loc)
4742                 {
4743                         EventInfo = ei;
4744                         this.loc = loc;
4745                         eclass = ExprClass.EventAccess;
4746
4747                         add_accessor = TypeManager.GetAddMethod (ei);
4748                         remove_accessor = TypeManager.GetRemoveMethod (ei);
4749                         
4750                         if (add_accessor.IsStatic || remove_accessor.IsStatic)
4751                                 is_static = true;
4752
4753                         if (EventInfo is MyEventBuilder)
4754                                 type = ((MyEventBuilder) EventInfo).EventType;
4755                         else
4756                                 type = EventInfo.EventHandlerType;
4757                 }
4758
4759                 public string Name {
4760                         get {
4761                                 return EventInfo.Name;
4762                         }
4763                 }
4764
4765                 public bool IsInstance {
4766                         get {
4767                                 return !is_static;
4768                         }
4769                 }
4770
4771                 public bool IsStatic {
4772                         get {
4773                                 return is_static;
4774                         }
4775                 }
4776
4777                 public Type DeclaringType {
4778                         get {
4779                                 return EventInfo.DeclaringType;
4780                         }
4781                 }
4782
4783                 public Expression InstanceExpression {
4784                         get {
4785                                 return instance_expr;
4786                         }
4787
4788                         set {
4789                                 instance_expr = value;
4790                         }
4791                 }
4792
4793                 public override Expression DoResolve (EmitContext ec)
4794                 {
4795                         if (instance_expr != null) {
4796                                 instance_expr = instance_expr.DoResolve (ec);
4797                                 if (instance_expr == null)
4798                                         return null;
4799                         }
4800
4801                         return this;
4802                 }
4803
4804                 public override void Emit (EmitContext ec)
4805                 {
4806                         Report.Error (70, loc, "The event '" + Name + "' can only appear on the left hand side of += or -= (except on the defining type)");
4807                 }
4808
4809                 public void EmitAddOrRemove (EmitContext ec, Expression source)
4810                 {
4811                         Expression handler = ((Binary) source).Right;
4812                         
4813                         Argument arg = new Argument (handler, Argument.AType.Expression);
4814                         ArrayList args = new ArrayList ();
4815                                 
4816                         args.Add (arg);
4817                         
4818                         if (((Binary) source).Oper == Binary.Operator.Addition)
4819                                 Invocation.EmitCall (
4820                                         ec, false, IsStatic, instance_expr, add_accessor, args, loc);
4821                         else
4822                                 Invocation.EmitCall (
4823                                         ec, false, IsStatic, instance_expr, remove_accessor, args, loc);
4824                 }
4825         }
4826 }