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