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