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