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