* ecore.cs (ImplicitInvocation): Set eclass and type to that of the child
[mono.git] / mcs / bmcs / convert.cs
1 //
2 // conversion.cs: various routines for implementing conversions.
3 //
4 // Authors:
5 //   Miguel de Icaza (miguel@ximian.com)
6 //   Ravi Pratap (ravi@ximian.com)
7 //
8 // (C) 2001, 2002, 2003 Ximian, Inc.
9 //
10
11 namespace Mono.CSharp {
12         using System;
13         using System.Collections;
14         using System.Diagnostics;
15         using System.Reflection;
16         using System.Reflection.Emit;
17
18         //
19         // A container class for all the conversion operations
20         //
21         public class Convert {
22                 //
23                 // This is used to prettify the code: a null argument is allowed
24                 // for ImplicitStandardConversion as long as it is known that
25                 // no anonymous method will play a role.
26                 //
27                 // FIXME: renamed from `const' to `static' to allow bootstraping from older
28                 // versions of the compiler that could not cope with this construct.
29                 //
30                 public static EmitContext ConstantEC = null;
31                 
32                 static public void Error_CannotConvertType (Location loc, Type source, Type target)
33                 {
34                         Report.Error (30, loc, "Cannot convert type '" +
35                                       TypeManager.CSharpName (source) + "' to '" +
36                                       TypeManager.CSharpName (target) + "'");
37                 }
38
39                 static Expression TypeParameter_to_Null (Expression expr, Type target_type,
40                                                          Location loc)
41                 {
42                         if (!TypeParameter_to_Null (target_type)) {
43                                 Report.Error (403, loc, "Cannot convert null to the type " +
44                                               "parameter `{0}' becaues it could be a value " +
45                                               "type.  Consider using `default ({0})' instead.",
46                                               target_type);
47                                 return null;
48                         }
49
50                         return new NullCast (expr, target_type);
51                 }
52
53                 static bool TypeParameter_to_Null (Type target_type)
54                 {
55                         GenericConstraints gc = TypeManager.GetTypeParameterConstraints (target_type);
56                         if (gc == null)
57                                 return false;
58
59                         if (gc.HasReferenceTypeConstraint)
60                                 return true;
61                         if (gc.HasClassConstraint && !TypeManager.IsValueType (gc.ClassConstraint))
62                                 return true;
63
64                         return false;
65                 }
66
67                 static Type TypeParam_EffectiveBaseType (EmitContext ec, Type t)
68                 {
69                         GenericConstraints gc = TypeManager.GetTypeParameterConstraints (t);
70                         if (gc == null)
71                                 return TypeManager.object_type;
72
73                         return TypeParam_EffectiveBaseType (ec, gc);
74                 }
75
76                 static Type TypeParam_EffectiveBaseType (EmitContext ec, GenericConstraints gc)
77                 {
78                         ArrayList list = new ArrayList ();
79                         list.Add (gc.EffectiveBaseClass);
80                         foreach (Type t in gc.InterfaceConstraints) {
81                                 if (!t.IsGenericParameter)
82                                         continue;
83
84                                 GenericConstraints new_gc = TypeManager.GetTypeParameterConstraints (t);
85                                 if (new_gc != null)
86                                         list.Add (TypeParam_EffectiveBaseType (ec, new_gc));
87                         }
88                         return FindMostEncompassedType (ec, list);
89                 }
90
91                 static Expression TypeParameterConversion (Expression expr, bool is_reference, Type target_type)
92                 {
93                         if (is_reference)
94                                 return new EmptyCast (expr, target_type);
95                         else
96                                 return new BoxedCast (expr, target_type);
97                 }
98
99                 static Expression ImplicitTypeParameterConversion (EmitContext ec, Expression expr,
100                                                                    Type target_type)
101                 {
102                         Type expr_type = expr.Type;
103
104                         GenericConstraints gc = TypeManager.GetTypeParameterConstraints (expr_type);
105
106                         if (gc == null) {
107                                 if (target_type == TypeManager.object_type)
108                                         return new BoxedCast (expr);
109
110                                 return null;
111                         }
112
113                         // We're converting from a type parameter which is known to be a reference type.
114                         bool is_reference = gc.IsReferenceType;
115                         Type base_type = TypeParam_EffectiveBaseType (ec, gc);
116
117                         if (TypeManager.IsSubclassOf (base_type, target_type))
118                                 return TypeParameterConversion (expr, is_reference, target_type);
119
120                         if (target_type.IsInterface) {
121                                 if (TypeManager.ImplementsInterface (base_type, target_type))
122                                         return TypeParameterConversion (expr, is_reference, target_type);
123
124                                 foreach (Type t in gc.InterfaceConstraints) {
125                                         if (TypeManager.IsSubclassOf (t, target_type))
126                                                 return TypeParameterConversion (expr, is_reference, target_type);
127                                 }
128                         }
129
130                         foreach (Type t in gc.InterfaceConstraints) {
131                                 if (!t.IsGenericParameter)
132                                         continue;
133                                 if (TypeManager.IsSubclassOf (t, target_type))
134                                         return TypeParameterConversion (expr, is_reference, target_type);
135                         }
136
137                         return null;
138                 }
139
140                 static EmptyExpression MyEmptyExpr;
141                 static public Expression WideningReferenceConversion (EmitContext ec, Expression expr, Type target_type)
142                 {
143                         Type expr_type = expr.Type;
144
145                         if (expr_type == null && expr.eclass == ExprClass.MethodGroup){
146                                 // if we are a method group, emit a warning
147
148                                 expr.Emit (null);
149                         }
150
151                         if (expr_type == TypeManager.void_type)
152                                 return null;
153
154                         if (expr_type.IsGenericParameter)
155                                 return ImplicitTypeParameterConversion (ec, expr, target_type);
156                                 
157                         //
158                         // notice that it is possible to write "ValueType v = 1", the ValueType here
159                         // is an abstract class, and not really a value type, so we apply the same rules.
160                         //
161                         if (target_type == TypeManager.object_type) {
162                                 //
163                                 // A pointer type cannot be converted to object
164                                 // 
165                                 if (expr_type.IsPointer)
166                                         return null;
167
168                                 if (TypeManager.IsValueType (expr_type))
169                                         return new BoxedCast (expr);
170                                 if (expr_type.IsClass || expr_type.IsInterface || expr_type == TypeManager.enum_type){
171                                         if (expr_type == TypeManager.anonymous_method_type)
172                                                 return null;
173                                         return new EmptyCast (expr, target_type);
174                                 }
175
176                                 return null;
177                         } else if (target_type == TypeManager.value_type) {
178                                 if (TypeManager.IsValueType (expr_type))
179                                         return new BoxedCast (expr);
180                                 if (expr_type == TypeManager.null_type)
181                                         return new NullCast (expr, target_type);
182
183                                 return null;
184                         } else if (TypeManager.IsSubclassOf (expr_type, target_type)) {
185                                 //
186                                 // Special case: enumeration to System.Enum.
187                                 // System.Enum is not a value type, it is a class, so we need
188                                 // a boxing conversion
189                                 //
190                                 if (expr_type.IsEnum || expr_type.IsGenericParameter)
191                                         return new BoxedCast (expr);
192
193                                 return new EmptyCast (expr, target_type);
194                         }
195
196                         // This code is kind of mirrored inside WideningStandardConversionExists
197                         // with the small distinction that we only probe there
198                         //
199                         // Always ensure that the code here and there is in sync
200
201                         // from the null type to any reference-type.
202                         if (expr_type == TypeManager.null_type){
203                                 if (target_type.IsPointer)
204                                         return new EmptyCast (expr, target_type);
205                                         
206                                 if (!target_type.IsValueType)
207                                         return new NullCast (expr, target_type);
208                         }
209
210                         // from any class-type S to any interface-type T.
211                         if (target_type.IsInterface) {
212                                 if (target_type != TypeManager.iconvertible_type &&
213                                     expr_type.IsValueType && (expr is Constant) &&
214                                     !(expr is IntLiteral || expr is BoolLiteral ||
215                                       expr is FloatLiteral || expr is DoubleLiteral ||
216                                       expr is LongLiteral || expr is CharLiteral ||
217                                       expr is StringLiteral || expr is DecimalLiteral ||
218                                       expr is UIntLiteral || expr is ULongLiteral)) {
219                                         return null;
220                                 }
221
222                                 if (TypeManager.ImplementsInterface (expr_type, target_type)){
223                                         if (expr_type.IsGenericParameter || TypeManager.IsValueType (expr_type))
224                                                 return new BoxedCast (expr, target_type);
225                                         else
226                                                 return new EmptyCast (expr, target_type);
227                                 }
228                         }
229
230                         // from any interface type S to interface-type T.
231                         if (expr_type.IsInterface && target_type.IsInterface) {
232                                 if (TypeManager.ImplementsInterface (expr_type, target_type))
233                                         return new EmptyCast (expr, target_type);
234                                 else
235                                         return null;
236                         }
237
238                         // from an array-type S to an array-type of type T
239                         if (expr_type.IsArray && target_type.IsArray) {
240                                 if (expr_type.GetArrayRank () == target_type.GetArrayRank ()) {
241
242                                         Type expr_element_type = TypeManager.GetElementType (expr_type);
243
244                                         if (MyEmptyExpr == null)
245                                                 MyEmptyExpr = new EmptyExpression ();
246                                                 
247                                         MyEmptyExpr.SetType (expr_element_type);
248                                         Type target_element_type = TypeManager.GetElementType (target_type);
249
250                                         if (!expr_element_type.IsValueType && !target_element_type.IsValueType)
251                                                 if (WideningStandardConversionExists (ConstantEC, MyEmptyExpr,
252                                                                                       target_element_type))
253                                                         return new EmptyCast (expr, target_type);
254                                 }
255                         }
256                                 
257                         // from an array-type to System.Array
258                         if (expr_type.IsArray && target_type == TypeManager.array_type)
259                                 return new EmptyCast (expr, target_type);
260
261                         // from an array-type of type T to IEnumerable<T>
262                         if (expr_type.IsArray && TypeManager.IsIEnumerable (expr_type, target_type))
263                                 return new EmptyCast (expr, target_type);
264
265                         // from any delegate type to System.Delegate
266                         if ((expr_type == TypeManager.delegate_type || TypeManager.IsDelegateType (expr_type)) &&
267                             target_type == TypeManager.delegate_type)
268                                 return new EmptyCast (expr, target_type);
269                                         
270                         // from any array-type or delegate type into System.ICloneable.
271                         if (expr_type.IsArray ||
272                             expr_type == TypeManager.delegate_type || TypeManager.IsDelegateType (expr_type))
273                                 if (target_type == TypeManager.icloneable_type)
274                                         return new EmptyCast (expr, target_type);
275
276                         // from a generic type definition to a generic instance.
277                         if (TypeManager.IsEqual (expr_type, target_type))
278                                 return new EmptyCast (expr, target_type);
279
280                         return null;
281                 }
282
283                 //
284                 // Tests whether an implicit reference conversion exists between expr_type
285                 // and target_type
286                 //
287                 public static bool WideningReferenceConversionExists (EmitContext ec, Expression expr, Type target_type)
288                 {
289                         Type expr_type = expr.Type;
290
291                         if (expr_type.IsGenericParameter)
292                                 return ImplicitTypeParameterConversion (ec, expr, target_type) != null;
293
294                         //
295                         // This is the boxed case.
296                         //
297                         if (target_type == TypeManager.object_type) {
298                                 if (expr_type.IsClass || TypeManager.IsValueType (expr_type) ||
299                                     expr_type.IsInterface || expr_type == TypeManager.enum_type)
300                                         if (target_type != TypeManager.anonymous_method_type)
301                                         return true;
302
303                                 return false;
304                         } else if (TypeManager.IsSubclassOf (expr_type, target_type))
305                                 return true;
306
307                         // Please remember that all code below actually comes
308                         // from WideningReferenceConversion so make sure code remains in sync
309                                 
310                         // from any class-type S to any interface-type T.
311                         if (target_type.IsInterface) {
312                                 if (target_type != TypeManager.iconvertible_type &&
313                                     expr_type.IsValueType && (expr is Constant) &&
314                                     !(expr is IntLiteral || expr is BoolLiteral ||
315                                       expr is FloatLiteral || expr is DoubleLiteral ||
316                                       expr is LongLiteral || expr is CharLiteral ||
317                                       expr is StringLiteral || expr is DecimalLiteral ||
318                                       expr is UIntLiteral || expr is ULongLiteral)) {
319                                         return false;
320                                 }
321                                 
322                                 if (TypeManager.ImplementsInterface (expr_type, target_type))
323                                         return true;
324                         }
325                                 
326                         // from any interface type S to interface-type T.
327                         if (expr_type.IsInterface && target_type.IsInterface)
328                                 if (TypeManager.ImplementsInterface (expr_type, target_type))
329                                         return true;
330                                 
331                         // from an array-type S to an array-type of type T
332                         if (expr_type.IsArray && target_type.IsArray) {
333                                 if (expr_type.GetArrayRank () == target_type.GetArrayRank ()) {
334                                                 
335                                         Type expr_element_type = expr_type.GetElementType ();
336
337                                         if (MyEmptyExpr == null)
338                                                 MyEmptyExpr = new EmptyExpression ();
339                                                 
340                                         MyEmptyExpr.SetType (expr_element_type);
341                                         Type target_element_type = TypeManager.GetElementType (target_type);
342                                                 
343                                         if (!expr_element_type.IsValueType && !target_element_type.IsValueType)
344                                                 if (WideningStandardConversionExists (ConstantEC, MyEmptyExpr,
345                                                                                       target_element_type))
346                                                         return true;
347                                 }
348                         }
349                                 
350                         // from an array-type to System.Array
351                         if (expr_type.IsArray && (target_type == TypeManager.array_type))
352                                 return true;
353
354                         // from an array-type of type T to IEnumerable<T>
355                         if (expr_type.IsArray && TypeManager.IsIEnumerable (expr_type, target_type))
356                                 return true;
357
358                         // from any delegate type to System.Delegate
359                         if ((expr_type == TypeManager.delegate_type || TypeManager.IsDelegateType (expr_type)) &&
360                             target_type == TypeManager.delegate_type)
361                                 if (target_type.IsAssignableFrom (expr_type))
362                                         return true;
363                                         
364                         // from any array-type or delegate type into System.ICloneable.
365                         if (expr_type.IsArray ||
366                             expr_type == TypeManager.delegate_type || TypeManager.IsDelegateType (expr_type))
367                                 if (target_type == TypeManager.icloneable_type)
368                                         return true;
369                                 
370                         // from the null type to any reference-type.
371                         if (expr_type == TypeManager.null_type){
372                                 if (target_type.IsPointer)
373                                         return true;
374                         
375                                 if (!target_type.IsValueType)
376                                         return true;
377                         }
378
379                         // from a generic type definition to a generic instance.
380                         if (TypeManager.IsEqual (expr_type, target_type))
381                                 return true;
382
383                         return false;
384                 }
385
386                 /// <summary>
387                 ///   Implicit Numeric Conversions.
388                 ///
389                 ///   expr is the expression to convert, returns a new expression of type
390                 ///   target_type or null if an implicit conversion is not possible.
391                 /// </summary>
392                 static public Expression WideningNumericConversion (EmitContext ec, Expression expr,
393                                                                     Type target_type, Location loc)
394                 {
395                         Type expr_type = expr.Type;
396
397                         //
398                         // Attempt to do the implicit constant expression conversions
399
400                         if (expr is Constant){
401                                 if (expr is IntConstant){
402                                         Expression e;
403                                         
404                                         e = TryWideningIntConversion (target_type, (IntConstant) expr);
405                                         
406                                         if (e != null)
407                                                 return e;
408                                 } else if (expr is LongConstant && target_type == TypeManager.uint64_type){
409                                         //
410                                         // Try the implicit constant expression conversion
411                                         // from long to ulong, instead of a nice routine,
412                                         // we just inline it
413                                         //
414                                         long v = ((LongConstant) expr).Value;
415                                         if (v >= 0)
416                                                 return new ULongConstant ((ulong) v);
417                                 } 
418                         }
419                         
420                         Type real_target_type = target_type;
421
422                         // VB.NET specific: Convert an enum to it's
423                         // underlying numeric type or any type that
424                         // it's underlyinmg type has widening
425                         // conversion to.
426
427                         if (expr_type.IsSubclassOf (TypeManager.enum_type)){
428                                 if (target_type == TypeManager.enum_type ||
429                                     target_type == TypeManager.object_type) {
430                                         if (expr is EnumConstant)
431                                                 expr = ((EnumConstant) expr).Child;
432                                         // We really need all these casts here .... :-(
433                                         expr = new BoxedCast (new EmptyCast (expr, expr_type));
434                                         return new EmptyCast (expr, target_type);
435                                 } 
436
437                                 //
438                                 // Notice that we have kept the expr_type unmodified, which is only
439                                 // used later on to 
440                                 if (expr is EnumConstant)
441                                         expr = ((EnumConstant) expr).Child;
442                                 else
443                                         expr = new EmptyCast (expr, TypeManager.EnumToUnderlying (expr_type));
444                                 expr_type = expr.Type;
445
446                                 if (expr_type == target_type)
447                                         return expr;
448                         }
449
450                         if (expr_type == TypeManager.sbyte_type){
451                                 //
452                                 // From sbyte to short, int, long, float, double.
453                                 //
454                                 if (real_target_type == TypeManager.int32_type)
455                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_I4);
456                                 if (real_target_type == TypeManager.int64_type)
457                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_I8);
458                                 if (real_target_type == TypeManager.double_type)
459                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_R8);
460                                 if (real_target_type == TypeManager.float_type)
461                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_R4);
462                                 if (real_target_type == TypeManager.short_type)
463                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_I2);
464                         } else if (expr_type == TypeManager.byte_type){
465                                 //
466                                 // From byte to short, ushort, int, uint, long, ulong, float, double
467                                 // 
468                                 if ((real_target_type == TypeManager.short_type) ||
469                                     (real_target_type == TypeManager.ushort_type) ||
470                                     (real_target_type == TypeManager.int32_type) ||
471                                     (real_target_type == TypeManager.uint32_type))
472                                         return new EmptyCast (expr, target_type);
473
474                                 if (real_target_type == TypeManager.uint64_type)
475                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_U8);
476                                 if (real_target_type == TypeManager.int64_type)
477                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_I8);
478                                 if (real_target_type == TypeManager.float_type)
479                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_R4);
480                                 if (real_target_type == TypeManager.double_type)
481                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_R8);
482                                 if (real_target_type == TypeManager.decimal_type)
483                                         return new ImplicitNew (ec, "System", "Decimal", loc, expr);
484                         } else if (expr_type == TypeManager.short_type){
485                                 //
486                                 // From short to int, long, float, double
487                                 // 
488                                 if (real_target_type == TypeManager.int32_type)
489                                         return new EmptyCast (expr, target_type);
490                                 if (real_target_type == TypeManager.int64_type)
491                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_I8);
492                                 if (real_target_type == TypeManager.double_type)
493                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_R8);
494                                 if (real_target_type == TypeManager.float_type)
495                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_R4);
496                                 if (real_target_type == TypeManager.decimal_type)
497                                         return new ImplicitNew (ec, "System", "Decimal", loc, expr);
498                         } else if (expr_type == TypeManager.ushort_type){
499                                 //
500                                 // From ushort to int, uint, long, ulong, float, double
501                                 //
502                                 if (real_target_type == TypeManager.uint32_type)
503                                         return new EmptyCast (expr, target_type);
504
505                                 if (real_target_type == TypeManager.uint64_type)
506                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_U8);
507                                 if (real_target_type == TypeManager.int32_type)
508                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_I4);
509                                 if (real_target_type == TypeManager.int64_type)
510                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_I8);
511                                 if (real_target_type == TypeManager.double_type)
512                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_R8);
513                                 if (real_target_type == TypeManager.float_type)
514                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_R4);
515                         } else if (expr_type == TypeManager.int32_type){
516                                 //
517                                 // From int to long, float, double
518                                 //
519                                 if (real_target_type == TypeManager.int64_type)
520                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_I8);
521                                 if (real_target_type == TypeManager.double_type)
522                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_R8);
523                                 if (real_target_type == TypeManager.float_type)
524                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_R4);
525                                 if (real_target_type == TypeManager.decimal_type)
526                                         return new ImplicitNew (ec, "System", "Decimal", loc, expr);
527                         } else if (expr_type == TypeManager.uint32_type){
528                                 //
529                                 // From uint to long, ulong, float, double
530                                 //
531                                 if (real_target_type == TypeManager.int64_type)
532                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_U8);
533                                 if (real_target_type == TypeManager.uint64_type)
534                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_U8);
535                                 if (real_target_type == TypeManager.double_type)
536                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_R_Un,
537                                                                OpCodes.Conv_R8);
538                                 if (real_target_type == TypeManager.float_type)
539                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_R_Un,
540                                                                OpCodes.Conv_R4);
541                         } else if (expr_type == TypeManager.uint64_type){
542                                 //
543                                 // From ulong to float, double
544                                 //
545                                 if (real_target_type == TypeManager.double_type)
546                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_R_Un,
547                                                                OpCodes.Conv_R8);
548                                 if (real_target_type == TypeManager.float_type)
549                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_R_Un,
550                                                                OpCodes.Conv_R4);        
551                         } else if (expr_type == TypeManager.int64_type){
552                                 //
553                                 // From long/ulong to float, double
554                                 //
555                                 if (real_target_type == TypeManager.double_type)
556                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_R8);
557                                 if (real_target_type == TypeManager.float_type)
558                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_R4);     
559                                 if (real_target_type == TypeManager.decimal_type)
560                                         return new ImplicitNew (ec, "System", "Decimal", loc, expr);    
561                         } else if (expr_type == TypeManager.float_type){
562                                 //
563                                 // float to double
564                                 //
565                                 if (real_target_type == TypeManager.double_type)
566                                         return new OpcodeCast (expr, target_type, OpCodes.Conv_R8);
567                         } else if (expr_type == TypeManager.decimal_type){
568                                 //
569                                 // From decimal to float, double
570                                 //
571                                 if (real_target_type == TypeManager.double_type)
572                                         return new ImplicitInvocation (ec, "System", "Convert", "ToDouble", loc, expr); 
573                                 if (real_target_type == TypeManager.float_type)
574                                         return new ImplicitInvocation (ec, "System", "Convert" ,"ToSingle", loc, expr); 
575                         }
576
577                         return null;
578                 }
579
580
581                 /// <summary>
582                 ///  Same as WideningStandardConversionExists except that it also looks at
583                 ///  implicit user defined conversions - needed for overload resolution
584                 /// </summary>
585                 public static bool WideningConversionExists (EmitContext ec, Expression expr, Type target_type)
586                 {
587                         if (expr is NullLiteral) {
588                                 if (target_type.IsGenericParameter)
589                                         return TypeParameter_to_Null (target_type);
590
591                                 if (TypeManager.IsNullableType (target_type))
592                                         return true;
593                         }
594
595                         if (WideningStandardConversionExists (ec, expr, target_type))
596                                 return true;
597
598                         //
599                         // VB.NET has no notion of User defined conversions
600                         //
601
602 //                      Expression dummy = ImplicitUserConversion (ec, expr, target_type, Location.Null);
603
604 //                      if (dummy != null)
605 //                              return true;
606
607                         return false;
608                 }
609
610                 //
611                 // VB.NET has no notion of User defined conversions
612                 //
613
614 //              public static bool ImplicitUserConversionExists (EmitContext ec, Type source, Type target)
615 //              {
616 //                      Expression dummy = ImplicitUserConversion (
617 //                              ec, new EmptyExpression (source), target, Location.Null);
618 //                      return dummy != null;
619 //              }
620
621                 /// <summary>
622                 ///  Determines if a standard implicit conversion exists from
623                 ///  expr_type to target_type
624                 ///
625                 ///  ec should point to a real EmitContext if expr.Type is TypeManager.anonymous_method_type.
626                 /// </summary>
627                 public static bool WideningStandardConversionExists (EmitContext ec, Expression expr, Type target_type)
628                 {
629                         Type expr_type = expr.Type;
630
631                         if (expr_type == TypeManager.void_type)
632                                 return false;
633
634                         //Console.WriteLine ("Expr is {0}", expr);
635                         //Console.WriteLine ("{0} -> {1} ?", expr_type, target_type);
636                         if (expr_type.Equals (target_type))
637                                 return true;
638
639
640                         // First numeric conversions 
641
642                         if (expr_type == TypeManager.sbyte_type){
643                                 //
644                                 // From sbyte to short, int, long, float, double.
645                                 //
646                                 if ((target_type == TypeManager.int32_type) || 
647                                     (target_type == TypeManager.int64_type) ||
648                                     (target_type == TypeManager.double_type) ||
649                                     (target_type == TypeManager.float_type)  ||
650                                     (target_type == TypeManager.short_type) ||
651                                     (target_type == TypeManager.decimal_type))
652                                         return true;
653                                 
654                         } else if (expr_type == TypeManager.byte_type){
655                                 //
656                                 // From byte to short, ushort, int, uint, long, ulong, float, double
657                                 // 
658                                 if ((target_type == TypeManager.short_type) ||
659                                     (target_type == TypeManager.ushort_type) ||
660                                     (target_type == TypeManager.int32_type) ||
661                                     (target_type == TypeManager.uint32_type) ||
662                                     (target_type == TypeManager.uint64_type) ||
663                                     (target_type == TypeManager.int64_type) ||
664                                     (target_type == TypeManager.float_type) ||
665                                     (target_type == TypeManager.double_type) ||
666                                     (target_type == TypeManager.decimal_type))
667                                         return true;
668         
669                         } else if (expr_type == TypeManager.short_type){
670                                 //
671                                 // From short to int, long, float, double
672                                 // 
673                                 if ((target_type == TypeManager.int32_type) ||
674                                     (target_type == TypeManager.int64_type) ||
675                                     (target_type == TypeManager.double_type) ||
676                                     (target_type == TypeManager.float_type) ||
677                                     (target_type == TypeManager.decimal_type))
678                                         return true;
679                                         
680                         } else if (expr_type == TypeManager.ushort_type){
681                                 //
682                                 // From ushort to int, uint, long, ulong, float, double
683                                 //
684                                 if ((target_type == TypeManager.uint32_type) ||
685                                     (target_type == TypeManager.uint64_type) ||
686                                     (target_type == TypeManager.int32_type) ||
687                                     (target_type == TypeManager.int64_type) ||
688                                     (target_type == TypeManager.double_type) ||
689                                     (target_type == TypeManager.float_type) ||
690                                     (target_type == TypeManager.decimal_type))
691                                         return true;
692                                     
693                         } else if (expr_type == TypeManager.int32_type){
694                                 //
695                                 // From int to long, float, double
696                                 //
697                                 if ((target_type == TypeManager.int64_type) ||
698                                     (target_type == TypeManager.double_type) ||
699                                     (target_type == TypeManager.float_type) ||
700                                     (target_type == TypeManager.decimal_type))
701                                         return true;
702                                         
703                         } else if (expr_type == TypeManager.uint32_type){
704                                 //
705                                 // From uint to long, ulong, float, double
706                                 //
707                                 if ((target_type == TypeManager.int64_type) ||
708                                     (target_type == TypeManager.uint64_type) ||
709                                     (target_type == TypeManager.double_type) ||
710                                     (target_type == TypeManager.float_type) ||
711                                     (target_type == TypeManager.decimal_type))
712                                         return true;
713                                         
714                         } else if ((expr_type == TypeManager.uint64_type) ||
715                                    (expr_type == TypeManager.int64_type)) {
716                                 //
717                                 // From long/ulong to float, double
718                                 //
719                                 if ((target_type == TypeManager.double_type) ||
720                                     (target_type == TypeManager.float_type) ||
721                                     (target_type == TypeManager.decimal_type))
722                                         return true;
723                                     
724                         } else if (expr_type == TypeManager.char_type){
725                                 //
726                                 // From char to ushort, int, uint, long, ulong, float, double
727                                 // 
728                                 if ((target_type == TypeManager.ushort_type) ||
729                                     (target_type == TypeManager.int32_type) ||
730                                     (target_type == TypeManager.uint32_type) ||
731                                     (target_type == TypeManager.uint64_type) ||
732                                     (target_type == TypeManager.int64_type) ||
733                                     (target_type == TypeManager.float_type) ||
734                                     (target_type == TypeManager.double_type) ||
735                                     (target_type == TypeManager.decimal_type))
736                                         return true;
737
738                         } else if (expr_type == TypeManager.float_type){
739                                 //
740                                 // float to double
741                                 //
742                                 if (target_type == TypeManager.double_type)
743                                         return true;
744                         }       
745                         
746                         if (expr.eclass == ExprClass.MethodGroup){
747                                 if (TypeManager.IsDelegateType (target_type) && RootContext.Version != LanguageVersion.ISO_1){
748                                         MethodGroupExpr mg = expr as MethodGroupExpr;
749                                         if (mg != null){
750                                                 //
751                                                 // This should not happen frequently, so we can create an object
752                                                 // to test compatibility
753                                                 //
754                                                 Expression c = ImplicitDelegateCreation.Create (ec, mg, target_type, Location.Null);
755                                                 return c != null;
756                                         }
757                                 }
758                         }
759                         
760                         if (WideningReferenceConversionExists (ec, expr, target_type))
761                                 return true;
762
763                         //
764                         // Implicit Constant Expression Conversions
765                         //
766                         if (expr is IntConstant){
767                                 int value = ((IntConstant) expr).Value;
768
769                                 if (target_type == TypeManager.sbyte_type){
770                                         if (value >= SByte.MinValue && value <= SByte.MaxValue)
771                                                 return true;
772                                 } else if (target_type == TypeManager.byte_type){
773                                         if (Byte.MinValue >= 0 && value <= Byte.MaxValue)
774                                                 return true;
775                                 } else if (target_type == TypeManager.short_type){
776                                         if (value >= Int16.MinValue && value <= Int16.MaxValue)
777                                                 return true;
778                                 } else if (target_type == TypeManager.ushort_type){
779                                         if (value >= UInt16.MinValue && value <= UInt16.MaxValue)
780                                                 return true;
781                                 } else if (target_type == TypeManager.uint32_type){
782                                         if (value >= 0)
783                                                 return true;
784                                 } else if (target_type == TypeManager.uint64_type){
785                                          //
786                                          // we can optimize this case: a positive int32
787                                          // always fits on a uint64.  But we need an opcode
788                                          // to do it.
789                                          //
790                                         if (value >= 0)
791                                                 return true;
792                                 }
793                                 
794                                 if (value == 0 && expr is IntLiteral && TypeManager.IsEnumType (target_type))
795                                         return true;
796                         }
797
798                         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 true;
807                         }
808                         
809                         if ((target_type == TypeManager.enum_type ||
810                              target_type.IsSubclassOf (TypeManager.enum_type)) &&
811                              expr is IntLiteral){
812                                 IntLiteral i = (IntLiteral) expr;
813
814                                 if (i.Value == 0)
815                                         return true;
816                         }
817
818                         //
819                         // If `expr_type' implements `target_type' (which is an iface)
820                         // see TryWideningIntConversion
821                         // 
822                         if (target_type.IsInterface && target_type.IsAssignableFrom (expr_type))
823                                 return true;
824
825                         if (target_type == TypeManager.void_ptr_type && expr_type.IsPointer)
826                                 return true;
827
828                         if (TypeManager.IsNullableType (expr_type) && TypeManager.IsNullableType (target_type))
829                                 return true;
830
831                         if (expr_type == TypeManager.anonymous_method_type){
832                                 if (!TypeManager.IsDelegateType (target_type))
833                                         return false;
834
835                                 AnonymousMethod am = (AnonymousMethod) expr;
836
837                                 Expression conv = am.Compatible (ec, target_type, true);
838                                 if (conv != null)
839                                         return true;
840                         }
841
842                         return false;
843                 }
844
845                 //
846                 // Used internally by FindMostEncompassedType, this is used
847                 // to avoid creating lots of objects in the tight loop inside
848                 // FindMostEncompassedType
849                 //
850                 static EmptyExpression priv_fmet_param;
851                 
852                 /// <summary>
853                 ///  Finds "most encompassed type" according to the spec (13.4.2)
854                 ///  amongst the methods in the MethodGroupExpr
855                 /// </summary>
856                 static Type FindMostEncompassedType (EmitContext ec, ArrayList types)
857                 {
858                         Type best = null;
859
860                         if (priv_fmet_param == null)
861                                 priv_fmet_param = new EmptyExpression ();
862
863                         foreach (Type t in types){
864                                 priv_fmet_param.SetType (t);
865                                 
866                                 if (best == null) {
867                                         best = t;
868                                         continue;
869                                 }
870                                 
871                                 if (WideningStandardConversionExists (ec, priv_fmet_param, best))
872                                         best = t;
873                         }
874
875                         return best;
876                 }
877
878                 //
879                 // Used internally by FindMostEncompassingType, this is used
880                 // to avoid creating lots of objects in the tight loop inside
881                 // FindMostEncompassingType
882                 //
883                 static EmptyExpression priv_fmee_ret;
884                 
885                 /// <summary>
886                 ///  Finds "most encompassing type" according to the spec (13.4.2)
887                 ///  amongst the types in the given set
888                 /// </summary>
889                 static Type FindMostEncompassingType (EmitContext ec, ArrayList types)
890                 {
891                         Type best = null;
892
893                         if (priv_fmee_ret == null)
894                                 priv_fmee_ret = new EmptyExpression ();
895
896                         foreach (Type t in types){
897                                 priv_fmee_ret.SetType (best);
898
899                                 if (best == null) {
900                                         best = t;
901                                         continue;
902                                 }
903
904                                 if (WideningStandardConversionExists (ec, priv_fmee_ret, t))
905                                         best = t;
906                         }
907                         
908                         return best;
909                 }
910
911                 //
912                 // Used to avoid creating too many objects
913                 //
914                 static EmptyExpression priv_fms_expr;
915                 
916                 /// <summary>
917                 ///   Finds the most specific source Sx according to the rules of the spec (13.4.4)
918                 ///   by making use of FindMostEncomp* methods. Applies the correct rules separately
919                 ///   for explicit and implicit conversion operators.
920                 /// </summary>
921                 static public Type FindMostSpecificSource (EmitContext ec, MethodGroupExpr me,
922                                                            Expression source, bool apply_explicit_conv_rules,
923                                                            Location loc)
924                 {
925                         ArrayList src_types_set = new ArrayList ();
926                         
927                         if (priv_fms_expr == null)
928                                 priv_fms_expr = new EmptyExpression ();
929
930                         //
931                         // If any operator converts from S then Sx = S
932                         //
933                         Type source_type = source.Type;
934                         foreach (MethodBase mb in me.Methods){
935                                 ParameterData pd = Invocation.GetParameterData (mb);
936                                 Type param_type = pd.ParameterType (0);
937
938                                 if (param_type == source_type)
939                                         return param_type;
940
941                                 if (apply_explicit_conv_rules) {
942                                         //
943                                         // From the spec :
944                                         // Find the set of applicable user-defined conversion operators, U.  This set
945                                         // consists of the
946                                         // user-defined implicit or explicit conversion operators declared by
947                                         // the classes or structs in D that convert from a type encompassing
948                                         // or encompassed by S to a type encompassing or encompassed by T
949                                         //
950                                         priv_fms_expr.SetType (param_type);
951                                         if (WideningStandardConversionExists (ec, priv_fms_expr, source_type))
952                                                 src_types_set.Add (param_type);
953                                         else {
954                                                 if (WideningStandardConversionExists (ec, source, param_type))
955                                                         src_types_set.Add (param_type);
956                                         }
957                                 } else {
958                                         //
959                                         // Only if S is encompassed by param_type
960                                         //
961                                         if (WideningStandardConversionExists (ec, source, param_type))
962                                                 src_types_set.Add (param_type);
963                                 }
964                         }
965                         
966                         //
967                         // Explicit Conv rules
968                         //
969                         if (apply_explicit_conv_rules) {
970                                 ArrayList candidate_set = new ArrayList ();
971
972                                 foreach (Type param_type in src_types_set){
973                                         if (WideningStandardConversionExists (ec, source, param_type))
974                                                 candidate_set.Add (param_type);
975                                 }
976
977                                 if (candidate_set.Count != 0)
978                                         return FindMostEncompassedType (ec, candidate_set);
979                         }
980
981                         //
982                         // Final case
983                         //
984                         if (apply_explicit_conv_rules)
985                                 return FindMostEncompassingType (ec, src_types_set);
986                         else
987                                 return FindMostEncompassedType (ec, src_types_set);
988                 }
989
990                 //
991                 // Useful in avoiding proliferation of objects
992                 //
993                 static EmptyExpression priv_fmt_expr;
994                 
995                 /// <summary>
996                 ///  Finds the most specific target Tx according to section 13.4.4
997                 /// </summary>
998                 static public Type FindMostSpecificTarget (EmitContext ec, MethodGroupExpr me,
999                                                            Type target, bool apply_explicit_conv_rules,
1000                                                            Location loc)
1001                 {
1002                         ArrayList tgt_types_set = new ArrayList ();
1003                         
1004                         if (priv_fmt_expr == null)
1005                                 priv_fmt_expr = new EmptyExpression ();
1006                         
1007                         //
1008                         // If any operator converts to T then Tx = T
1009                         //
1010                         foreach (MethodInfo mi in me.Methods){
1011                                 Type ret_type = mi.ReturnType;
1012
1013                                 if (ret_type == target)
1014                                         return ret_type;
1015
1016                                 if (apply_explicit_conv_rules) {
1017                                         //
1018                                         // From the spec :
1019                                         // Find the set of applicable user-defined conversion operators, U.
1020                                         //
1021                                         // This set consists of the
1022                                         // user-defined implicit or explicit conversion operators declared by
1023                                         // the classes or structs in D that convert from a type encompassing
1024                                         // or encompassed by S to a type encompassing or encompassed by T
1025                                         //
1026                                         priv_fms_expr.SetType (ret_type);
1027                                         if (WideningStandardConversionExists (ec, priv_fms_expr, target))
1028                                                 tgt_types_set.Add (ret_type);
1029                                         else {
1030                                                 priv_fms_expr.SetType (target);
1031                                                 if (WideningStandardConversionExists (ec, priv_fms_expr, ret_type))
1032                                                         tgt_types_set.Add (ret_type);
1033                                         }
1034                                 } else {
1035                                         //
1036                                         // Only if T is encompassed by param_type
1037                                         //
1038                                         priv_fms_expr.SetType (ret_type);
1039                                         if (WideningStandardConversionExists (ec, priv_fms_expr, target))
1040                                                 tgt_types_set.Add (ret_type);
1041                                 }
1042                         }
1043
1044                         //
1045                         // Explicit conv rules
1046                         //
1047                         if (apply_explicit_conv_rules) {
1048                                 ArrayList candidate_set = new ArrayList ();
1049
1050                                 foreach (Type ret_type in tgt_types_set){
1051                                         priv_fmt_expr.SetType (ret_type);
1052                                         
1053                                         if (WideningStandardConversionExists (ec, priv_fmt_expr, target))
1054                                                 candidate_set.Add (ret_type);
1055                                 }
1056
1057                                 if (candidate_set.Count != 0)
1058                                         return FindMostEncompassingType (ec, candidate_set);
1059                         }
1060                         
1061                         //
1062                         // Okay, final case !
1063                         //
1064                         if (apply_explicit_conv_rules)
1065                                 return FindMostEncompassedType (ec, tgt_types_set);
1066                         else 
1067                                 return FindMostEncompassingType (ec, tgt_types_set);
1068                 }
1069                 
1070                 /// <summary>
1071                 ///  User-defined Implicit conversions
1072                 /// </summary>
1073
1074                 //
1075                 // VB.NET has no notion of User defined conversions
1076                 //
1077
1078 //              static public Expression ImplicitUserConversion (EmitContext ec, Expression source,
1079 //                                                               Type target, Location loc)
1080 //              {
1081 //                      return UserDefinedConversion (ec, source, target, loc, false);
1082 //              }
1083
1084                 /// <summary>
1085                 ///  User-defined Explicit conversions
1086                 /// </summary>
1087
1088                 //
1089                 // VB.NET has no notion of User defined conversions
1090                 //
1091
1092 //              static public Expression ExplicitUserConversion (EmitContext ec, Expression source,
1093 //                                                               Type target, Location loc)
1094 //              {
1095 //                      return UserDefinedConversion (ec, source, target, loc, true);
1096 //              }
1097
1098                 static DoubleHash explicit_conv = new DoubleHash (100);
1099                 static DoubleHash implicit_conv = new DoubleHash (100);
1100                 /// <summary>
1101                 ///   Computes the MethodGroup for the user-defined conversion
1102                 ///   operators from source_type to target_type.  `look_for_explicit'
1103                 ///   controls whether we should also include the list of explicit
1104                 ///   operators
1105                 /// </summary>
1106                 static MethodGroupExpr GetConversionOperators (EmitContext ec,
1107                                                                Type source_type, Type target_type,
1108                                                                Location loc, bool look_for_explicit)
1109                 {
1110                         Expression mg1 = null, mg2 = null;
1111                         Expression mg5 = null, mg6 = null, mg7 = null, mg8 = null;
1112                         string op_name;
1113
1114                         op_name = "op_Implicit";
1115
1116                         MethodGroupExpr union3;
1117                         object r;
1118                         if ((look_for_explicit ? explicit_conv : implicit_conv).Lookup (source_type, target_type, out r))
1119                                 return (MethodGroupExpr) r;
1120
1121                         mg1 = Expression.MethodLookup (ec, source_type, op_name, loc);
1122                         if (source_type.BaseType != null)
1123                                 mg2 = Expression.MethodLookup (ec, source_type.BaseType, op_name, loc);
1124
1125                         if (mg1 == null)
1126                                 union3 = (MethodGroupExpr) mg2;
1127                         else if (mg2 == null)
1128                                 union3 = (MethodGroupExpr) mg1;
1129                         else
1130                                 union3 = Invocation.MakeUnionSet (mg1, mg2, loc);
1131
1132                         mg1 = Expression.MethodLookup (ec, target_type, op_name, loc);
1133                         if (mg1 != null){
1134                                 if (union3 != null)
1135                                         union3 = Invocation.MakeUnionSet (union3, mg1, loc);
1136                                 else
1137                                         union3 = (MethodGroupExpr) mg1;
1138                         }
1139
1140                         if (target_type.BaseType != null)
1141                                 mg1 = Expression.MethodLookup (ec, target_type.BaseType, op_name, loc);
1142                         
1143                         if (mg1 != null){
1144                                 if (union3 != null)
1145                                         union3 = Invocation.MakeUnionSet (union3, mg1, loc);
1146                                 else
1147                                         union3 = (MethodGroupExpr) mg1;
1148                         }
1149
1150                         MethodGroupExpr union4 = null;
1151
1152                         if (look_for_explicit) {
1153                                 op_name = "op_Explicit";
1154
1155                                 mg5 = Expression.MemberLookup (ec, source_type, op_name, loc);
1156                                 if (source_type.BaseType != null)
1157                                         mg6 = Expression.MethodLookup (ec, source_type.BaseType, op_name, loc);
1158                                 
1159                                 mg7 = Expression.MemberLookup (ec, target_type, op_name, loc);
1160                                 if (target_type.BaseType != null)
1161                                         mg8 = Expression.MethodLookup (ec, target_type.BaseType, op_name, loc);
1162                                 
1163                                 MethodGroupExpr union5 = Invocation.MakeUnionSet (mg5, mg6, loc);
1164                                 MethodGroupExpr union6 = Invocation.MakeUnionSet (mg7, mg8, loc);
1165
1166                                 union4 = Invocation.MakeUnionSet (union5, union6, loc);
1167                         }
1168                         
1169                         MethodGroupExpr ret = Invocation.MakeUnionSet (union3, union4, loc);
1170                         (look_for_explicit ? explicit_conv : implicit_conv).Insert (source_type, target_type, ret);
1171                         return ret;
1172                 }
1173                 
1174                 /// <summary>
1175                 ///   User-defined conversions
1176                 /// </summary>
1177
1178                 //
1179                 // VB.NET has no notion of User defined conversions. This method is not used.
1180                 //
1181                 static public Expression UserDefinedConversion (EmitContext ec, Expression source,
1182                                                                 Type target, Location loc,
1183                                                                 bool look_for_explicit)
1184                 {
1185                         MethodGroupExpr union;
1186                         Type source_type = source.Type;
1187                         MethodBase method = null;
1188
1189                         if (TypeManager.IsNullableType (source_type) && TypeManager.IsNullableType (target))
1190                                 return new Nullable.LiftedConversion (
1191                                         source, target, true, look_for_explicit, loc).Resolve (ec);
1192
1193                         union = GetConversionOperators (ec, source_type, target, loc, look_for_explicit);
1194                         if (union == null)
1195                                 return null;
1196                         
1197                         Type most_specific_source, most_specific_target;
1198
1199                         most_specific_source = FindMostSpecificSource (ec, union, source, look_for_explicit, loc);
1200                         if (most_specific_source == null)
1201                                 return null;
1202
1203                         most_specific_target = FindMostSpecificTarget (ec, union, target, look_for_explicit, loc);
1204                         if (most_specific_target == null) 
1205                                 return null;
1206
1207                         int count = 0;
1208
1209                         
1210                         foreach (MethodBase mb in union.Methods){
1211                                 ParameterData pd = Invocation.GetParameterData (mb);
1212                                 MethodInfo mi = (MethodInfo) mb;
1213                                 
1214                                 if (pd.ParameterType (0) == most_specific_source &&
1215                                     mi.ReturnType == most_specific_target) {
1216                                         method = mb;
1217                                         count++;
1218                                 }
1219                         }
1220                         
1221                         if (method == null || count > 1)
1222                                 return null;
1223                         
1224                         
1225                         //
1226                         // This will do the conversion to the best match that we
1227                         // found.  Now we need to perform an implict standard conversion
1228                         // if the best match was not the type that we were requested
1229                         // by target.
1230                         //
1231                         if (look_for_explicit)
1232                                 source = WideningAndNarrowingConversionStandard (ec, source, most_specific_source, loc);
1233                         else
1234                                 source = WideningConversionStandard (ec, source, most_specific_source, loc);
1235
1236                         if (source == null)
1237                                 return null;
1238
1239                         Expression e;
1240                         e =  new UserCast ((MethodInfo) method, source, loc);
1241                         if (e.Type != target){
1242                                 if (!look_for_explicit)
1243                                         e = WideningConversionStandard (ec, e, target, loc);
1244                                 else
1245                                         e = WideningAndNarrowingConversionStandard (ec, e, target, loc);
1246                         }
1247
1248                         return e;
1249                 }
1250                 
1251                 /// <summary>
1252                 ///   Converts implicitly the resolved expression `expr' into the
1253                 ///   `target_type'.  It returns a new expression that can be used
1254                 ///   in a context that expects a `target_type'. 
1255                 /// </summary>
1256                 static public Expression WideningConversion (EmitContext ec, Expression expr,
1257                                                              Type target_type, Location loc)
1258                 {
1259                         Expression e;
1260
1261                         if (target_type == null)
1262                                 throw new Exception ("Target type is null");
1263
1264                         e = WideningConversionStandard (ec, expr, target_type, loc);
1265                         if (e != null)
1266                                 return e;
1267
1268                         //
1269                         // VB.NET has no notion of User defined conversions
1270                         //
1271
1272 //                      e = ImplicitUserConversion (ec, expr, target_type, loc);
1273 //                      if (e != null)
1274 //                              return e;
1275
1276                         return null;
1277                 }
1278
1279                 
1280                 /// <summary>
1281                 ///   Attempts to apply the `Standard Implicit
1282                 ///   Conversion' rules to the expression `expr' into
1283                 ///   the `target_type'.  It returns a new expression
1284                 ///   that can be used in a context that expects a
1285                 ///   `target_type'.
1286                 ///
1287                 ///   This is different from `WideningConversion' in that the
1288                 ///   user defined implicit conversions are excluded. 
1289                 /// </summary>
1290                 static public Expression WideningConversionStandard (EmitContext ec, Expression expr,
1291                                                                      Type target_type, Location loc)
1292                 {
1293                         Type expr_type = expr.Type;
1294                         Expression e;
1295
1296                         if (expr is NullLiteral) {
1297                                 if (target_type.IsGenericParameter)
1298                                         return TypeParameter_to_Null (expr, target_type, loc);
1299
1300                                 if (TypeManager.IsNullableType (target_type))
1301                                         return new Nullable.NullableLiteral (target_type, loc);
1302                         }
1303
1304                         if (TypeManager.IsNullableType (expr_type) && TypeManager.IsNullableType (target_type))
1305                                 return new Nullable.LiftedConversion (
1306                                         expr, target_type, false, false, loc).Resolve (ec);
1307
1308                         if (expr.eclass == ExprClass.MethodGroup){
1309                                 if (!TypeManager.IsDelegateType (target_type)){
1310                                         return null;
1311                                 }
1312
1313                                 //
1314                                 // Only allow anonymous method conversions on post ISO_1
1315                                 //
1316                                 if (RootContext.Version != LanguageVersion.ISO_1){
1317                                         MethodGroupExpr mg = expr as MethodGroupExpr;
1318                                         if (mg != null)
1319                                                 return ImplicitDelegateCreation.Create (ec, mg, target_type, loc);
1320                                 }
1321                         }
1322
1323                         if (expr_type.Equals (target_type) && !TypeManager.IsNullType (expr_type))
1324                                 return expr;
1325
1326                         e = WideningNumericConversion (ec, expr, target_type, loc);
1327                         if (e != null)
1328                                 return e;
1329
1330                         e = WideningReferenceConversion (ec, expr, target_type);
1331                         if (e != null)
1332                                 return e;
1333                         
1334                         if ((target_type == TypeManager.enum_type ||
1335                              target_type.IsSubclassOf (TypeManager.enum_type)) &&
1336                             expr is IntLiteral){
1337                                 IntLiteral i = (IntLiteral) expr;
1338
1339                                 if (i.Value == 0)
1340                                         return new EnumConstant ((Constant) expr, target_type);
1341                         }
1342
1343                         if (ec.InUnsafe) {
1344                                 if (expr_type.IsPointer){
1345                                         if (target_type == TypeManager.void_ptr_type)
1346                                                 return new EmptyCast (expr, target_type);
1347
1348                                         //
1349                                         // yep, comparing pointer types cant be done with
1350                                         // t1 == t2, we have to compare their element types.
1351                                         //
1352                                         if (target_type.IsPointer){
1353                                                 if (TypeManager.GetElementType(target_type) == TypeManager.GetElementType(expr_type))
1354                                                         return expr;
1355                                         }
1356                                 }
1357                                 
1358                                 if (target_type.IsPointer) {
1359                                         if (expr_type == TypeManager.null_type)
1360                                                 return new EmptyCast (expr, target_type);
1361
1362                                         if (expr_type == TypeManager.void_ptr_type)
1363                                                 return new EmptyCast (expr, target_type);
1364                                 }
1365                         }
1366
1367                         if (expr_type == TypeManager.anonymous_method_type){
1368                                 if (!TypeManager.IsDelegateType (target_type)){
1369                                         Report.Error (1660, loc,
1370                                                               "Cannot convert anonymous method to `{0}', since it is not a delegate",
1371                                                               TypeManager.CSharpName (target_type));
1372                                         return null;
1373                                 }
1374
1375                                 AnonymousMethod am = (AnonymousMethod) expr;
1376                                 int errors = Report.Errors;
1377
1378                                 Expression conv = am.Compatible (ec, target_type, false);
1379                                 if (conv != null)
1380                                         return conv;
1381                                 
1382                                 //
1383                                 // We return something instead of null, to avoid
1384                                 // the duplicate error, since am.Compatible would have
1385                                 // reported that already
1386                                 //
1387                                 if (errors != Report.Errors)
1388                                         return new EmptyCast (expr, target_type);
1389                         }
1390
1391                         //
1392                         // VB.NET specific conversions
1393                         //
1394
1395                         e = WideningStringConversions (ec, expr, target_type, loc);
1396                         if (e != null)
1397                                 return e;
1398
1399                         
1400                         return null;
1401                 }
1402
1403                 /// <summary>
1404                 ///   Attempts to perform an implicit constant conversion of the IntConstant
1405                 ///   into a different data type using casts (See Implicit Constant
1406                 ///   Expression Conversions)
1407                 /// </summary>
1408                 static public Expression TryWideningIntConversion (Type target_type, IntConstant ic)
1409                 {
1410                         int value = ic.Value;
1411
1412                         if (target_type == TypeManager.sbyte_type){
1413                                 if (value >= SByte.MinValue && value <= SByte.MaxValue)
1414                                         return new SByteConstant ((sbyte) value);
1415                         } else if (target_type == TypeManager.byte_type){
1416                                 if (value >= Byte.MinValue && value <= Byte.MaxValue)
1417                                         return new ByteConstant ((byte) value);
1418                         } else if (target_type == TypeManager.short_type){
1419                                 if (value >= Int16.MinValue && value <= Int16.MaxValue)
1420                                         return new ShortConstant ((short) value);
1421                         } else if (target_type == TypeManager.ushort_type){
1422                                 if (value >= UInt16.MinValue && value <= UInt16.MaxValue)
1423                                         return new UShortConstant ((ushort) value);
1424                         } else if (target_type == TypeManager.uint32_type){
1425                                 if (value >= 0)
1426                                         return new UIntConstant ((uint) value);
1427                         } else if (target_type == TypeManager.uint64_type){
1428                                 //
1429                                 // we can optimize this case: a positive int32
1430                                 // always fits on a uint64.  But we need an opcode
1431                                 // to do it.
1432                                 //
1433                                 if (value >= 0)
1434                                         return new ULongConstant ((ulong) value);
1435                         } else if (target_type == TypeManager.double_type)
1436                                 return new DoubleConstant ((double) value);
1437                         else if (target_type == TypeManager.float_type)
1438                                 return new FloatConstant ((float) value);
1439                         
1440                         if (value == 0 && ic is IntLiteral && TypeManager.IsEnumType (target_type)){
1441                                 Type underlying = TypeManager.EnumToUnderlying (target_type);
1442                                 Constant e = (Constant) ic;
1443                                 
1444                                 //
1445                                 // Possibly, we need to create a different 0 literal before passing
1446                                 // to EnumConstant
1447                                 //
1448                                 if (underlying == TypeManager.int64_type)
1449                                         e = new LongLiteral (0);
1450                                 else if (underlying == TypeManager.uint64_type)
1451                                         e = new ULongLiteral (0);
1452
1453                                 return new EnumConstant (e, target_type);
1454                         }
1455
1456                         //
1457                         // If `target_type' is an interface and the type of `ic' implements the interface
1458                         // e.g. target_type is IComparable, IConvertible, IFormattable
1459                         //
1460                         if (target_type.IsInterface && target_type.IsAssignableFrom (ic.Type))
1461                                 return new BoxedCast (ic);
1462
1463                         return null;
1464                 }
1465
1466                 static public void Error_CannotWideningConversion (Location loc, Type source, Type target)
1467                 {
1468                         if (source.Name == target.Name){
1469                                 Report.ExtraInformation (loc,
1470                                          String.Format (
1471                                                 "The type {0} has two conflicting definitons, one comes from {0} and the other from {1}",
1472                                                 source.Assembly.FullName, target.Assembly.FullName));
1473                                                          
1474                         }
1475                         Report.Error (29, loc, "Cannot convert implicitly from {0} to `{1}'",
1476                                       source == TypeManager.anonymous_method_type ?
1477                                       "anonymous method" : "`" + TypeManager.CSharpName (source) + "'",
1478                                       TypeManager.CSharpName (target));
1479                 }
1480
1481                 /// <summary>
1482                 ///   Attempts to implicitly convert `source' into `target_type', using
1483                 ///   WideningConversion.  If there is no implicit conversion, then
1484                 ///   an error is signaled
1485                 /// </summary>
1486                 static public Expression WideningConversionRequired (EmitContext ec, Expression source,
1487                                                                      Type target_type, Location loc)
1488                 {
1489                         Expression e;
1490
1491                         int errors = Report.Errors;
1492                         e = WideningConversion (ec, source, target_type, loc);
1493                         if (Report.Errors > errors)
1494                                 return null;
1495                         if (e != null)
1496                                 return e;
1497
1498                         if (source is DoubleLiteral) {
1499                                 if (target_type == TypeManager.float_type) {
1500                                         Error_664 (loc, "float", "f");
1501                                         return null;
1502                                 }
1503                                 if (target_type == TypeManager.decimal_type) {
1504                                         Error_664 (loc, "decimal", "m");
1505                                         return null;
1506                                 }
1507                         }
1508
1509                         if (source is Constant){
1510                                 Constant c = (Constant) source;
1511
1512                                 Expression.Error_ConstantValueCannotBeConverted (loc, c.AsString (), target_type);
1513                                 return null;
1514                         }
1515                         
1516                         Error_CannotWideningConversion (loc, source.Type, target_type);
1517
1518                         return null;
1519                 }
1520
1521                 static void Error_664 (Location loc, string type, string suffix) {
1522                         Report.Error (664, loc,
1523                                 "Literal of type double cannot be implicitly converted to type '{0}'. Add suffix '{1}' to create a literal of this type",
1524                                 type, suffix);
1525                 }
1526
1527                 /// <summary>
1528                 ///   Performs the explicit numeric conversions
1529                 /// </summary>
1530
1531                 /// <summary>
1532                 ///   Performs the explicit numeric conversions
1533                 /// </summary>
1534                 static Expression NarrowingNumericConversion (EmitContext ec, Expression expr, Type target_type, Location loc)
1535                 {
1536                         Type expr_type = expr.Type;
1537
1538                         //
1539                         // If we have an enumeration, extract the underlying type,
1540                         // use this during the comparison, but wrap around the original
1541                         // target_type
1542                         //
1543                         Type real_target_type = target_type;
1544
1545                         if (TypeManager.IsEnumType (real_target_type))
1546                                 real_target_type = TypeManager.EnumToUnderlying (real_target_type);
1547
1548                         if (WideningStandardConversionExists (ec, expr, real_target_type)){
1549                                 Expression ce = WideningConversionStandard (ec, expr, real_target_type, loc);
1550
1551                                 if (real_target_type != target_type)
1552                                         return new EmptyCast (ce, target_type);
1553                                 return ce;
1554                         }
1555                         
1556                         if (expr_type == TypeManager.sbyte_type){
1557                                 //
1558                                 // From sbyte to byte, ushort, uint, ulong, char
1559                                 //
1560                                 if (real_target_type == TypeManager.byte_type)
1561                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.I1_U1);
1562                                 if (real_target_type == TypeManager.ushort_type)
1563                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.I1_U2);
1564                                 if (real_target_type == TypeManager.uint32_type)
1565                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.I1_U4);
1566                                 if (real_target_type == TypeManager.uint64_type)
1567                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.I1_U8);
1568                                 if (real_target_type == TypeManager.char_type)
1569                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.I1_CH);
1570                         } else if (expr_type == TypeManager.byte_type){
1571                                 //
1572                                 // From byte to sbyte and char
1573                                 //
1574                                 if (real_target_type == TypeManager.sbyte_type)
1575                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.U1_I1);
1576                         } else if (expr_type == TypeManager.short_type){
1577                                 //
1578                                 // From short to byte
1579                                 //
1580                                 if (real_target_type == TypeManager.sbyte_type)
1581                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.I2_I1);
1582                                 if (real_target_type == TypeManager.byte_type)
1583                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.I2_U1);
1584                                 if (real_target_type == TypeManager.ushort_type)
1585                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.I2_U2);
1586                                 if (real_target_type == TypeManager.uint32_type)
1587                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.I2_U4);
1588                                 if (real_target_type == TypeManager.uint64_type)
1589                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.I2_U8);
1590                         } else if (expr_type == TypeManager.ushort_type){
1591                                 //
1592                                 // From ushort to sbyte, byte, short, char
1593                                 //
1594                                 if (real_target_type == TypeManager.sbyte_type)
1595                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.U2_I1);
1596                                 if (real_target_type == TypeManager.byte_type)
1597                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.U2_U1);
1598                                 if (real_target_type == TypeManager.short_type)
1599                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.U2_I2);
1600                                 if (real_target_type == TypeManager.char_type)
1601                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.U2_CH);
1602                         } else if (expr_type == TypeManager.int32_type){
1603                                 //
1604                                 // From int to byte, short
1605                                 //
1606                                 if (real_target_type == TypeManager.sbyte_type)
1607                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.I4_I1);
1608                                 if (real_target_type == TypeManager.byte_type)
1609                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.I4_U1);
1610                                 if (real_target_type == TypeManager.short_type)
1611                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.I4_I2);
1612                                 if (real_target_type == TypeManager.ushort_type)
1613                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.I4_U2);
1614                                 if (real_target_type == TypeManager.uint32_type)
1615                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.I4_U4);
1616                                 if (real_target_type == TypeManager.uint64_type)
1617                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.I4_U8);
1618                         } else if (expr_type == TypeManager.uint32_type){
1619                                 //
1620                                 // From uint to sbyte, byte, short, ushort, int, char
1621                                 //
1622                                 if (real_target_type == TypeManager.sbyte_type)
1623                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.U4_I1);
1624                                 if (real_target_type == TypeManager.byte_type)
1625                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.U4_U1);
1626                                 if (real_target_type == TypeManager.short_type)
1627                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.U4_I2);
1628                                 if (real_target_type == TypeManager.ushort_type)
1629                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.U4_U2);
1630                                 if (real_target_type == TypeManager.int32_type)
1631                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.U4_I4);
1632                                 if (real_target_type == TypeManager.char_type)
1633                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.U4_CH);
1634                         } else if (expr_type == TypeManager.int64_type){
1635                                 //
1636                                 // From long to byte, short, int
1637                                 //
1638                                 if (real_target_type == TypeManager.sbyte_type)
1639                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.I8_I1);
1640                                 if (real_target_type == TypeManager.byte_type)
1641                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.I8_U1);
1642                                 if (real_target_type == TypeManager.short_type)
1643                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.I8_I2);
1644                                 if (real_target_type == TypeManager.ushort_type)
1645                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.I8_U2);
1646                                 if (real_target_type == TypeManager.int32_type)
1647                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.I8_I4);
1648                                 if (real_target_type == TypeManager.uint32_type)
1649                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.I8_U4);
1650                                 if (real_target_type == TypeManager.uint64_type)
1651                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.I8_U8);
1652                         } else if (expr_type == TypeManager.uint64_type){
1653                                 //
1654                                 // From ulong to sbyte, byte, short, ushort, int, uint, long, char
1655                                 //
1656                                 if (real_target_type == TypeManager.sbyte_type)
1657                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.U8_I1);
1658                                 if (real_target_type == TypeManager.byte_type)
1659                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.U8_U1);
1660                                 if (real_target_type == TypeManager.short_type)
1661                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.U8_I2);
1662                                 if (real_target_type == TypeManager.ushort_type)
1663                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.U8_U2);
1664                                 if (real_target_type == TypeManager.int32_type)
1665                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.U8_I4);
1666                                 if (real_target_type == TypeManager.uint32_type)
1667                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.U8_U4);
1668                                 if (real_target_type == TypeManager.int64_type)
1669                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.U8_I8);
1670                                 if (real_target_type == TypeManager.char_type)
1671                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.U8_CH);
1672                         } else if (expr_type == TypeManager.float_type){
1673                                 //
1674                                 // From float to byte, short, int, long, decimal
1675                                 //
1676                                 if (real_target_type == TypeManager.sbyte_type)
1677                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.R4_I1);
1678                                 if (real_target_type == TypeManager.byte_type)
1679                                         return new FloatingToFixedCast (ec, expr, target_type, ConvCast.Mode.R8_U1);
1680                                 if (real_target_type == TypeManager.short_type)
1681                                         return new FloatingToFixedCast (ec, expr, target_type, ConvCast.Mode.R8_I2);
1682                                 if (real_target_type == TypeManager.ushort_type)
1683                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.R4_U2);
1684                                 if (real_target_type == TypeManager.int32_type)
1685                                         return new FloatingToFixedCast (ec, expr, target_type, ConvCast.Mode.R8_I4);
1686                                 if (real_target_type == TypeManager.uint32_type)
1687                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.R4_U4);
1688                                 if (real_target_type == TypeManager.int64_type)
1689                                         return new FloatingToFixedCast (ec, expr, target_type, ConvCast.Mode.R8_I8);
1690                                 if (real_target_type == TypeManager.uint64_type)
1691                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.R4_U8);
1692                                 if (real_target_type == TypeManager.decimal_type)
1693                                         return new ImplicitNew (ec, "System", "Decimal", loc, expr);    
1694                         } else if (expr_type == TypeManager.double_type){
1695                                 //
1696                                 // From double to byte, short, int, long, float, decimal
1697                                 //
1698                                 if (real_target_type == TypeManager.sbyte_type)
1699                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.R8_I1);
1700                                 if (real_target_type == TypeManager.byte_type)
1701                                         return new FloatingToFixedCast (ec, expr, target_type, ConvCast.Mode.R8_U1);
1702                                 if (real_target_type == TypeManager.short_type)
1703                                         return new FloatingToFixedCast (ec, expr, target_type, ConvCast.Mode.R8_I2);
1704                                 if (real_target_type == TypeManager.ushort_type)
1705                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.R8_U2);
1706                                 if (real_target_type == TypeManager.int32_type)
1707                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.R8_I4);
1708                                 if (real_target_type == TypeManager.uint32_type)
1709                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.R8_U4);
1710                                 if (real_target_type == TypeManager.int64_type)
1711                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.R8_I8);
1712                                 if (real_target_type == TypeManager.uint64_type)
1713                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.R8_U8);
1714
1715                                 if (real_target_type == TypeManager.float_type)
1716                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.R8_R4);
1717                                 if (real_target_type == TypeManager.decimal_type)
1718                                         return new ImplicitNew (ec, "System", "Decimal", loc, expr);
1719                         } else if (expr_type == TypeManager.decimal_type){
1720                                 //
1721                                 // From decimal to byte, short, int, long
1722                                 //
1723                                 if (real_target_type == TypeManager.byte_type)
1724                                         return new ImplicitInvocation (ec, "System", "Convert" , "ToByte", loc, expr);  
1725                                 if (real_target_type == TypeManager.short_type)
1726                                         return new ImplicitInvocation (ec, "System", "Convert", "ToInt16", loc, expr);  
1727                                 if (real_target_type == TypeManager.int32_type)
1728                                         return new ImplicitInvocation (ec, "System", "Convert", "ToInt32", loc, expr);  
1729                                 if (real_target_type == TypeManager.int64_type)
1730                                         return new ImplicitInvocation (ec, "System", "Convert", "ToInt64", loc, expr);  
1731                         } 
1732
1733                         return null;
1734                 }
1735
1736                 /// <summary> 
1737                 /// VB.NET specific: Convert to and from boolean
1738                 /// </summary>
1739
1740                 static public Expression BooleanConversions (EmitContext ec, Expression expr,
1741                                                                     Type target_type, Location loc)
1742                 {
1743                         Type expr_type = expr.Type;
1744                         Type real_target_type = target_type;
1745
1746                         if (expr_type == TypeManager.bool_type) {
1747
1748                                 //
1749                                 // From boolean to byte, short, int,
1750                                 // long, float, double, decimal
1751                                 //
1752
1753                                 if (real_target_type == TypeManager.byte_type)
1754                                         return new BooleanToNumericCast (expr, target_type, OpCodes.Conv_U1);
1755                                 if (real_target_type == TypeManager.short_type)
1756                                         return new BooleanToNumericCast (expr, target_type, OpCodes.Conv_I2);
1757                                 if (real_target_type == TypeManager.int32_type)
1758                                         return new BooleanToNumericCast (expr, target_type, OpCodes.Conv_I4);
1759                                 if (real_target_type == TypeManager.int64_type)
1760                                         return new BooleanToNumericCast (expr, target_type, OpCodes.Conv_I8);
1761                                 if (real_target_type == TypeManager.float_type)
1762                                         return new BooleanToNumericCast (expr, target_type, OpCodes.Conv_R4);
1763                                 if (real_target_type == TypeManager.double_type)
1764                                         return new BooleanToNumericCast (expr, target_type, OpCodes.Conv_R8);
1765                                 if (real_target_type == TypeManager.decimal_type) {
1766                                         return new ImplicitInvocation (ec, "DecimalType", "FromBoolean", loc, expr);
1767                                 }
1768                         } if (real_target_type == TypeManager.bool_type) {
1769
1770                                 //
1771                                 // From byte, short, int, long, float,
1772                                 // double, decimal to boolean
1773                                 //
1774
1775                                 if (expr_type == TypeManager.byte_type ||
1776                                         expr_type == TypeManager.short_type ||
1777                                         expr_type == TypeManager.int32_type ||
1778                                         expr_type == TypeManager.int64_type || 
1779                                         expr_type == TypeManager.float_type || 
1780                                         expr_type == TypeManager.double_type)
1781                                                 return new NumericToBooleanCast (expr, expr_type);
1782                                 if (expr_type == TypeManager.decimal_type) {
1783                                         return new ImplicitInvocation (ec, "System", "Convert", "ToBoolean", loc, expr);
1784                                 }
1785                         }
1786
1787                         return null;
1788                 }
1789
1790                 /// <summary> 
1791                 /// VB.NET specific: Widening conversions to string
1792                 /// </summary>
1793
1794                 static public Expression WideningStringConversions (EmitContext ec, Expression expr,
1795                                                                     Type target_type, Location loc)
1796
1797                 {
1798                         Type expr_type = expr.Type;
1799                         Type real_target_type = target_type;
1800
1801                         if (real_target_type == TypeManager.string_type) {
1802                                 //
1803                                 // From char to string
1804                                 //
1805                                 if (expr_type == TypeManager.char_type)
1806                                         return new ImplicitInvocation (ec, "StringType", "FromChar", loc, expr);
1807                         }
1808
1809                         if(expr_type.IsArray && (expr_type.GetElementType() == TypeManager.char_type)) {
1810                                 //
1811                                 // From char array to string
1812                                 //
1813                                 return new ImplicitNew (ec, "System", "String", loc, expr);
1814                         }
1815
1816                         return null;
1817                 }
1818                 
1819                 /// <summary> 
1820                 /// VB.NET specific: Narrowing conversions involving strings
1821                 /// </summary>
1822
1823                 static public Expression NarrowingStringConversions (EmitContext ec, Expression expr,
1824                                                                     Type target_type, Location loc)
1825                 {
1826                         Type expr_type = expr.Type;
1827                         Type real_target_type = target_type;
1828
1829                         // FIXME: Need to take care of Constants
1830
1831                         if (expr_type == TypeManager.string_type) {
1832
1833                                 //
1834                                 // From string to chararray, bool,
1835                                 // byte, short, char, int, long,
1836                                 // float, double, decimal and date 
1837                                 //
1838
1839                                 if (real_target_type.IsArray && (real_target_type.GetElementType() == TypeManager.char_type))
1840                                         return new ImplicitInvocation (ec, "CharArrayType", "FromString", loc, expr);
1841                                 if (real_target_type == TypeManager.bool_type)
1842                                         return new ImplicitInvocation (ec, "BooleanType", "FromString", loc, expr);
1843                                 if (real_target_type == TypeManager.byte_type)
1844                                         return new ImplicitInvocation (ec, "ByteType", "FromString", loc, expr);
1845                                 if (real_target_type == TypeManager.short_type)
1846                                         return new ImplicitInvocation (ec, "ShortType", "FromString", loc, expr);
1847                                 if (real_target_type == TypeManager.char_type)
1848                                         return new ImplicitInvocation (ec, "CharType", "FromString", loc, expr);
1849                                 if (real_target_type == TypeManager.int32_type)
1850                                         return new ImplicitInvocation (ec, "IntegerType", "FromString", loc, expr);
1851                                 if (real_target_type == TypeManager.int64_type)
1852                                         return new ImplicitInvocation (ec, "LongType", "FromString", loc, expr);
1853                                 if (real_target_type == TypeManager.float_type)
1854                                         return new ImplicitInvocation (ec, "SingleType", "FromString", loc, expr);
1855                                 if (real_target_type == TypeManager.double_type)
1856                                         return new ImplicitInvocation (ec, "DoubleType", "FromString", loc, expr);
1857                                 if (real_target_type == TypeManager.decimal_type)
1858                                         return new ImplicitInvocation (ec, "DecimalType", "FromString", loc, expr);
1859                                 if (real_target_type == TypeManager.date_type)
1860                                         return new ImplicitInvocation (ec, "DateType", "FromString", loc, expr);
1861                         } if (real_target_type == TypeManager.string_type) {
1862
1863                                 //
1864                                 // From bool, byte, short, char, int,
1865                                 // long, float, double, decimal and
1866                                 // date to string
1867                                 //
1868
1869                                 if (expr_type == TypeManager.bool_type)
1870                                         return new ImplicitInvocation (ec, "StringType", "FromBoolean", loc, expr);
1871                                 if (expr_type == TypeManager.byte_type)
1872                                         return new ImplicitInvocation (ec, "StringType", "FromByte", loc, expr);
1873                                 if (expr_type == TypeManager.short_type)
1874                                         return new ImplicitInvocation (ec, "StringType", "FromShort", loc, expr);
1875                                 if (expr_type == TypeManager.int32_type)
1876                                         return new ImplicitInvocation (ec, "StringType", "FromInteger", loc, expr);
1877                                 if (expr_type == TypeManager.int64_type)
1878                                         return new ImplicitInvocation (ec, "StringType", "FromLong", loc, expr);
1879                                 if (expr_type == TypeManager.float_type)
1880                                         return new ImplicitInvocation (ec, "StringType", "FromSingle", loc, expr);
1881                                 if (expr_type == TypeManager.double_type)
1882                                         return new ImplicitInvocation (ec, "StringType", "FromDouble", loc, expr);
1883                                 if (expr_type == TypeManager.decimal_type)
1884                                         return new ImplicitInvocation (ec, "StringType", "FromDecimal", loc, expr);
1885                                 if (expr_type == TypeManager.date_type)
1886                                         return new ImplicitInvocation (ec, "StringType", "FromDate", loc, expr);
1887                         }
1888
1889                         return null;
1890                 }
1891
1892                 /// <summary>
1893                 ///  Returns whether an explicit reference conversion can be performed
1894                 ///  from source_type to target_type
1895                 /// </summary>
1896                 public static bool NarrowingReferenceConversionExists (Type source_type, Type target_type)
1897                 {
1898                         bool target_is_type_param = target_type.IsGenericParameter;
1899                         bool target_is_value_type = target_type.IsValueType;
1900                         
1901                         if (source_type == target_type)
1902                                 return true;
1903                         
1904                         //
1905                         // From generic parameter to any type
1906                         //
1907                         if (source_type.IsGenericParameter)
1908                                 return true;
1909
1910                         //
1911                         // From object to a generic parameter
1912                         //
1913                         if (source_type == TypeManager.object_type && target_is_type_param)
1914                                 return true;
1915
1916                         //
1917                         // From object to any reference type
1918                         //
1919                         if (source_type == TypeManager.object_type && !target_is_value_type)
1920                                 return true;
1921                                         
1922                         //
1923                         // From any class S to any class-type T, provided S is a base class of T
1924                         //
1925                         if (TypeManager.IsSubclassOf (target_type, source_type))
1926                                 return true;
1927
1928                         //
1929                         // From any interface type S to any interface T provided S is not derived from T
1930                         //
1931                         if (source_type.IsInterface && target_type.IsInterface){
1932                                 if (!TypeManager.IsSubclassOf (target_type, source_type))
1933                                         return true;
1934                         }
1935                             
1936                         //
1937                         // From any class type S to any interface T, provided S is not sealed
1938                         // and provided S does not implement T.
1939                         //
1940                         if (target_type.IsInterface && !source_type.IsSealed &&
1941                             !TypeManager.ImplementsInterface (source_type, target_type))
1942                                 return true;
1943
1944                         //
1945                         // From any interface-type S to to any class type T, provided T is not
1946                         // sealed, or provided T implements S.
1947                         //
1948                         if (source_type.IsInterface &&
1949                             (!target_type.IsSealed || TypeManager.ImplementsInterface (target_type, source_type)))
1950                                 return true;
1951                         
1952                         
1953                         // From an array type S with an element type Se to an array type T with an 
1954                         // element type Te provided all the following are true:
1955                         //     * S and T differe only in element type, in other words, S and T
1956                         //       have the same number of dimensions.
1957                         //     * Both Se and Te are reference types
1958                         //     * An explicit referenc conversions exist from Se to Te
1959                         //
1960                         if (source_type.IsArray && target_type.IsArray) {
1961                                 if (source_type.GetArrayRank () == target_type.GetArrayRank ()) {
1962                                         
1963                                         Type source_element_type = TypeManager.GetElementType (source_type);
1964                                         Type target_element_type = TypeManager.GetElementType (target_type);
1965
1966                                         if (source_element_type.IsGenericParameter ||
1967                                             (!source_element_type.IsValueType && !target_element_type.IsValueType))
1968                                                 if (NarrowingReferenceConversionExists (source_element_type,
1969                                                                                        target_element_type))
1970                                                         return true;
1971                                 }
1972                         }
1973                         
1974
1975                         // From System.Array to any array-type
1976                         if (source_type == TypeManager.array_type &&
1977                             target_type.IsArray){
1978                                 return true;
1979                         }
1980
1981                         //
1982                         // From System delegate to any delegate-type
1983                         //
1984                         if (source_type == TypeManager.delegate_type &&
1985                             TypeManager.IsDelegateType (target_type))
1986                                 return true;
1987
1988                         //
1989                         // From ICloneable to Array or Delegate types
1990                         //
1991                         if (source_type == TypeManager.icloneable_type &&
1992                             (target_type == TypeManager.array_type ||
1993                              target_type == TypeManager.delegate_type))
1994                                 return true;
1995                         
1996                         return false;
1997                 }
1998
1999                 /// <summary>
2000                 ///   Implements Explicit Reference conversions
2001                 /// </summary>
2002                 static Expression NarrowingReferenceConversion (Expression source, Type target_type)
2003                 {
2004                         Type source_type = source.Type;
2005                         bool target_is_type_param = target_type.IsGenericParameter;
2006                         bool target_is_value_type = target_type.IsValueType;
2007
2008                         //
2009                         // From object to a generic parameter
2010                         //
2011                         if (source_type == TypeManager.object_type && target_is_type_param)
2012                                 return new UnboxCast (source, target_type);
2013
2014                         //
2015                         // From object to any reference type
2016                         //
2017                         if (source_type == TypeManager.object_type && !target_is_value_type)
2018                                 return new ClassCast (source, target_type);
2019
2020                         //
2021                         // Unboxing conversion.
2022                         //
2023                         if (((source_type == TypeManager.enum_type &&
2024                                 !(source is EmptyCast)) ||
2025                                 source_type == TypeManager.value_type) && target_is_value_type)
2026                                 return new UnboxCast (source, target_type);
2027
2028                         //
2029                         // From any class S to any class-type T, provided S is a base class of T
2030                         //
2031                         if (TypeManager.IsSubclassOf (target_type, source_type))
2032                                 return new ClassCast (source, target_type);
2033
2034                         //
2035                         // From any interface type S to any interface T provided S is not derived from T
2036                         //
2037                         if (source_type.IsInterface && target_type.IsInterface){
2038                                 if (TypeManager.ImplementsInterface (source_type, target_type))
2039                                         return null;
2040                                 else
2041                                         return new ClassCast (source, target_type);
2042                         }
2043
2044                         //
2045                         // From any class type S to any interface T, provides S is not sealed
2046                         // and provided S does not implement T.
2047                         //
2048                         if (target_type.IsInterface && !source_type.IsSealed) {
2049                                 if (TypeManager.ImplementsInterface (source_type, target_type))
2050                                         return null;
2051                                 else
2052                                         return new ClassCast (source, target_type);
2053                                 
2054                         }
2055
2056                         //
2057                         // From any interface-type S to to any class type T, provided T is not
2058                         // sealed, or provided T implements S.
2059                         //
2060                         if (source_type.IsInterface) {
2061                                 if (!target_type.IsSealed || TypeManager.ImplementsInterface (target_type, source_type)) {
2062                                         if (target_type.IsClass)
2063                                                 return new ClassCast (source, target_type);
2064                                         else
2065                                                 return new UnboxCast (source, target_type);
2066                                 }
2067
2068                                 return null;
2069                         }
2070                         
2071                         // From an array type S with an element type Se to an array type T with an 
2072                         // element type Te provided all the following are true:
2073                         //     * S and T differe only in element type, in other words, S and T
2074                         //       have the same number of dimensions.
2075                         //     * Both Se and Te are reference types
2076                         //     * An explicit referenc conversions exist from Se to Te
2077                         //
2078                         if (source_type.IsArray && target_type.IsArray) {
2079                                 if (source_type.GetArrayRank () == target_type.GetArrayRank ()) {
2080                                         
2081                                         Type source_element_type = TypeManager.GetElementType (source_type);
2082                                         Type target_element_type = TypeManager.GetElementType (target_type);
2083                                         
2084                                         if (!source_element_type.IsValueType && !target_element_type.IsValueType)
2085                                                 if (NarrowingReferenceConversionExists (source_element_type,
2086                                                                                        target_element_type))
2087                                                         return new ClassCast (source, target_type);
2088                                 }
2089                         }
2090                         
2091
2092                         // From System.Array to any array-type
2093                         if (source_type == TypeManager.array_type &&
2094                             target_type.IsArray) {
2095                                 return new ClassCast (source, target_type);
2096                         }
2097
2098                         //
2099                         // From System delegate to any delegate-type
2100                         //
2101                         if (source_type == TypeManager.delegate_type &&
2102                             TypeManager.IsDelegateType (target_type))
2103                                 return new ClassCast (source, target_type);
2104
2105                         //
2106                         // From ICloneable to Array or Delegate types
2107                         //
2108                         if (source_type == TypeManager.icloneable_type &&
2109                             (target_type == TypeManager.array_type ||
2110                              target_type == TypeManager.delegate_type))
2111                                 return new ClassCast (source, target_type);
2112                         
2113                         return null;
2114                 }
2115                 
2116                 /// <summary>
2117                 ///   Performs an explicit conversion of the expression `expr' whose
2118                 ///   type is expr.Type to `target_type'.
2119                 /// </summary>
2120                 static public Expression WideningAndNarrowingConversion (EmitContext ec, Expression expr,
2121                                                              Type target_type, Location loc)
2122                 {
2123                         Type expr_type = expr.Type;
2124                         Type original_expr_type = expr_type;
2125
2126                         if (expr_type.IsSubclassOf (TypeManager.enum_type)){
2127                                 if (target_type == TypeManager.enum_type ||
2128                                     target_type == TypeManager.object_type) {
2129                                         if (expr is EnumConstant)
2130                                                 expr = ((EnumConstant) expr).Child;
2131                                         // We really need all these casts here .... :-(
2132                                         expr = new BoxedCast (new EmptyCast (expr, expr_type));
2133                                         return new EmptyCast (expr, target_type);
2134                                 } else if ((expr_type == TypeManager.enum_type) && target_type.IsValueType &&
2135                                            target_type.IsSubclassOf (TypeManager.enum_type))
2136                                         return new UnboxCast (expr, target_type);
2137
2138                                 //
2139                                 // Notice that we have kept the expr_type unmodified, which is only
2140                                 // used later on to 
2141                                 if (expr is EnumConstant)
2142                                         expr = ((EnumConstant) expr).Child;
2143                                 else
2144                                         expr = new EmptyCast (expr, TypeManager.EnumToUnderlying (expr_type));
2145                                 expr_type = expr.Type;
2146                         }
2147
2148                         int errors = Report.Errors;
2149                         Expression ne = WideningConversionStandard (ec, expr, target_type, loc);
2150                         if (Report.Errors > errors)
2151                                 return null;
2152
2153                         if (ne != null)
2154                                 return ne;
2155
2156                         if (TypeManager.IsNullableType (expr.Type) && TypeManager.IsNullableType (target_type))
2157                                 return new Nullable.LiftedConversion (
2158                                         expr, target_type, false, true, loc).Resolve (ec);
2159
2160                         ne = NarrowingNumericConversion (ec, expr, target_type, loc);
2161                         if (ne != null)
2162                                 return ne;
2163
2164                         //
2165                         // Unboxing conversion.
2166                         //
2167                         if (expr_type == TypeManager.object_type && target_type.IsValueType)
2168                                 return new UnboxCast (expr, target_type);
2169
2170                         //
2171                         // Skip the NarrowingReferenceConversion because we can not convert
2172                         // from Null to a ValueType, and ExplicitReference wont check against
2173                         // null literal explicitly
2174                         //
2175                         if (expr_type != TypeManager.null_type){
2176                                 ne = NarrowingReferenceConversion (expr, target_type);
2177                                 if (ne != null)
2178                                         return ne;
2179                         }
2180
2181                 skip_explicit:
2182                         if (ec.InUnsafe){
2183                                 if (target_type.IsPointer){
2184                                         if (expr_type.IsPointer)
2185                                                 return new EmptyCast (expr, target_type);
2186                                         
2187                                         if (expr_type == TypeManager.sbyte_type ||
2188                                             expr_type == TypeManager.byte_type ||
2189                                             expr_type == TypeManager.short_type ||
2190                                             expr_type == TypeManager.ushort_type ||
2191                                             expr_type == TypeManager.int32_type ||
2192                                             expr_type == TypeManager.uint32_type ||
2193                                             expr_type == TypeManager.uint64_type ||
2194                                             expr_type == TypeManager.int64_type)
2195                                                 return new OpcodeCast (expr, target_type, OpCodes.Conv_U);
2196                                 }
2197                                 if (expr_type.IsPointer){
2198                                         Expression e = null;
2199                                         
2200                                         if (target_type == TypeManager.sbyte_type)
2201                                                 e = new OpcodeCast (expr, target_type, OpCodes.Conv_I1);
2202                                         else if (target_type == TypeManager.byte_type)
2203                                                 e = new OpcodeCast (expr, target_type, OpCodes.Conv_U1);
2204                                         else if (target_type == TypeManager.short_type)
2205                                                 e = new OpcodeCast (expr, target_type, OpCodes.Conv_I2);
2206                                         else if (target_type == TypeManager.ushort_type)
2207                                                 e = new OpcodeCast (expr, target_type, OpCodes.Conv_U2);
2208                                         else if (target_type == TypeManager.int32_type)
2209                                                 e = new OpcodeCast (expr, target_type, OpCodes.Conv_I4);
2210                                         else if (target_type == TypeManager.uint32_type)
2211                                                 e = new OpcodeCast (expr, target_type, OpCodes.Conv_U4);
2212                                         else if (target_type == TypeManager.uint64_type)
2213                                                 e = new OpcodeCast (expr, target_type, OpCodes.Conv_U8);
2214                                         else if (target_type == TypeManager.int64_type){
2215                                                 e = new OpcodeCast (expr, target_type, OpCodes.Conv_I8);
2216                                         }
2217
2218                                         if (e != null){
2219                                                 Expression ci, ce;
2220
2221                                                 ci = WideningConversionStandard (ec, e, target_type, loc);
2222
2223                                                 if (ci != null)
2224                                                         return ci;
2225
2226                                                 ce = NarrowingNumericConversion (ec, e, target_type, loc);
2227                                                 if (ce != null)
2228                                                         return ce;
2229                                                 //
2230                                                 // We should always be able to go from an uint32
2231                                                 // implicitly or explicitly to the other integral
2232                                                 // types
2233                                                 //
2234                                                 throw new Exception ("Internal compiler error");
2235                                         }
2236                                 }
2237                         }
2238
2239                         //
2240                         // VB.NET specific conversions
2241                         //
2242
2243                         ne = BooleanConversions (ec, expr, target_type, loc);
2244                         if (ne != null)
2245                                 return ne;
2246
2247                         ne = NarrowingStringConversions (ec, expr, target_type, loc);
2248                         if (ne != null)
2249                                 return ne;
2250                         
2251                         
2252                         //
2253                         // VB.NET has no notion of User defined conversions
2254                         //
2255
2256 //                      ne = ExplicitUserConversion (ec, expr, target_type, loc);
2257 //                      if (ne != null)
2258 //                              return ne;
2259
2260                         if (expr is NullLiteral){
2261                                 Report.Error (37, loc, "Cannot convert null to value type `" +
2262                                               TypeManager.CSharpName (target_type) + "'");
2263                                 return null;
2264                         }
2265                                 
2266                         Error_CannotConvertType (loc, original_expr_type, target_type);
2267                         return null;
2268                 }
2269
2270                 /// <summary>
2271                 ///   Same as WideningAndNarrowingConversion, only it doesn't include user defined conversions
2272                 /// </summary>
2273                 static public Expression WideningAndNarrowingConversionStandard (EmitContext ec, Expression expr,
2274                                                                      Type target_type, Location l)
2275                 {
2276                         int errors = Report.Errors;
2277                         Expression ne = WideningConversionStandard (ec, expr, target_type, l);
2278                         if (Report.Errors > errors)
2279                                 return null;
2280
2281                         if (ne != null)
2282                                 return ne;
2283
2284                         if (TypeManager.IsNullableType (expr.Type) && TypeManager.IsNullableType (target_type))
2285                                 return new Nullable.LiftedConversion (
2286                                         expr, target_type, false, true, l).Resolve (ec);
2287
2288                         ne = NarrowingNumericConversion (ec, expr, target_type, l);
2289                         if (ne != null)
2290                                 return ne;
2291
2292                         ne = NarrowingReferenceConversion (expr, target_type);
2293                         if (ne != null)
2294                                 return ne;
2295
2296                         Error_CannotConvertType (l, expr.Type, target_type);
2297                         return null;
2298                 }
2299
2300                 /// <summary>
2301                 ///   Entry point for VB.NET specific implicit conversions
2302                 /// </summary>
2303                 static public Expression ImplicitVBConversion (EmitContext ec, Expression expr,
2304                                                              Type target_type, Location loc)
2305                 {
2306                         if (RootContext.StricterTypeChecking)
2307                                 return WideningConversion (ec, expr, target_type, loc);
2308                         else
2309                                 return WideningAndNarrowingConversion(ec, expr, target_type, loc);
2310                 }
2311
2312                 /// <summary>
2313                 ///   Mandates VB.NET specific implicit conversions
2314                 /// </summary>
2315                 static public Expression ImplicitVBConversionRequired (EmitContext ec, Expression source,
2316                                                                      Type target_type, Location loc)
2317                 {
2318                         Expression e;
2319
2320
2321                         int errors = Report.Errors;
2322                         e = ImplicitVBConversion (ec, source, target_type, loc);
2323                         if (Report.Errors > errors)
2324                                 return null;
2325                         if (e != null)
2326                                 return e;
2327
2328                         if (source is DoubleLiteral) {
2329                                 if (target_type == TypeManager.float_type) {
2330                                         Error_664 (loc, "float", "f");
2331                                         return null;
2332                                 }
2333                                 if (target_type == TypeManager.decimal_type) {
2334                                         Error_664 (loc, "decimal", "m");
2335                                         return null;
2336                                 }
2337                         }
2338
2339                         if (source is Constant){
2340                                 Constant c = (Constant) source;
2341
2342                                 Expression.Error_ConstantValueCannotBeConverted (loc, c.AsString (), target_type);
2343                                 return null;
2344                         }
2345                         
2346                         Error_CannotWideningConversion (loc, source.Type, target_type);
2347
2348                         return null;
2349                 }
2350
2351                 /// <summary>
2352                 ///   Entry point for VB.NET specific explicit conversions
2353                 /// </summary>
2354                 static public Expression ExplicitVBConversion (EmitContext ec, Expression expr,
2355                                                              Type target_type, Location loc)
2356                 {
2357                                 return WideningAndNarrowingConversion(ec, expr, target_type, loc);
2358                 }
2359
2360         }
2361 }