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