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