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