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