* mb-tokenizer.cs: Oops. Also pulled out all of the old
[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 (30390, "'" + s.Name + "' " +
329                                                        "is inaccessible because of its protection level");
330                                         else
331                                                 Error (30451, "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                                                 30451, 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                                         30456, loc, "'" + t + "' does not contain a definition " +
654                                         "for '" + name + "'");
655                         } else {
656                                         Report.Error (
657                                                 30390, 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                                 ce.IsRuntimeCast = true;
1680                                 return ce.Resolve (ec);
1681                         }
1682
1683                         switch (dest_type) {
1684                                 case TypeCode.String:
1685                                         switch (src_type) {
1686                                                 case TypeCode.SByte:                                            
1687                                                 case TypeCode.Byte:
1688                                                         e = RTConversionExpression(ec, "StringType.FromByte", expr, loc);
1689                                                         break;  
1690                                                 case TypeCode.UInt16:
1691                                                 case TypeCode.Int16:
1692                                                         e = RTConversionExpression(ec, "StringType.FromShort", expr, loc);
1693                                                         break;          
1694                                                 case TypeCode.UInt32:                                   
1695                                                 case TypeCode.Int32:
1696                                                         e = RTConversionExpression(ec, "StringType.FromInteger", expr, loc);
1697                                                         break;                                                  
1698                                                 case TypeCode.UInt64:   
1699                                                 case TypeCode.Int64:
1700                                                         e = RTConversionExpression(ec, "StringType.FromLong", expr, loc);
1701                                                         break;                                                  
1702                                                 case TypeCode.Char:
1703                                                         e = RTConversionExpression(ec, "StringType.FromChar", expr, loc);
1704                                                         break;                                                          
1705                                                 case TypeCode.Single:
1706                                                         e = RTConversionExpression(ec, "StringType.FromSingle", expr, loc);
1707                                                         break;          
1708                                                 case TypeCode.Double:
1709                                                         e = RTConversionExpression(ec, "StringType.FromDouble", expr, loc);
1710                                                         break;                                                                                                                                                  
1711                                                 case TypeCode.Boolean:
1712                                                         e = RTConversionExpression(ec, "StringType.FromBoolean", expr, loc);
1713                                                         break;  
1714                                                 case TypeCode.DateTime:
1715                                                         e = RTConversionExpression(ec, "StringType.FromDate", expr, loc);
1716                                                         break;          
1717                                                 case TypeCode.Decimal:
1718                                                         e = RTConversionExpression(ec, "StringType.FromDecimal", expr, loc);
1719                                                         break;          
1720                                                 case TypeCode.Object:
1721                                                         e = RTConversionExpression(ec, "StringType.FromObject", expr, loc);
1722                                                         break;                                                                                                                                                                                                                          
1723                                         }
1724                                         break;
1725                                         
1726                                 case TypeCode.Int32:
1727                                 case TypeCode.UInt32:   
1728                                         switch (src_type) {                                             
1729                                                 case TypeCode.String:                           
1730                                                         e = RTConversionExpression(ec, "IntegerType.FromString", expr, loc);
1731                                                         break;          
1732                                                 case TypeCode.Object:                           
1733                                                         e = RTConversionExpression(ec, "IntegerType.FromObject", expr, loc);
1734                                                         break;                                                                                  
1735                                         }
1736                                         break;  
1737
1738                                 case TypeCode.Int16:
1739                                 case TypeCode.UInt16:   
1740                                         switch (src_type) {                                             
1741                                                 case TypeCode.String:                           
1742                                                         e = RTConversionExpression(ec, "ShortType.FromString", expr, loc);
1743                                                         break;          
1744                                                 case TypeCode.Object:                           
1745                                                         e = RTConversionExpression(ec, "ShortType.FromObject", expr, loc);
1746                                                         break;                                                                                  
1747                                         }
1748                                         break;  
1749                                 case TypeCode.Byte:
1750                                         // Ok, this *is* broken
1751                                         e = RTConversionExpression(ec, "ByteType.FromObject", expr, loc);
1752                                         break;                                                                                                                                                  
1753                         }
1754                         
1755                         // We must examine separately some types that
1756                         // don't have a TypeCode but are supported 
1757                         // in the runtime
1758                         if (expr_type == typeof(System.String) && target_type == typeof (System.Char[])) {
1759                                 e = RTConversionExpression(ec, "CharArrayType.FromString", expr, loc);
1760                         }
1761                         
1762                         return e;
1763                 }
1764                                                                                                 
1765                 /// <summary>
1766                 ///   Attempts to apply the 'Standard Implicit
1767                 ///   Conversion' rules to the expression 'expr' into
1768                 ///   the 'target_type'.  It returns a new expression
1769                 ///   that can be used in a context that expects a
1770                 ///   'target_type'.
1771                 ///
1772                 ///   This is different from 'ConvertImplicit' in that the
1773                 ///   user defined implicit conversions are excluded. 
1774                 /// </summary>
1775                 static public Expression ConvertImplicitStandard (EmitContext ec, Expression expr,
1776                                                                   Type target_type, Location loc)
1777                 {
1778                         Type expr_type = expr.Type;
1779                         Expression e;
1780
1781                         if (expr_type == target_type)
1782                                 return expr;
1783
1784                         e = ImplicitNumericConversion (ec, expr, target_type, loc);
1785                         if (e != null)
1786                                 return e;
1787
1788                         e = ImplicitReferenceConversion (expr, target_type);
1789                         if (e != null)
1790                                 return e;
1791
1792                         if (target_type.IsSubclassOf (TypeManager.enum_type) && expr is IntLiteral){
1793                                 IntLiteral i = (IntLiteral) expr;
1794
1795                                 if (i.Value == 0)
1796                                         return new EmptyCast (expr, target_type);
1797                         }
1798
1799                         if (ec.InUnsafe) {
1800                                 if (expr_type.IsPointer){
1801                                         if (target_type == TypeManager.void_ptr_type)
1802                                                 return new EmptyCast (expr, target_type);
1803
1804                                         //
1805                                         // yep, comparing pointer types cant be done with
1806                                         // t1 == t2, we have to compare their element types.
1807                                         //
1808                                         if (target_type.IsPointer){
1809                                                 if (target_type.GetElementType()==expr_type.GetElementType())
1810                                                         return expr;
1811                                         }
1812                                 }
1813                                 
1814                                 if (target_type.IsPointer){
1815                                         if (expr is NullLiteral)
1816                                                 return new EmptyCast (expr, target_type);
1817                                 }
1818                         }
1819
1820                         return null;
1821                 }
1822
1823                 /// <summary>
1824                 ///   Attemps to perform an implict constant conversion of the IntConstant
1825                 ///   into a different data type using casts (See Implicit Constant
1826                 ///   Expression Conversions)
1827                 /// </summary>
1828                 static protected Expression TryImplicitIntConversion (Type target_type, IntConstant ic)
1829                 {
1830                         int value = ic.Value;
1831
1832                         //
1833                         // FIXME: This could return constants instead of EmptyCasts
1834                         //
1835                         if (target_type == TypeManager.sbyte_type){
1836                                 if (value >= SByte.MinValue && value <= SByte.MaxValue)
1837                                         return new SByteConstant ((sbyte) value);
1838                         } else if (target_type == TypeManager.byte_type){
1839                                 if (Byte.MinValue >= 0 && value <= Byte.MaxValue)
1840                                         return new ByteConstant ((byte) value);
1841                         } else if (target_type == TypeManager.short_type){
1842                                 if (value >= Int16.MinValue && value <= Int16.MaxValue)
1843                                         return new ShortConstant ((short) value);
1844                         } else if (target_type == TypeManager.ushort_type){
1845                                 if (value >= UInt16.MinValue && value <= UInt16.MaxValue)
1846                                         return new UShortConstant ((ushort) value);
1847                         } else if (target_type == TypeManager.uint32_type){
1848                                 if (value >= 0)
1849                                         return new UIntConstant ((uint) value);
1850                         } else if (target_type == TypeManager.uint64_type){
1851                                 //
1852                                 // we can optimize this case: a positive int32
1853                                 // always fits on a uint64.  But we need an opcode
1854                                 // to do it.
1855                                 //
1856                                 if (value >= 0)
1857                                         return new ULongConstant ((ulong) value);
1858                         }
1859                         
1860                         if (value == 0 && ic is IntLiteral && TypeManager.IsEnumType (target_type)){
1861                                 Type underlying = TypeManager.EnumToUnderlying (target_type);
1862                                 Constant e = (Constant) ic;
1863                                 
1864                                 //
1865                                 // Possibly, we need to create a different 0 literal before passing
1866                                 // to EnumConstant
1867                                 //n
1868                                 if (underlying == TypeManager.int64_type)
1869                                         e = new LongLiteral (0);
1870                                 else if (underlying == TypeManager.uint64_type)
1871                                         e = new ULongLiteral (0);
1872
1873                                 return new EnumConstant (e, target_type);
1874                         }
1875                         return null;
1876                 }
1877
1878                 static public void Error_CannotConvertImplicit (Location loc, Type source, Type target)
1879                 {
1880                         string msg = "Cannot convert implicitly from '"+
1881                                 TypeManager.MonoBASIC_Name (source) + "' to '" +
1882                                 TypeManager.MonoBASIC_Name (target) + "'";
1883
1884                         Report.Error (29, loc, msg);
1885                 }
1886
1887                 /// <summary>
1888                 ///   Attemptes to implicityly convert 'target' into 'type', using
1889                 ///   ConvertImplicit.  If there is no implicit conversion, then
1890                 ///   an error is signaled
1891                 /// </summary>
1892                 static public Expression ConvertImplicitRequired (EmitContext ec, Expression source,
1893                                                                   Type target_type, Location loc)
1894                 {
1895                         Expression e;
1896                         
1897                         e = ConvertImplicit (ec, source, target_type, loc);
1898                         if (e != null)
1899                                 return e;
1900
1901                         if (source is DoubleLiteral && target_type == TypeManager.float_type){
1902                                 Report.Error (664, loc,
1903                                               "Double literal cannot be implicitly converted to " +
1904                                               "float type, use F suffix to create a float literal");
1905                         }
1906
1907                         Error_CannotConvertImplicit (loc, source.Type, target_type);
1908
1909                         return null;
1910                 }
1911
1912                 /// <summary>
1913                 ///   Performs the explicit numeric conversions
1914                 /// </summary>
1915                 static Expression ConvertNumericExplicit (EmitContext ec, Expression expr, Type target_type, Location loc)
1916                 {
1917                         Type expr_type = expr.Type;
1918
1919                         //
1920                         // If we have an enumeration, extract the underlying type,
1921                         // use this during the comparison, but wrap around the original
1922                         // target_type
1923                         //
1924                         Type real_target_type = target_type;
1925
1926                         if (TypeManager.IsEnumType (real_target_type))
1927                                 real_target_type = TypeManager.EnumToUnderlying (real_target_type);
1928
1929                         if (StandardConversionExists (expr, real_target_type)){
1930                                 Expression ce = ConvertImplicitStandard (ec, expr, real_target_type, loc);
1931
1932                                 if (real_target_type != target_type)
1933                                         return new EmptyCast (ce, target_type);
1934                                 return ce;
1935                         }
1936                         
1937                         if (expr_type == TypeManager.sbyte_type){
1938                                 //
1939                                 // From sbyte to byte, ushort, uint, ulong, char
1940                                 //
1941                                 if (real_target_type == TypeManager.byte_type)
1942                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.I1_U1);
1943                                 if (real_target_type == TypeManager.ushort_type)
1944                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.I1_U2);
1945                                 if (real_target_type == TypeManager.uint32_type)
1946                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.I1_U4);
1947                                 if (real_target_type == TypeManager.uint64_type)
1948                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.I1_U8);
1949                                 if (real_target_type == TypeManager.char_type)
1950                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.I1_CH);
1951                         } else if (expr_type == TypeManager.byte_type){
1952                                 //
1953                                 // From byte to sbyte and char
1954                                 //
1955                                 if (real_target_type == TypeManager.sbyte_type)
1956                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.U1_I1);
1957                                 if (real_target_type == TypeManager.char_type)
1958                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.U1_CH);
1959                         } else if (expr_type == TypeManager.short_type){
1960                                 //
1961                                 // From short to sbyte, byte, ushort, uint, ulong, char
1962                                 //
1963                                 if (real_target_type == TypeManager.sbyte_type)
1964                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.I2_I1);
1965                                 if (real_target_type == TypeManager.byte_type)
1966                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.I2_U1);
1967                                 if (real_target_type == TypeManager.ushort_type)
1968                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.I2_U2);
1969                                 if (real_target_type == TypeManager.uint32_type)
1970                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.I2_U4);
1971                                 if (real_target_type == TypeManager.uint64_type)
1972                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.I2_U8);
1973                                 if (real_target_type == TypeManager.char_type)
1974                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.I2_CH);
1975                         } else if (expr_type == TypeManager.ushort_type){
1976                                 //
1977                                 // From ushort to sbyte, byte, short, char
1978                                 //
1979                                 if (real_target_type == TypeManager.sbyte_type)
1980                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.U2_I1);
1981                                 if (real_target_type == TypeManager.byte_type)
1982                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.U2_U1);
1983                                 if (real_target_type == TypeManager.short_type)
1984                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.U2_I2);
1985                                 if (real_target_type == TypeManager.char_type)
1986                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.U2_CH);
1987                         } else if (expr_type == TypeManager.int32_type){
1988                                 //
1989                                 // From int to sbyte, byte, short, ushort, uint, ulong, char
1990                                 //
1991                                 if (real_target_type == TypeManager.sbyte_type)
1992                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.I4_I1);
1993                                 if (real_target_type == TypeManager.byte_type)
1994                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.I4_U1);
1995                                 if (real_target_type == TypeManager.short_type)
1996                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.I4_I2);
1997                                 if (real_target_type == TypeManager.ushort_type)
1998                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.I4_U2);
1999                                 if (real_target_type == TypeManager.uint32_type)
2000                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.I4_U4);
2001                                 if (real_target_type == TypeManager.uint64_type)
2002                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.I4_U8);
2003                                 if (real_target_type == TypeManager.char_type)
2004                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.I4_CH);
2005                         } else if (expr_type == TypeManager.uint32_type){
2006                                 //
2007                                 // From uint to sbyte, byte, short, ushort, int, char
2008                                 //
2009                                 if (real_target_type == TypeManager.sbyte_type)
2010                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.U4_I1);
2011                                 if (real_target_type == TypeManager.byte_type)
2012                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.U4_U1);
2013                                 if (real_target_type == TypeManager.short_type)
2014                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.U4_I2);
2015                                 if (real_target_type == TypeManager.ushort_type)
2016                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.U4_U2);
2017                                 if (real_target_type == TypeManager.int32_type)
2018                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.U4_I4);
2019                                 if (real_target_type == TypeManager.char_type)
2020                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.U4_CH);
2021                         } else if (expr_type == TypeManager.int64_type){
2022                                 //
2023                                 // From long to sbyte, byte, short, ushort, int, uint, ulong, char
2024                                 //
2025                                 if (real_target_type == TypeManager.sbyte_type)
2026                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.I8_I1);
2027                                 if (real_target_type == TypeManager.byte_type)
2028                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.I8_U1);
2029                                 if (real_target_type == TypeManager.short_type)
2030                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.I8_I2);
2031                                 if (real_target_type == TypeManager.ushort_type)
2032                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.I8_U2);
2033                                 if (real_target_type == TypeManager.int32_type)
2034                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.I8_I4);
2035                                 if (real_target_type == TypeManager.uint32_type)
2036                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.I8_U4);
2037                                 if (real_target_type == TypeManager.uint64_type)
2038                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.I8_U8);
2039                                 if (real_target_type == TypeManager.char_type)
2040                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.I8_CH);
2041                         } else if (expr_type == TypeManager.uint64_type){
2042                                 //
2043                                 // From ulong to sbyte, byte, short, ushort, int, uint, long, char
2044                                 //
2045                                 if (real_target_type == TypeManager.sbyte_type)
2046                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.U8_I1);
2047                                 if (real_target_type == TypeManager.byte_type)
2048                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.U8_U1);
2049                                 if (real_target_type == TypeManager.short_type)
2050                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.U8_I2);
2051                                 if (real_target_type == TypeManager.ushort_type)
2052                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.U8_U2);
2053                                 if (real_target_type == TypeManager.int32_type)
2054                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.U8_I4);
2055                                 if (real_target_type == TypeManager.uint32_type)
2056                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.U8_U4);
2057                                 if (real_target_type == TypeManager.int64_type)
2058                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.U8_I8);
2059                                 if (real_target_type == TypeManager.char_type)
2060                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.U8_CH);
2061                         } else if (expr_type == TypeManager.char_type){
2062                                 //
2063                                 // From char to sbyte, byte, short
2064                                 //
2065                                 if (real_target_type == TypeManager.sbyte_type)
2066                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.CH_I1);
2067                                 if (real_target_type == TypeManager.byte_type)
2068                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.CH_U1);
2069                                 if (real_target_type == TypeManager.short_type)
2070                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.CH_I2);
2071                         } else if (expr_type == TypeManager.float_type){
2072                                 //
2073                                 // From float to sbyte, byte, short,
2074                                 // ushort, int, uint, long, ulong, char
2075                                 // or decimal
2076                                 //
2077                                 if (real_target_type == TypeManager.sbyte_type)
2078                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.R4_I1);
2079                                 if (real_target_type == TypeManager.byte_type)
2080                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.R4_U1);
2081                                 if (real_target_type == TypeManager.short_type)
2082                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.R4_I2);
2083                                 if (real_target_type == TypeManager.ushort_type)
2084                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.R4_U2);
2085                                 if (real_target_type == TypeManager.int32_type)
2086                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.R4_I4);
2087                                 if (real_target_type == TypeManager.uint32_type)
2088                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.R4_U4);
2089                                 if (real_target_type == TypeManager.int64_type)
2090                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.R4_I8);
2091                                 if (real_target_type == TypeManager.uint64_type)
2092                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.R4_U8);
2093                                 if (real_target_type == TypeManager.char_type)
2094                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.R4_CH);
2095                         } else if (expr_type == TypeManager.double_type){
2096                                 //
2097                                 // From double to byte, byte, short,
2098                                 // ushort, int, uint, long, ulong,
2099                                 // char, float or decimal
2100                                 //
2101                                 if (real_target_type == TypeManager.sbyte_type)
2102                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.R8_I1);
2103                                 if (real_target_type == TypeManager.byte_type)
2104                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.R8_U1);
2105                                 if (real_target_type == TypeManager.short_type)
2106                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.R8_I2);
2107                                 if (real_target_type == TypeManager.ushort_type)
2108                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.R8_U2);
2109                                 if (real_target_type == TypeManager.int32_type)
2110                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.R8_I4);
2111                                 if (real_target_type == TypeManager.uint32_type)
2112                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.R8_U4);
2113                                 if (real_target_type == TypeManager.int64_type)
2114                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.R8_I8);
2115                                 if (real_target_type == TypeManager.uint64_type)
2116                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.R8_U8);
2117                                 if (real_target_type == TypeManager.char_type)
2118                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.R8_CH);
2119                                 if (real_target_type == TypeManager.float_type)
2120                                         return new ConvCast (ec, expr, target_type, ConvCast.Mode.R8_R4);
2121                         } 
2122
2123                         // decimal is taken care of by the op_Explicit methods.
2124
2125                         return null;
2126                 }
2127
2128                 /// <summary>
2129                 ///  Returns whether an explicit reference conversion can be performed
2130                 ///  from source_type to target_type
2131                 /// </summary>
2132                 public static bool ExplicitReferenceConversionExists (Type source_type, Type target_type)
2133                 {
2134                         bool target_is_value_type = target_type.IsValueType;
2135                         
2136                         if (source_type == target_type)
2137                                 return true;
2138                         
2139                         //
2140                         // From object to any reference type
2141                         //
2142                         if (source_type == TypeManager.object_type && !target_is_value_type)
2143                                 return true;
2144                                         
2145                         //
2146                         // From any class S to any class-type T, provided S is a base class of T
2147                         //
2148                         if (target_type.IsSubclassOf (source_type))
2149                                 return true;
2150
2151                         //
2152                         // From any interface type S to any interface T provided S is not derived from T
2153                         //
2154                         if (source_type.IsInterface && target_type.IsInterface){
2155                                 if (!target_type.IsSubclassOf (source_type))
2156                                         return true;
2157                         }
2158                             
2159                         //
2160                         // From any class type S to any interface T, provided S is not sealed
2161                         // and provided S does not implement T.
2162                         //
2163                         if (target_type.IsInterface && !source_type.IsSealed &&
2164                             !TypeManager.ImplementsInterface (source_type, target_type))
2165                                 return true;
2166
2167                         //
2168                         // From any interface-type S to to any class type T, provided T is not
2169                         // sealed, or provided T implements S.
2170                         //
2171                         if (source_type.IsInterface &&
2172                             (!target_type.IsSealed || TypeManager.ImplementsInterface (target_type, source_type)))
2173                                 return true;
2174                         
2175                         
2176                         // From an array type S with an element type Se to an array type T with an 
2177                         // element type Te provided all the following are true:
2178                         //     * S and T differe only in element type, in other words, S and T
2179                         //       have the same number of dimensions.
2180                         //     * Both Se and Te are reference types
2181                         //     * An explicit referenc conversions exist from Se to Te
2182                         //
2183                         if (source_type.IsArray && target_type.IsArray) {
2184                                 if (source_type.GetArrayRank () == target_type.GetArrayRank ()) {
2185                                         
2186                                         Type source_element_type = source_type.GetElementType ();
2187                                         Type target_element_type = target_type.GetElementType ();
2188                                         
2189                                         if (!source_element_type.IsValueType && !target_element_type.IsValueType)
2190                                                 if (ExplicitReferenceConversionExists (source_element_type,
2191                                                                                        target_element_type))
2192                                                         return true;
2193                                 }
2194                         }
2195                         
2196
2197                         // From System.Array to any array-type
2198                         if (source_type == TypeManager.array_type &&
2199                             target_type.IsArray){
2200                                 return true;
2201                         }
2202
2203                         //
2204                         // From System delegate to any delegate-type
2205                         //
2206                         if (source_type == TypeManager.delegate_type &&
2207                             target_type.IsSubclassOf (TypeManager.delegate_type))
2208                                 return true;
2209
2210                         //
2211                         // From ICloneable to Array or Delegate types
2212                         //
2213                         if (source_type == TypeManager.icloneable_type &&
2214                             (target_type == TypeManager.array_type ||
2215                              target_type == TypeManager.delegate_type))
2216                                 return true;
2217                         
2218                         return false;
2219                 }
2220
2221                 /// <summary>
2222                 ///   Implements Explicit Reference conversions
2223                 /// </summary>
2224                 static Expression ConvertReferenceExplicit (Expression source, Type target_type)
2225                 {
2226                         Type source_type = source.Type;
2227                         bool target_is_value_type = target_type.IsValueType;
2228
2229                         //
2230                         // From object to any reference type
2231                         //
2232                         if (source_type == TypeManager.object_type && !target_is_value_type)
2233                                 return new ClassCast (source, target_type);
2234
2235
2236                         //
2237                         // From any class S to any class-type T, provided S is a base class of T
2238                         //
2239                         if (target_type.IsSubclassOf (source_type))
2240                                 return new ClassCast (source, target_type);
2241
2242                         //
2243                         // From any interface type S to any interface T provided S is not derived from T
2244                         //
2245                         if (source_type.IsInterface && target_type.IsInterface){
2246                                 if (TypeManager.ImplementsInterface (source_type, target_type))
2247                                         return null;
2248                                 else
2249                                         return new ClassCast (source, target_type);
2250                         }
2251                             
2252                         //
2253                         // From any class type S to any interface T, provides S is not sealed
2254                         // and provided S does not implement T.
2255                         //
2256                         if (target_type.IsInterface && !source_type.IsSealed) {
2257                                 if (TypeManager.ImplementsInterface (source_type, target_type))
2258                                         return null;
2259                                 else
2260                                         return new ClassCast (source, target_type);
2261                                 
2262                         }
2263
2264                         //
2265                         // From any interface-type S to to any class type T, provided T is not
2266                         // sealed, or provided T implements S.
2267                         //
2268                         if (source_type.IsInterface) {
2269                                 if (!target_type.IsSealed || TypeManager.ImplementsInterface (target_type, source_type))
2270                                         return new ClassCast (source, target_type);
2271                                 else
2272                                         return null;
2273                         }
2274                         
2275                         // From an array type S with an element type Se to an array type T with an 
2276                         // element type Te provided all the following are true:
2277                         //     * S and T differe only in element type, in other words, S and T
2278                         //       have the same number of dimensions.
2279                         //     * Both Se and Te are reference types
2280                         //     * An explicit referenc conversions exist from Se to Te
2281                         //
2282                         if (source_type.IsArray && target_type.IsArray) {
2283                                 if (source_type.GetArrayRank () == target_type.GetArrayRank ()) {
2284                                         
2285                                         Type source_element_type = source_type.GetElementType ();
2286                                         Type target_element_type = target_type.GetElementType ();
2287                                         
2288                                         if (!source_element_type.IsValueType && !target_element_type.IsValueType)
2289                                                 if (ExplicitReferenceConversionExists (source_element_type,
2290                                                                                        target_element_type))
2291                                                         return new ClassCast (source, target_type);
2292                                 }
2293                         }
2294                         
2295
2296                         // From System.Array to any array-type
2297                         if (source_type == TypeManager.array_type &&
2298                             target_type.IsArray) {
2299                                 return new ClassCast (source, target_type);
2300                         }
2301
2302                         //
2303                         // From System delegate to any delegate-type
2304                         //
2305                         if (source_type == TypeManager.delegate_type &&
2306                             target_type.IsSubclassOf (TypeManager.delegate_type))
2307                                 return new ClassCast (source, target_type);
2308
2309                         //
2310                         // From ICloneable to Array or Delegate types
2311                         //
2312                         if (source_type == TypeManager.icloneable_type &&
2313                             (target_type == TypeManager.array_type ||
2314                              target_type == TypeManager.delegate_type))
2315                                 return new ClassCast (source, target_type);
2316                         
2317                         return null;
2318                 }
2319                 
2320                 /// <summary>
2321                 ///   Performs an explicit conversion of the expression 'expr' whose
2322                 ///   type is expr.Type to 'target_type'.
2323                 /// </summary>
2324                 static public Expression ConvertExplicit (EmitContext ec, Expression expr,
2325                                                           Type target_type, bool runtimeconv, Location loc)
2326                 {
2327                         Type expr_type = expr.Type;
2328                         Expression ne = ConvertImplicitStandard (ec, expr, target_type, loc);
2329
2330                         if (ne != null)
2331                                 return ne;
2332
2333                         ne = ConvertNumericExplicit (ec, expr, target_type, loc);
2334                         if (ne != null)
2335                                 return ne;
2336
2337                         //
2338                         // Unboxing conversion.
2339                         //
2340                         if (expr_type == TypeManager.object_type && target_type.IsValueType)
2341                                 return new UnboxCast (expr, target_type);
2342
2343                         //
2344                         // Enum types
2345                         //
2346                         if (expr_type.IsSubclassOf (TypeManager.enum_type)) {
2347                                 Expression e;
2348
2349                                 //
2350                                 // FIXME: Is there any reason we should have EnumConstant
2351                                 // dealt with here instead of just using always the
2352                                 // UnderlyingSystemType to wrap the type?
2353                                 //
2354                                 if (expr is EnumConstant)
2355                                         e = ((EnumConstant) expr).Child;
2356                                 else {
2357                                         e = new EmptyCast (expr, TypeManager.EnumToUnderlying (expr_type));
2358                                 }
2359                                 
2360                                 Expression t = ConvertImplicit (ec, e, target_type, loc);
2361                                 if (t != null)
2362                                         return t;
2363                                 
2364                                 t = ConvertNumericExplicit (ec, e, target_type, loc);
2365                                 if (t != null)
2366                                         return t;
2367                                 
2368                                 t = RuntimeConversion (ec, e, target_type, loc);
2369                                 if (t != null)
2370                                         return t;       
2371                                                                 
2372                                 Error_CannotConvertType (loc, expr_type, target_type);
2373                                 return null;
2374                         }
2375                         
2376                         ne = ConvertReferenceExplicit (expr, target_type);
2377                         if (ne != null)
2378                                 return ne;
2379
2380                         if (ec.InUnsafe){
2381                                 if (target_type.IsPointer){
2382                                         if (expr_type.IsPointer)
2383                                                 return new EmptyCast (expr, target_type);
2384                                         
2385                                         if (expr_type == TypeManager.sbyte_type ||
2386                                             expr_type == TypeManager.byte_type ||
2387                                             expr_type == TypeManager.short_type ||
2388                                             expr_type == TypeManager.ushort_type ||
2389                                             expr_type == TypeManager.int32_type ||
2390                                             expr_type == TypeManager.uint32_type ||
2391                                             expr_type == TypeManager.uint64_type ||
2392                                             expr_type == TypeManager.int64_type)
2393                                                 return new OpcodeCast (expr, target_type, OpCodes.Conv_U);
2394                                 }
2395                                 if (expr_type.IsPointer){
2396                                         if (target_type == TypeManager.sbyte_type ||
2397                                             target_type == TypeManager.byte_type ||
2398                                             target_type == TypeManager.short_type ||
2399                                             target_type == TypeManager.ushort_type ||
2400                                             target_type == TypeManager.int32_type ||
2401                                             target_type == TypeManager.uint32_type ||
2402                                             target_type == TypeManager.uint64_type ||
2403                                             target_type == TypeManager.int64_type){
2404                                                 Expression e = new EmptyCast (expr, TypeManager.uint32_type);
2405                                                 Expression ci, ce;
2406
2407                                                 ci = ConvertImplicitStandard (ec, e, target_type, loc);
2408
2409                                                 if (ci != null)
2410                                                         return ci;
2411
2412                                                 ce = ConvertNumericExplicit (ec, e, target_type, loc);
2413                                                 if (ce != null)
2414                                                         return ce;
2415                                                 //
2416                                                 // We should always be able to go from an uint32
2417                                                 // implicitly or explicitly to the other integral
2418                                                 // types
2419                                                 //
2420                                                 throw new Exception ("Internal compiler error");
2421                                         }
2422                                 }
2423                         }
2424                         
2425                         ne = ExplicitUserConversion (ec, expr, target_type, loc);
2426                         if (ne != null)
2427                                 return ne;
2428
2429                         if (!(runtimeconv))     {
2430                                 ne = RuntimeConversion (ec, expr, target_type, loc);
2431                                 if (ne != null)
2432                                         return ne;
2433                                 
2434                                 Error_CannotConvertType (loc, expr_type, target_type);
2435                         }
2436                         return null;
2437                 }
2438
2439                 /// <summary>
2440                 ///   Same as ConvertExplicit, only it doesn't include user defined conversions
2441                 /// </summary>
2442                 static public Expression ConvertExplicitStandard (EmitContext ec, Expression expr,
2443                                                                   Type target_type, Location l)
2444                 {
2445                         Expression ne = ConvertImplicitStandard (ec, expr, target_type, l);
2446
2447                         if (ne != null)
2448                                 return ne;
2449
2450                         ne = ConvertNumericExplicit (ec, expr, target_type, l);
2451                         if (ne != null)
2452                                 return ne;
2453
2454                         ne = ConvertReferenceExplicit (expr, target_type);
2455                         if (ne != null)
2456                                 return ne;
2457
2458                         ne = RuntimeConversion (ec, expr, target_type, l);
2459                         if (ne != null)
2460                                 return ne;                              
2461
2462                         Error_CannotConvertType (l, expr.Type, target_type);
2463                         return null;
2464                 }
2465
2466                 static string ExprClassName (ExprClass c)
2467                 {
2468                         switch (c){
2469                         case ExprClass.Invalid:
2470                                 return "Invalid";
2471                         case ExprClass.Value:
2472                                 return "value";
2473                         case ExprClass.Variable:
2474                                 return "variable";
2475                         case ExprClass.Namespace:
2476                                 return "namespace";
2477                         case ExprClass.Type:
2478                                 return "type";
2479                         case ExprClass.MethodGroup:
2480                                 return "method group";
2481                         case ExprClass.PropertyAccess:
2482                                 return "property access";
2483                         case ExprClass.EventAccess:
2484                                 return "event access";
2485                         case ExprClass.IndexerAccess:
2486                                 return "indexer access";
2487                         case ExprClass.Nothing:
2488                                 return "null";
2489                         }
2490                         throw new Exception ("Should not happen");
2491                 }
2492                 
2493                 /// <summary>
2494                 ///   Reports that we were expecting 'expr' to be of class 'expected'
2495                 /// </summary>
2496                 public void Error118 (string expected)
2497                 {
2498                         string kind = "Unknown";
2499                         
2500                         kind = ExprClassName (eclass);
2501
2502                         Error (118, "Expression denotes a '" + kind +
2503                                "' where a '" + expected + "' was expected");
2504                 }
2505
2506                 public void Error118 (ResolveFlags flags)
2507                 {
2508                         ArrayList valid = new ArrayList (10);
2509
2510                         if ((flags & ResolveFlags.VariableOrValue) != 0) {
2511                                 valid.Add ("variable");
2512                                 valid.Add ("value");
2513                         }
2514
2515                         if ((flags & ResolveFlags.Type) != 0)
2516                                 valid.Add ("type");
2517
2518                         if ((flags & ResolveFlags.MethodGroup) != 0)
2519                                 valid.Add ("method group");
2520
2521                         if ((flags & ResolveFlags.SimpleName) != 0)
2522                                 valid.Add ("simple name");
2523
2524                         if (valid.Count == 0)
2525                                 valid.Add ("unknown");
2526
2527                         StringBuilder sb = new StringBuilder ();
2528                         for (int i = 0; i < valid.Count; i++) {
2529                                 if (i > 0)
2530                                         sb.Append (", ");
2531                                 else if (i == valid.Count)
2532                                         sb.Append (" or ");
2533                                 sb.Append (valid [i]);
2534                         }
2535
2536                         string kind = ExprClassName (eclass);
2537
2538                         Error (119, "Expression denotes a '" + kind + "' where " +
2539                                "a '" + sb.ToString () + "' was expected");
2540                 }
2541                 
2542                 static void Error_ConstantValueCannotBeConverted (Location l, string val, Type t)
2543                 {
2544                         Report.Error (31, l, "Constant value '" + val + "' cannot be converted to " +
2545                                       TypeManager.MonoBASIC_Name (t));
2546                 }
2547
2548                 public static void UnsafeError (Location loc)
2549                 {
2550                         Report.Error (214, loc, "Pointers may only be used in an unsafe context");
2551                 }
2552                 
2553                 /// <summary>
2554                 ///   Converts the IntConstant, UIntConstant, LongConstant or
2555                 ///   ULongConstant into the integral target_type.   Notice
2556                 ///   that we do not return an 'Expression' we do return
2557                 ///   a boxed integral type.
2558                 ///
2559                 ///   FIXME: Since I added the new constants, we need to
2560                 ///   also support conversions from CharConstant, ByteConstant,
2561                 ///   SByteConstant, UShortConstant, ShortConstant
2562                 ///
2563                 ///   This is used by the switch statement, so the domain
2564                 ///   of work is restricted to the literals above, and the
2565                 ///   targets are int32, uint32, char, byte, sbyte, ushort,
2566                 ///   short, uint64 and int64
2567                 /// </summary>
2568                 public static object ConvertIntLiteral (Constant c, Type target_type, Location loc)
2569                 {
2570                         string s = "";
2571
2572                         if (c.Type == target_type)
2573                                 return ((Constant) c).GetValue ();
2574
2575                         //
2576                         // Make into one of the literals we handle, we dont really care
2577                         // about this value as we will just return a few limited types
2578                         // 
2579                         if (c is EnumConstant)
2580                                 c = ((EnumConstant)c).WidenToCompilerConstant ();
2581
2582                         if (c is IntConstant){
2583                                 int v = ((IntConstant) c).Value;
2584                                 
2585                                 if (target_type == TypeManager.uint32_type){
2586                                         if (v >= 0)
2587                                                 return (uint) v;
2588                                 } else if (target_type == TypeManager.char_type){
2589                                         if (v >= Char.MinValue && v <= Char.MaxValue)
2590                                                 return (char) v;
2591                                 } else if (target_type == TypeManager.byte_type){
2592                                         if (v >= Byte.MinValue && v <= Byte.MaxValue)
2593                                                 return (byte) v;
2594                                 } else if (target_type == TypeManager.sbyte_type){
2595                                         if (v >= SByte.MinValue && v <= SByte.MaxValue)
2596                                                 return (sbyte) v;
2597                                 } else if (target_type == TypeManager.short_type){
2598                                         if (v >= Int16.MinValue && v <= UInt16.MaxValue)
2599                                                 return (short) v;
2600                                 } else if (target_type == TypeManager.ushort_type){
2601                                         if (v >= UInt16.MinValue && v <= UInt16.MaxValue)
2602                                                 return (ushort) v;
2603                                 } else if (target_type == TypeManager.int64_type)
2604                                         return (long) v;
2605                                 else if (target_type == TypeManager.uint64_type){
2606                                         if (v > 0)
2607                                                 return (ulong) v;
2608                                 }
2609
2610                                 s = v.ToString ();
2611                         } else if (c is UIntConstant){
2612                                 uint v = ((UIntConstant) c).Value;
2613
2614                                 if (target_type == TypeManager.int32_type){
2615                                         if (v <= Int32.MaxValue)
2616                                                 return (int) v;
2617                                 } else if (target_type == TypeManager.char_type){
2618                                         if (v >= Char.MinValue && v <= Char.MaxValue)
2619                                                 return (char) v;
2620                                 } else if (target_type == TypeManager.byte_type){
2621                                         if (v <= Byte.MaxValue)
2622                                                 return (byte) v;
2623                                 } else if (target_type == TypeManager.sbyte_type){
2624                                         if (v <= SByte.MaxValue)
2625                                                 return (sbyte) v;
2626                                 } else if (target_type == TypeManager.short_type){
2627                                         if (v <= UInt16.MaxValue)
2628                                                 return (short) v;
2629                                 } else if (target_type == TypeManager.ushort_type){
2630                                         if (v <= UInt16.MaxValue)
2631                                                 return (ushort) v;
2632                                 } else if (target_type == TypeManager.int64_type)
2633                                         return (long) v;
2634                                 else if (target_type == TypeManager.uint64_type)
2635                                         return (ulong) v;
2636                                 s = v.ToString ();
2637                         } else if (c is LongConstant){ 
2638                                 long v = ((LongConstant) c).Value;
2639
2640                                 if (target_type == TypeManager.int32_type){
2641                                         if (v >= UInt32.MinValue && v <= UInt32.MaxValue)
2642                                                 return (int) v;
2643                                 } else if (target_type == TypeManager.uint32_type){
2644                                         if (v >= 0 && v <= UInt32.MaxValue)
2645                                                 return (uint) v;
2646                                 } else if (target_type == TypeManager.char_type){
2647                                         if (v >= Char.MinValue && v <= Char.MaxValue)
2648                                                 return (char) v;
2649                                 } else if (target_type == TypeManager.byte_type){
2650                                         if (v >= Byte.MinValue && v <= Byte.MaxValue)
2651                                                 return (byte) v;
2652                                 } else if (target_type == TypeManager.sbyte_type){
2653                                         if (v >= SByte.MinValue && v <= SByte.MaxValue)
2654                                                 return (sbyte) v;
2655                                 } else if (target_type == TypeManager.short_type){
2656                                         if (v >= Int16.MinValue && v <= UInt16.MaxValue)
2657                                                 return (short) v;
2658                                 } else if (target_type == TypeManager.ushort_type){
2659                                         if (v >= UInt16.MinValue && v <= UInt16.MaxValue)
2660                                                 return (ushort) v;
2661                                 } else if (target_type == TypeManager.uint64_type){
2662                                         if (v > 0)
2663                                                 return (ulong) v;
2664                                 }
2665                                 s = v.ToString ();
2666                         } else if (c is ULongConstant){
2667                                 ulong v = ((ULongConstant) c).Value;
2668
2669                                 if (target_type == TypeManager.int32_type){
2670                                         if (v <= Int32.MaxValue)
2671                                                 return (int) v;
2672                                 } else if (target_type == TypeManager.uint32_type){
2673                                         if (v <= UInt32.MaxValue)
2674                                                 return (uint) v;
2675                                 } else if (target_type == TypeManager.char_type){
2676                                         if (v >= Char.MinValue && v <= Char.MaxValue)
2677                                                 return (char) v;
2678                                 } else if (target_type == TypeManager.byte_type){
2679                                         if (v >= Byte.MinValue && v <= Byte.MaxValue)
2680                                                 return (byte) v;
2681                                 } else if (target_type == TypeManager.sbyte_type){
2682                                         if (v <= (int) SByte.MaxValue)
2683                                                 return (sbyte) v;
2684                                 } else if (target_type == TypeManager.short_type){
2685                                         if (v <= UInt16.MaxValue)
2686                                                 return (short) v;
2687                                 } else if (target_type == TypeManager.ushort_type){
2688                                         if (v <= UInt16.MaxValue)
2689                                                 return (ushort) v;
2690                                 } else if (target_type == TypeManager.int64_type){
2691                                         if (v <= Int64.MaxValue)
2692                                                 return (long) v;
2693                                 }
2694                                 s = v.ToString ();
2695                         } else if (c is ByteConstant){
2696                                 byte v = ((ByteConstant) c).Value;
2697                                 
2698                                 if (target_type == TypeManager.int32_type)
2699                                         return (int) v;
2700                                 else if (target_type == TypeManager.uint32_type)
2701                                         return (uint) v;
2702                                 else if (target_type == TypeManager.char_type)
2703                                         return (char) v;
2704                                 else if (target_type == TypeManager.sbyte_type){
2705                                         if (v <= SByte.MaxValue)
2706                                                 return (sbyte) v;
2707                                 } else if (target_type == TypeManager.short_type)
2708                                         return (short) v;
2709                                 else if (target_type == TypeManager.ushort_type)
2710                                         return (ushort) v;
2711                                 else if (target_type == TypeManager.int64_type)
2712                                         return (long) v;
2713                                 else if (target_type == TypeManager.uint64_type)
2714                                         return (ulong) v;
2715                                 s = v.ToString ();
2716                         } else if (c is SByteConstant){
2717                                 sbyte v = ((SByteConstant) c).Value;
2718                                 
2719                                 if (target_type == TypeManager.int32_type)
2720                                         return (int) v;
2721                                 else if (target_type == TypeManager.uint32_type){
2722                                         if (v >= 0)
2723                                                 return (uint) v;
2724                                 } else if (target_type == TypeManager.char_type){
2725                                         if (v >= 0)
2726                                                 return (char) v;
2727                                 } else if (target_type == TypeManager.byte_type){
2728                                         if (v >= 0)
2729                                                 return (byte) v;
2730                                 } else if (target_type == TypeManager.short_type)
2731                                         return (short) v;
2732                                 else if (target_type == TypeManager.ushort_type){
2733                                         if (v >= 0)
2734                                                 return (ushort) v;
2735                                 } else if (target_type == TypeManager.int64_type)
2736                                         return (long) v;
2737                                 else if (target_type == TypeManager.uint64_type){
2738                                         if (v >= 0)
2739                                                 return (ulong) v;
2740                                 }
2741                                 s = v.ToString ();
2742                         } else if (c is ShortConstant){
2743                                 short v = ((ShortConstant) c).Value;
2744                                 
2745                                 if (target_type == TypeManager.int32_type){
2746                                         return (int) v;
2747                                 } else if (target_type == TypeManager.uint32_type){
2748                                         if (v >= 0)
2749                                                 return (uint) v;
2750                                 } else if (target_type == TypeManager.char_type){
2751                                         if (v >= 0)
2752                                                 return (char) v;
2753                                 } else if (target_type == TypeManager.byte_type){
2754                                         if (v >= Byte.MinValue && v <= Byte.MaxValue)
2755                                                 return (byte) v;
2756                                 } else if (target_type == TypeManager.sbyte_type){
2757                                         if (v >= SByte.MinValue && v <= SByte.MaxValue)
2758                                                 return (sbyte) v;
2759                                 } else if (target_type == TypeManager.ushort_type){
2760                                         if (v >= 0)
2761                                                 return (ushort) v;
2762                                 } else if (target_type == TypeManager.int64_type)
2763                                         return (long) v;
2764                                 else if (target_type == TypeManager.uint64_type)
2765                                         return (ulong) v;
2766
2767                                 s = v.ToString ();
2768                         } else if (c is UShortConstant){
2769                                 ushort v = ((UShortConstant) c).Value;
2770                                 
2771                                 if (target_type == TypeManager.int32_type)
2772                                         return (int) v;
2773                                 else if (target_type == TypeManager.uint32_type)
2774                                         return (uint) v;
2775                                 else if (target_type == TypeManager.char_type){
2776                                         if (v >= Char.MinValue && v <= Char.MaxValue)
2777                                                 return (char) v;
2778                                 } else if (target_type == TypeManager.byte_type){
2779                                         if (v >= Byte.MinValue && v <= Byte.MaxValue)
2780                                                 return (byte) v;
2781                                 } else if (target_type == TypeManager.sbyte_type){
2782                                         if (v <= SByte.MaxValue)
2783                                                 return (byte) v;
2784                                 } else if (target_type == TypeManager.short_type){
2785                                         if (v <= Int16.MaxValue)
2786                                                 return (short) v;
2787                                 } else if (target_type == TypeManager.int64_type)
2788                                         return (long) v;
2789                                 else if (target_type == TypeManager.uint64_type)
2790                                         return (ulong) v;
2791
2792                                 s = v.ToString ();
2793                         } else if (c is CharConstant){
2794                                 char v = ((CharConstant) c).Value;
2795                                 
2796                                 if (target_type == TypeManager.int32_type)
2797                                         return (int) v;
2798                                 else if (target_type == TypeManager.uint32_type)
2799                                         return (uint) v;
2800                                 else if (target_type == TypeManager.byte_type){
2801                                         if (v >= Byte.MinValue && v <= Byte.MaxValue)
2802                                                 return (byte) v;
2803                                 } else if (target_type == TypeManager.sbyte_type){
2804                                         if (v <= SByte.MaxValue)
2805                                                 return (sbyte) v;
2806                                 } else if (target_type == TypeManager.short_type){
2807                                         if (v <= Int16.MaxValue)
2808                                                 return (short) v;
2809                                 } else if (target_type == TypeManager.ushort_type)
2810                                         return (short) v;
2811                                 else if (target_type == TypeManager.int64_type)
2812                                         return (long) v;
2813                                 else if (target_type == TypeManager.uint64_type)
2814                                         return (ulong) v;
2815
2816                                 s = v.ToString ();
2817                         }
2818                         Error_ConstantValueCannotBeConverted (loc, s, target_type);
2819                         return null;
2820                 }
2821
2822                 //
2823                 // Load the object from the pointer.  
2824                 //
2825                 public static void LoadFromPtr (ILGenerator ig, Type t)
2826                 {
2827                         if (t == TypeManager.int32_type)
2828                                 ig.Emit (OpCodes.Ldind_I4);
2829                         else if (t == TypeManager.uint32_type)
2830                                 ig.Emit (OpCodes.Ldind_U4);
2831                         else if (t == TypeManager.short_type)
2832                                 ig.Emit (OpCodes.Ldind_I2);
2833                         else if (t == TypeManager.ushort_type)
2834                                 ig.Emit (OpCodes.Ldind_U2);
2835                         else if (t == TypeManager.char_type)
2836                                 ig.Emit (OpCodes.Ldind_U2);
2837                         else if (t == TypeManager.byte_type)
2838                                 ig.Emit (OpCodes.Ldind_U1);
2839                         else if (t == TypeManager.sbyte_type)
2840                                 ig.Emit (OpCodes.Ldind_I1);
2841                         else if (t == TypeManager.uint64_type)
2842                                 ig.Emit (OpCodes.Ldind_I8);
2843                         else if (t == TypeManager.int64_type)
2844                                 ig.Emit (OpCodes.Ldind_I8);
2845                         else if (t == TypeManager.float_type)
2846                                 ig.Emit (OpCodes.Ldind_R4);
2847                         else if (t == TypeManager.double_type)
2848                                 ig.Emit (OpCodes.Ldind_R8);
2849                         else if (t == TypeManager.bool_type)
2850                                 ig.Emit (OpCodes.Ldind_I1);
2851                         else if (t == TypeManager.intptr_type)
2852                                 ig.Emit (OpCodes.Ldind_I);
2853                         else if (TypeManager.IsEnumType (t)) {
2854                                 if (t == TypeManager.enum_type)
2855                                         ig.Emit (OpCodes.Ldind_Ref);
2856                                 else
2857                                         LoadFromPtr (ig, TypeManager.EnumToUnderlying (t));
2858                         } else if (t.IsValueType)
2859                                 ig.Emit (OpCodes.Ldobj, t);
2860                         else
2861                                 ig.Emit (OpCodes.Ldind_Ref);
2862                 }
2863
2864                 //
2865                 // The stack contains the pointer and the value of type 'type'
2866                 //
2867                 public static void StoreFromPtr (ILGenerator ig, Type type)
2868                 {
2869                         if (TypeManager.IsEnumType (type))
2870                                 type = TypeManager.EnumToUnderlying (type);
2871                         if (type == TypeManager.int32_type || type == TypeManager.uint32_type)
2872                                 ig.Emit (OpCodes.Stind_I4);
2873                         else if (type == TypeManager.int64_type || type == TypeManager.uint64_type)
2874                                 ig.Emit (OpCodes.Stind_I8);
2875                         else if (type == TypeManager.char_type || type == TypeManager.short_type ||
2876                                  type == TypeManager.ushort_type)
2877                                 ig.Emit (OpCodes.Stind_I2);
2878                         else if (type == TypeManager.float_type)
2879                                 ig.Emit (OpCodes.Stind_R4);
2880                         else if (type == TypeManager.double_type)
2881                                 ig.Emit (OpCodes.Stind_R8);
2882                         else if (type == TypeManager.byte_type || type == TypeManager.sbyte_type ||
2883                                  type == TypeManager.bool_type)
2884                                 ig.Emit (OpCodes.Stind_I1);
2885                         else if (type == TypeManager.intptr_type)
2886                                 ig.Emit (OpCodes.Stind_I);
2887                         else if (type.IsValueType)
2888                                 ig.Emit (OpCodes.Stobj, type);
2889                         else
2890                                 ig.Emit (OpCodes.Stind_Ref);
2891                 }
2892                 
2893                 //
2894                 // Returns the size of type 't' if known, otherwise, 0
2895                 //
2896                 public static int GetTypeSize (Type t)
2897                 {
2898                         t = TypeManager.TypeToCoreType (t);
2899                         if (t == TypeManager.int32_type ||
2900                             t == TypeManager.uint32_type ||
2901                             t == TypeManager.float_type)
2902                                 return 4;
2903                         else if (t == TypeManager.int64_type ||
2904                                  t == TypeManager.uint64_type ||
2905                                  t == TypeManager.double_type)
2906                                 return 8;
2907                         else if (t == TypeManager.byte_type ||
2908                                  t == TypeManager.sbyte_type ||
2909                                  t == TypeManager.bool_type)    
2910                                 return 1;
2911                         else if (t == TypeManager.short_type ||
2912                                  t == TypeManager.char_type ||
2913                                  t == TypeManager.ushort_type)
2914                                 return 2;
2915                         else if (t == TypeManager.decimal_type)
2916                                 return 16;
2917                         else
2918                                 return 0;
2919                 }
2920
2921                 //
2922                 // Default implementation of IAssignMethod.CacheTemporaries
2923                 //
2924                 public void CacheTemporaries (EmitContext ec)
2925                 {
2926                 }
2927
2928                 static void Error_NegativeArrayIndex (Location loc)
2929                 {
2930                         Report.Error (284, loc, "Can not create array with a negative size");
2931                 }
2932                 
2933                 //
2934                 // Converts 'source' to an int, uint, long or ulong.
2935                 //
2936                 public Expression ExpressionToArrayArgument (EmitContext ec, Expression source, Location loc)
2937                 {
2938                         Expression target;
2939                         
2940                         bool old_checked = ec.CheckState;
2941                         ec.CheckState = true;
2942                         
2943                         target = ConvertImplicit (ec, source, TypeManager.int32_type, loc);
2944                         if (target == null){
2945                                 target = ConvertImplicit (ec, source, TypeManager.uint32_type, loc);
2946                                 if (target == null){
2947                                         target = ConvertImplicit (ec, source, TypeManager.int64_type, loc);
2948                                         if (target == null){
2949                                                 target = ConvertImplicit (ec, source, TypeManager.uint64_type, loc);
2950                                                 if (target == null)
2951                                                         Expression.Error_CannotConvertImplicit (loc, source.Type, TypeManager.int32_type);
2952                                         }
2953                                 }
2954                         } 
2955                         ec.CheckState = old_checked;
2956
2957                         //
2958                         // Only positive constants are allowed at compile time
2959                         //
2960                         if (target is Constant){
2961                                 if (target is IntConstant){
2962                                         if (((IntConstant) target).Value < 0){
2963                                                 Error_NegativeArrayIndex (loc);
2964                                                 return null;
2965                                         }
2966                                 }
2967
2968                                 if (target is LongConstant){
2969                                         if (((LongConstant) target).Value < 0){
2970                                                 Error_NegativeArrayIndex (loc);
2971                                                 return null;
2972                                         }
2973                                 }
2974                                 
2975                         }
2976
2977                         return target;
2978                 }
2979                 
2980         }
2981
2982         /// <summary>
2983         ///   This is just a base class for expressions that can
2984         ///   appear on statements (invocations, object creation,
2985         ///   assignments, post/pre increment and decrement).  The idea
2986         ///   being that they would support an extra Emition interface that
2987         ///   does not leave a result on the stack.
2988         /// </summary>
2989         public abstract class ExpressionStatement : Expression {
2990
2991                 /// <summary>
2992                 ///   Requests the expression to be emitted in a 'statement'
2993                 ///   context.  This means that no new value is left on the
2994                 ///   stack after invoking this method (constrasted with
2995                 ///   Emit that will always leave a value on the stack).
2996                 /// </summary>
2997                 public abstract void EmitStatement (EmitContext ec);
2998         }
2999
3000         /// <summary>
3001         ///   This kind of cast is used to encapsulate the child
3002         ///   whose type is child.Type into an expression that is
3003         ///   reported to return "return_type".  This is used to encapsulate
3004         ///   expressions which have compatible types, but need to be dealt
3005         ///   at higher levels with.
3006         ///
3007         ///   For example, a "byte" expression could be encapsulated in one
3008         ///   of these as an "unsigned int".  The type for the expression
3009         ///   would be "unsigned int".
3010         ///
3011         /// </summary>
3012         public class EmptyCast : Expression {
3013                 protected Expression child;
3014
3015                 public EmptyCast (Expression child, Type return_type)
3016                 {
3017                         eclass = child.eclass;
3018                         type = return_type;
3019                         this.child = child;
3020                 }
3021
3022                 public override Expression DoResolve (EmitContext ec)
3023                 {
3024                         // This should never be invoked, we are born in fully
3025                         // initialized state.
3026
3027                         return this;
3028                 }
3029
3030                 public override void Emit (EmitContext ec)
3031                 {
3032                         child.Emit (ec);
3033                 }
3034         }
3035
3036         /// <summary>
3037         ///  This class is used to wrap literals which belong inside Enums
3038         /// </summary>
3039         public class EnumConstant : Constant {
3040                 public Constant Child;
3041
3042                 public EnumConstant (Constant child, Type enum_type)
3043                 {
3044                         eclass = child.eclass;
3045                         this.Child = child;
3046                         type = enum_type;
3047                 }
3048                 
3049                 public override Expression DoResolve (EmitContext ec)
3050                 {
3051                         // This should never be invoked, we are born in fully
3052                         // initialized state.
3053
3054                         return this;
3055                 }
3056
3057                 public override void Emit (EmitContext ec)
3058                 {
3059                         Child.Emit (ec);
3060                 }
3061
3062                 public override object GetValue ()
3063                 {
3064                         return Child.GetValue ();
3065                 }
3066
3067                 //
3068                 // Converts from one of the valid underlying types for an enumeration
3069                 // (int32, uint32, int64, uint64, short, ushort, byte, sbyte) to
3070                 // one of the internal compiler literals: Int/UInt/Long/ULong Literals.
3071                 //
3072                 public Constant WidenToCompilerConstant ()
3073                 {
3074                         Type t = TypeManager.EnumToUnderlying (Child.Type);
3075                         object v = ((Constant) Child).GetValue ();;
3076                         
3077                         if (t == TypeManager.int32_type)
3078                                 return new IntConstant ((int) v);
3079                         if (t == TypeManager.uint32_type)
3080                                 return new UIntConstant ((uint) v);
3081                         if (t == TypeManager.int64_type)
3082                                 return new LongConstant ((long) v);
3083                         if (t == TypeManager.uint64_type)
3084                                 return new ULongConstant ((ulong) v);
3085                         if (t == TypeManager.short_type)
3086                                 return new ShortConstant ((short) v);
3087                         if (t == TypeManager.ushort_type)
3088                                 return new UShortConstant ((ushort) v);
3089                         if (t == TypeManager.byte_type)
3090                                 return new ByteConstant ((byte) v);
3091                         if (t == TypeManager.sbyte_type)
3092                                 return new SByteConstant ((sbyte) v);
3093
3094                         throw new Exception ("Invalid enumeration underlying type: " + t);
3095                 }
3096
3097                 //
3098                 // Extracts the value in the enumeration on its native representation
3099                 //
3100                 public object GetPlainValue ()
3101                 {
3102                         Type t = TypeManager.EnumToUnderlying (Child.Type);
3103                         object v = ((Constant) Child).GetValue ();;
3104                         
3105                         if (t == TypeManager.int32_type)
3106                                 return (int) v;
3107                         if (t == TypeManager.uint32_type)
3108                                 return (uint) v;
3109                         if (t == TypeManager.int64_type)
3110                                 return (long) v;
3111                         if (t == TypeManager.uint64_type)
3112                                 return (ulong) v;
3113                         if (t == TypeManager.short_type)
3114                                 return (short) v;
3115                         if (t == TypeManager.ushort_type)
3116                                 return (ushort) v;
3117                         if (t == TypeManager.byte_type)
3118                                 return (byte) v;
3119                         if (t == TypeManager.sbyte_type)
3120                                 return (sbyte) v;
3121
3122                         return null;
3123                 }
3124                 
3125                 public override string AsString ()
3126                 {
3127                         return Child.AsString ();
3128                 }
3129
3130                 public override DoubleConstant ConvertToDouble ()
3131                 {
3132                         return Child.ConvertToDouble ();
3133                 }
3134
3135                 public override FloatConstant ConvertToFloat ()
3136                 {
3137                         return Child.ConvertToFloat ();
3138                 }
3139
3140                 public override ULongConstant ConvertToULong ()
3141                 {
3142                         return Child.ConvertToULong ();
3143                 }
3144
3145                 public override LongConstant ConvertToLong ()
3146                 {
3147                         return Child.ConvertToLong ();
3148                 }
3149
3150                 public override UIntConstant ConvertToUInt ()
3151                 {
3152                         return Child.ConvertToUInt ();
3153                 }
3154
3155                 public override IntConstant ConvertToInt ()
3156                 {
3157                         return Child.ConvertToInt ();
3158                 }
3159         }
3160
3161         /// <summary>
3162         ///   This kind of cast is used to encapsulate Value Types in objects.
3163         ///
3164         ///   The effect of it is to box the value type emitted by the previous
3165         ///   operation.
3166         /// </summary>
3167         public class BoxedCast : EmptyCast {
3168
3169                 public BoxedCast (Expression expr)
3170                         : base (expr, TypeManager.object_type)
3171                 {
3172                 }
3173
3174                 public override Expression DoResolve (EmitContext ec)
3175                 {
3176                         // This should never be invoked, we are born in fully
3177                         // initialized state.
3178
3179                         return this;
3180                 }
3181
3182                 public override void Emit (EmitContext ec)
3183                 {
3184                         base.Emit (ec);
3185                         
3186                         ec.ig.Emit (OpCodes.Box, child.Type);
3187                 }
3188         }
3189
3190         public class UnboxCast : EmptyCast {
3191                 public UnboxCast (Expression expr, Type return_type)
3192                         : base (expr, return_type)
3193                 {
3194                 }
3195
3196                 public override Expression DoResolve (EmitContext ec)
3197                 {
3198                         // This should never be invoked, we are born in fully
3199                         // initialized state.
3200
3201                         return this;
3202                 }
3203
3204                 public override void Emit (EmitContext ec)
3205                 {
3206                         Type t = type;
3207                         ILGenerator ig = ec.ig;
3208                         
3209                         base.Emit (ec);
3210                         ig.Emit (OpCodes.Unbox, t);
3211
3212                         LoadFromPtr (ig, t);
3213                 }
3214         }
3215         
3216         /// <summary>
3217         ///   This is used to perform explicit numeric conversions.
3218         ///
3219         ///   Explicit numeric conversions might trigger exceptions in a checked
3220         ///   context, so they should generate the conv.ovf opcodes instead of
3221         ///   conv opcodes.
3222         /// </summary>
3223         public class ConvCast : EmptyCast {
3224                 public enum Mode : byte {
3225                         I1_U1, I1_U2, I1_U4, I1_U8, I1_CH,
3226                         U1_I1, U1_CH,
3227                         I2_I1, I2_U1, I2_U2, I2_U4, I2_U8, I2_CH,
3228                         U2_I1, U2_U1, U2_I2, U2_CH,
3229                         I4_I1, I4_U1, I4_I2, I4_U2, I4_U4, I4_U8, I4_CH,
3230                         U4_I1, U4_U1, U4_I2, U4_U2, U4_I4, U4_CH,
3231                         I8_I1, I8_U1, I8_I2, I8_U2, I8_I4, I8_U4, I8_U8, I8_CH,
3232                         U8_I1, U8_U1, U8_I2, U8_U2, U8_I4, U8_U4, U8_I8, U8_CH,
3233                         CH_I1, CH_U1, CH_I2,
3234                         R4_I1, R4_U1, R4_I2, R4_U2, R4_I4, R4_U4, R4_I8, R4_U8, R4_CH,
3235                         R8_I1, R8_U1, R8_I2, R8_U2, R8_I4, R8_U4, R8_I8, R8_U8, R8_CH, R8_R4
3236                 }
3237
3238                 Mode mode;
3239                 bool checked_state;
3240                 
3241                 public ConvCast (EmitContext ec, Expression child, Type return_type, Mode m)
3242                         : base (child, return_type)
3243                 {
3244                         checked_state = ec.CheckState;
3245                         mode = m;
3246                 }
3247
3248                 public override Expression DoResolve (EmitContext ec)
3249                 {
3250                         // This should never be invoked, we are born in fully
3251                         // initialized state.
3252
3253                         return this;
3254                 }
3255
3256                 public override void Emit (EmitContext ec)
3257                 {
3258                         ILGenerator ig = ec.ig;
3259                         
3260                         base.Emit (ec);
3261
3262                         if (checked_state){
3263                                 switch (mode){
3264                                 case Mode.I1_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
3265                                 case Mode.I1_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
3266                                 case Mode.I1_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
3267                                 case Mode.I1_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
3268                                 case Mode.I1_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
3269
3270                                 case Mode.U1_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
3271                                 case Mode.U1_CH: /* nothing */ break;
3272
3273                                 case Mode.I2_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
3274                                 case Mode.I2_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
3275                                 case Mode.I2_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
3276                                 case Mode.I2_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
3277                                 case Mode.I2_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
3278                                 case Mode.I2_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
3279
3280                                 case Mode.U2_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
3281                                 case Mode.U2_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
3282                                 case Mode.U2_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
3283                                 case Mode.U2_CH: /* nothing */ break;
3284
3285                                 case Mode.I4_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
3286                                 case Mode.I4_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
3287                                 case Mode.I4_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
3288                                 case Mode.I4_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
3289                                 case Mode.I4_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
3290                                 case Mode.I4_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
3291                                 case Mode.I4_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
3292
3293                                 case Mode.U4_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
3294                                 case Mode.U4_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
3295                                 case Mode.U4_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
3296                                 case Mode.U4_U2: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
3297                                 case Mode.U4_I4: ig.Emit (OpCodes.Conv_Ovf_I4_Un); break;
3298                                 case Mode.U4_CH: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
3299
3300                                 case Mode.I8_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
3301                                 case Mode.I8_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
3302                                 case Mode.I8_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
3303                                 case Mode.I8_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
3304                                 case Mode.I8_I4: ig.Emit (OpCodes.Conv_Ovf_I4); break;
3305                                 case Mode.I8_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
3306                                 case Mode.I8_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
3307                                 case Mode.I8_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
3308
3309                                 case Mode.U8_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
3310                                 case Mode.U8_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
3311                                 case Mode.U8_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
3312                                 case Mode.U8_U2: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
3313                                 case Mode.U8_I4: ig.Emit (OpCodes.Conv_Ovf_I4_Un); break;
3314                                 case Mode.U8_U4: ig.Emit (OpCodes.Conv_Ovf_U4_Un); break;
3315                                 case Mode.U8_I8: ig.Emit (OpCodes.Conv_Ovf_I8_Un); break;
3316                                 case Mode.U8_CH: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
3317
3318                                 case Mode.CH_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
3319                                 case Mode.CH_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
3320                                 case Mode.CH_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
3321
3322                                 case Mode.R4_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
3323                                 case Mode.R4_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
3324                                 case Mode.R4_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
3325                                 case Mode.R4_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
3326                                 case Mode.R4_I4: ig.Emit (OpCodes.Conv_Ovf_I4); break;
3327                                 case Mode.R4_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
3328                                 case Mode.R4_I8: ig.Emit (OpCodes.Conv_Ovf_I8); break;
3329                                 case Mode.R4_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
3330                                 case Mode.R4_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
3331
3332                                 case Mode.R8_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
3333                                 case Mode.R8_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
3334                                 case Mode.R8_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
3335                                 case Mode.R8_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
3336                                 case Mode.R8_I4: ig.Emit (OpCodes.Conv_Ovf_I4); break;
3337                                 case Mode.R8_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
3338                                 case Mode.R8_I8: ig.Emit (OpCodes.Conv_Ovf_I8); break;
3339                                 case Mode.R8_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
3340                                 case Mode.R8_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
3341                                 case Mode.R8_R4: ig.Emit (OpCodes.Conv_R4); break;
3342                                 }
3343                         } else {
3344                                 switch (mode){
3345                                 case Mode.I1_U1: ig.Emit (OpCodes.Conv_U1); break;
3346                                 case Mode.I1_U2: ig.Emit (OpCodes.Conv_U2); break;
3347                                 case Mode.I1_U4: ig.Emit (OpCodes.Conv_U4); break;
3348                                 case Mode.I1_U8: ig.Emit (OpCodes.Conv_I8); break;
3349                                 case Mode.I1_CH: ig.Emit (OpCodes.Conv_U2); break;
3350
3351                                 case Mode.U1_I1: ig.Emit (OpCodes.Conv_I1); break;
3352                                 case Mode.U1_CH: ig.Emit (OpCodes.Conv_U2); break;
3353
3354                                 case Mode.I2_I1: ig.Emit (OpCodes.Conv_I1); break;
3355                                 case Mode.I2_U1: ig.Emit (OpCodes.Conv_U1); break;
3356                                 case Mode.I2_U2: ig.Emit (OpCodes.Conv_U2); break;
3357                                 case Mode.I2_U4: ig.Emit (OpCodes.Conv_U4); break;
3358                                 case Mode.I2_U8: ig.Emit (OpCodes.Conv_I8); break;
3359                                 case Mode.I2_CH: ig.Emit (OpCodes.Conv_U2); break;
3360
3361                                 case Mode.U2_I1: ig.Emit (OpCodes.Conv_I1); break;
3362                                 case Mode.U2_U1: ig.Emit (OpCodes.Conv_U1); break;
3363                                 case Mode.U2_I2: ig.Emit (OpCodes.Conv_I2); break;
3364                                 case Mode.U2_CH: /* nothing */ break;
3365
3366                                 case Mode.I4_I1: ig.Emit (OpCodes.Conv_I1); break;
3367                                 case Mode.I4_U1: ig.Emit (OpCodes.Conv_U1); break;
3368                                 case Mode.I4_I2: ig.Emit (OpCodes.Conv_I2); break;
3369                                 case Mode.I4_U4: /* nothing */ break;
3370                                 case Mode.I4_U2: ig.Emit (OpCodes.Conv_U2); break;
3371                                 case Mode.I4_U8: ig.Emit (OpCodes.Conv_I8); break;
3372                                 case Mode.I4_CH: ig.Emit (OpCodes.Conv_U2); break;
3373
3374                                 case Mode.U4_I1: ig.Emit (OpCodes.Conv_I1); break;
3375                                 case Mode.U4_U1: ig.Emit (OpCodes.Conv_U1); break;
3376                                 case Mode.U4_I2: ig.Emit (OpCodes.Conv_I2); break;
3377                                 case Mode.U4_U2: ig.Emit (OpCodes.Conv_U2); break;
3378                                 case Mode.U4_I4: /* nothing */ break;
3379                                 case Mode.U4_CH: ig.Emit (OpCodes.Conv_U2); break;
3380
3381                                 case Mode.I8_I1: ig.Emit (OpCodes.Conv_I1); break;
3382                                 case Mode.I8_U1: ig.Emit (OpCodes.Conv_U1); break;
3383                                 case Mode.I8_I2: ig.Emit (OpCodes.Conv_I2); break;
3384                                 case Mode.I8_U2: ig.Emit (OpCodes.Conv_U2); break;
3385                                 case Mode.I8_I4: ig.Emit (OpCodes.Conv_I4); break;
3386                                 case Mode.I8_U4: ig.Emit (OpCodes.Conv_U4); break;
3387                                 case Mode.I8_U8: /* nothing */ break;
3388                                 case Mode.I8_CH: ig.Emit (OpCodes.Conv_U2); break;
3389
3390                                 case Mode.U8_I1: ig.Emit (OpCodes.Conv_I1); break;
3391                                 case Mode.U8_U1: ig.Emit (OpCodes.Conv_U1); break;
3392                                 case Mode.U8_I2: ig.Emit (OpCodes.Conv_I2); break;
3393                                 case Mode.U8_U2: ig.Emit (OpCodes.Conv_U2); break;
3394                                 case Mode.U8_I4: ig.Emit (OpCodes.Conv_I4); break;
3395                                 case Mode.U8_U4: ig.Emit (OpCodes.Conv_U4); break;
3396                                 case Mode.U8_I8: /* nothing */ break;
3397                                 case Mode.U8_CH: ig.Emit (OpCodes.Conv_U2); break;
3398
3399                                 case Mode.CH_I1: ig.Emit (OpCodes.Conv_I1); break;
3400                                 case Mode.CH_U1: ig.Emit (OpCodes.Conv_U1); break;
3401                                 case Mode.CH_I2: ig.Emit (OpCodes.Conv_I2); break;
3402
3403                                 case Mode.R4_I1: ig.Emit (OpCodes.Conv_I1); break;
3404                                 case Mode.R4_U1: ig.Emit (OpCodes.Conv_U1); break;
3405                                 case Mode.R4_I2: ig.Emit (OpCodes.Conv_I2); break;
3406                                 case Mode.R4_U2: ig.Emit (OpCodes.Conv_U2); break;
3407                                 case Mode.R4_I4: ig.Emit (OpCodes.Conv_I4); break;
3408                                 case Mode.R4_U4: ig.Emit (OpCodes.Conv_U4); break;
3409                                 case Mode.R4_I8: ig.Emit (OpCodes.Conv_I8); break;
3410                                 case Mode.R4_U8: ig.Emit (OpCodes.Conv_U8); break;
3411                                 case Mode.R4_CH: ig.Emit (OpCodes.Conv_U2); break;
3412
3413                                 case Mode.R8_I1: ig.Emit (OpCodes.Conv_I1); break;
3414                                 case Mode.R8_U1: ig.Emit (OpCodes.Conv_U1); break;
3415                                 case Mode.R8_I2: ig.Emit (OpCodes.Conv_I2); break;
3416                                 case Mode.R8_U2: ig.Emit (OpCodes.Conv_U2); break;
3417                                 case Mode.R8_I4: ig.Emit (OpCodes.Conv_I4); break;
3418                                 case Mode.R8_U4: ig.Emit (OpCodes.Conv_U4); break;
3419                                 case Mode.R8_I8: ig.Emit (OpCodes.Conv_I8); break;
3420                                 case Mode.R8_U8: ig.Emit (OpCodes.Conv_U8); break;
3421                                 case Mode.R8_CH: ig.Emit (OpCodes.Conv_U2); break;
3422                                 case Mode.R8_R4: ig.Emit (OpCodes.Conv_R4); break;
3423                                 }
3424                         }
3425                 }
3426         }
3427         
3428         public class OpcodeCast : EmptyCast {
3429                 OpCode op, op2;
3430                 bool second_valid;
3431                 
3432                 public OpcodeCast (Expression child, Type return_type, OpCode op)
3433                         : base (child, return_type)
3434                         
3435                 {
3436                         this.op = op;
3437                         second_valid = false;
3438                 }
3439
3440                 public OpcodeCast (Expression child, Type return_type, OpCode op, OpCode op2)
3441                         : base (child, return_type)
3442                         
3443                 {
3444                         this.op = op;
3445                         this.op2 = op2;
3446                         second_valid = true;
3447                 }
3448
3449                 public override Expression DoResolve (EmitContext ec)
3450                 {
3451                         // This should never be invoked, we are born in fully
3452                         // initialized state.
3453
3454                         return this;
3455                 }
3456
3457                 public override void Emit (EmitContext ec)
3458                 {
3459                         base.Emit (ec);
3460                         ec.ig.Emit (op);
3461
3462                         if (second_valid)
3463                                 ec.ig.Emit (op2);
3464                 }                       
3465         }
3466
3467         /// <summary>
3468         ///   This kind of cast is used to encapsulate a child and cast it
3469         ///   to the class requested
3470         /// </summary>
3471         public class ClassCast : EmptyCast {
3472                 public ClassCast (Expression child, Type return_type)
3473                         : base (child, return_type)
3474                         
3475                 {
3476                 }
3477
3478                 public override Expression DoResolve (EmitContext ec)
3479                 {
3480                         // This should never be invoked, we are born in fully
3481                         // initialized state.
3482
3483                         return this;
3484                 }
3485
3486                 public override void Emit (EmitContext ec)
3487                 {
3488                         base.Emit (ec);
3489
3490                         ec.ig.Emit (OpCodes.Castclass, type);
3491                 }                       
3492                 
3493         }
3494         
3495         /// <summary>
3496         ///   SimpleName expressions are initially formed of a single
3497         ///   word and it only happens at the beginning of the expression.
3498         /// </summary>
3499         ///
3500         /// <remarks>
3501         ///   The expression will try to be bound to a Field, a Method
3502         ///   group or a Property.  If those fail we pass the name to our
3503         ///   caller and the SimpleName is compounded to perform a type
3504         ///   lookup.  The idea behind this process is that we want to avoid
3505         ///   creating a namespace map from the assemblies, as that requires
3506         ///   the GetExportedTypes function to be called and a hashtable to
3507         ///   be constructed which reduces startup time.  If later we find
3508         ///   that this is slower, we should create a 'NamespaceExpr' expression
3509         ///   that fully participates in the resolution process. 
3510         ///   
3511         ///   For example 'System.Console.WriteLine' is decomposed into
3512         ///   MemberAccess (MemberAccess (SimpleName ("System"), "Console"), "WriteLine")
3513         ///   
3514         ///   The first SimpleName wont produce a match on its own, so it will
3515         ///   be turned into:
3516         ///   MemberAccess (SimpleName ("System.Console"), "WriteLine").
3517         ///   
3518         ///   System.Console will produce a TypeExpr match.
3519         ///   
3520         ///   The downside of this is that we might be hitting 'LookupType' too many
3521         ///   times with this scheme.
3522         /// </remarks>
3523         public class SimpleName : Expression, ITypeExpression {
3524                 public readonly string Name;
3525                 
3526                 public SimpleName (string name, Location l)
3527                 {
3528                         Name = name;
3529                         loc = l;
3530                 }
3531
3532                 public static void Error_ObjectRefRequired (EmitContext ec, Location l, string name)
3533                 {
3534                         if (ec.IsFieldInitializer)
3535                                 Report.Error (
3536                                         236, l,
3537                                         "A field initializer cannot reference the non-static field, " +
3538                                         "method or property '"+name+"'");
3539                         else
3540                                 Report.Error (
3541                                         120, l,
3542                                         "An object reference is required " +
3543                                         "for the non-static field '"+name+"'");
3544                 }
3545                 
3546                 //
3547                 // Checks whether we are trying to access an instance
3548                 // property, method or field from a static body.
3549                 //
3550                 Expression MemberStaticCheck (EmitContext ec, Expression e)
3551                 {
3552                         if (e is IMemberExpr){
3553                                 IMemberExpr member = (IMemberExpr) e;
3554                                 
3555                                 if (!member.IsStatic){
3556                                         Error_ObjectRefRequired (ec, loc, Name);
3557                                         return null;
3558                                 }
3559                         }
3560
3561                         return e;
3562                 }
3563                 
3564                 public override Expression DoResolve (EmitContext ec)
3565                 {
3566                         return SimpleNameResolve (ec, null, false);
3567                 }
3568
3569                 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
3570                 {
3571                         return SimpleNameResolve (ec, right_side, false);
3572                 }
3573                 
3574
3575                 public Expression DoResolveAllowStatic (EmitContext ec)
3576                 {
3577                         return SimpleNameResolve (ec, null, true);
3578                 }
3579
3580                 public Expression DoResolveType (EmitContext ec)
3581                 {
3582                         //
3583                         // Stage 3: Lookup symbol in the various namespaces. 
3584                         //
3585                         DeclSpace ds = ec.DeclSpace;
3586                         Type t;
3587                         string alias_value;
3588
3589                         if (ec.ResolvingTypeTree){
3590                                 int errors = Report.Errors;
3591                                 Type dt = ec.DeclSpace.FindType (loc, Name);
3592                                 if (Report.Errors != errors)
3593                                         return null;
3594                                 
3595                                 if (dt != null)
3596                                         return new TypeExpr (dt, loc);
3597                         }
3598
3599                         if ((t = RootContext.LookupType (ds, Name, true, loc)) != null)
3600                                 return new TypeExpr (t, loc);
3601                                 
3602
3603                         //
3604                         // Stage 2 part b: Lookup up if we are an alias to a type
3605                         // or a namespace.
3606                         //
3607                         // Since we are cheating: we only do the Alias lookup for
3608                         // namespaces if the name does not include any dots in it
3609                         //
3610                                 
3611                         alias_value = ec.DeclSpace.LookupAlias (Name);
3612                                 
3613                         if (Name.IndexOf ('.') == -1 && alias_value != null) {
3614                                 if ((t = RootContext.LookupType (ds, alias_value, true, loc)) != null)
3615                                         return new TypeExpr (t, loc);
3616                                         
3617                                 // we have alias value, but it isn't Type, so try if it's namespace
3618                                 return new SimpleName (alias_value, loc);
3619                         }
3620                                 
3621                         // No match, maybe our parent can compose us
3622                         // into something meaningful.
3623                         return this;
3624                 }
3625
3626                 /// <remarks>
3627                 ///   7.5.2: Simple Names. 
3628                 ///
3629                 ///   Local Variables and Parameters are handled at
3630                 ///   parse time, so they never occur as SimpleNames.
3631                 ///
3632                 ///   The 'allow_static' flag is used by MemberAccess only
3633                 ///   and it is used to inform us that it is ok for us to 
3634                 ///   avoid the static check, because MemberAccess might end
3635                 ///   up resolving the Name as a Type name and the access as
3636                 ///   a static type access.
3637                 ///
3638                 ///   ie: Type Type; .... { Type.GetType (""); }
3639                 ///
3640                 ///   Type is both an instance variable and a Type;  Type.GetType
3641                 ///   is the static method not an instance method of type.
3642                 /// </remarks>
3643                 Expression SimpleNameResolve (EmitContext ec, Expression right_side, bool allow_static)
3644                 {
3645                         Expression e = null;
3646                         
3647                         //
3648                         // Stage 1: Performed by the parser (binding to locals or parameters).
3649                         //
3650                         Block current_block = ec.CurrentBlock;
3651                         if (ec.InvokingOwnOverload == false && current_block != null && current_block.IsVariableDefined (Name)){
3652                                 LocalVariableReference var;
3653
3654                                 var = new LocalVariableReference (ec.CurrentBlock, Name, loc);
3655
3656                                 if (right_side != null)
3657                                         return var.ResolveLValue (ec, right_side);
3658                                 else
3659                                         return var.Resolve (ec);
3660                         }
3661
3662                         if (current_block != null){
3663                                 int idx = -1;
3664                                 Parameter par = null;
3665                                 Parameters pars = current_block.Parameters;
3666                                 if (pars != null)
3667                                         par = pars.GetParameterByName (Name, out idx);
3668
3669                                 if (par != null) {
3670                                         ParameterReference param;
3671                                         
3672                                         param = new ParameterReference (pars, idx, Name, loc);
3673
3674                                         if (right_side != null)
3675                                                 return param.ResolveLValue (ec, right_side);
3676                                         else
3677                                                 return param.Resolve (ec);
3678                                 }
3679                         }
3680
3681                         //
3682                         // Stage 2: Lookup members 
3683                         //
3684
3685                         //
3686                         // For enums, the TypeBuilder is not ec.DeclSpace.TypeBuilder
3687                         // Hence we have two different cases
3688                         //
3689
3690                         DeclSpace lookup_ds = ec.DeclSpace;
3691                         do {
3692                                 if (lookup_ds.TypeBuilder == null)
3693                                         break;
3694
3695                                 e = MemberLookup (ec, lookup_ds.TypeBuilder, Name, loc);
3696                                 if (e != null)
3697                                         break;
3698
3699                                 //
3700                                 // Classes/structs keep looking, enums break
3701                                 //
3702                                 if (lookup_ds is TypeContainer)
3703                                         lookup_ds = ((TypeContainer) lookup_ds).Parent;
3704                                 else
3705                                         break;
3706                         } while (lookup_ds != null);
3707                                 
3708                         if (e == null && ec.ContainerType != null)
3709                                 e = MemberLookup (ec, ec.ContainerType, Name, loc);
3710
3711 // #52067 - Start - Trying to solve
3712
3713                         if (e == null) {
3714                                 
3715                                 ArrayList lookups = new ArrayList();
3716                                 ArrayList typelookups = new ArrayList();
3717                                 
3718                                 int split = Name.LastIndexOf('.');
3719                                 if (split != -1) {
3720                                         String nameSpacePart = Name.Substring(0, split);
3721                                         String memberNamePart = Name.Substring(split + 1);
3722                                         foreach(Type type in TypeManager.GetPertinentStandardModules(nameSpacePart)) {
3723                                                 e = MemberLookup(ec, type, memberNamePart, loc);
3724                                                 if (e != null) {
3725                                                         lookups.Add(e);
3726                                                         typelookups.Add(type);
3727                                                 }
3728                                         }
3729                                 }
3730                                 
3731                                 string[] NamespacesInScope = RootContext.SourceBeingCompiled.GetNamespacesInScope(ec.DeclSpace.Namespace.Name);
3732                                 foreach(Type type in TypeManager.GetPertinentStandardModules(NamespacesInScope)) {
3733                                         e = MemberLookup(ec, type, Name, loc);
3734                                         if (e != null) {
3735                                                 lookups.Add(e);
3736                                                 typelookups.Add(type);
3737                                         }
3738                                 }
3739                                 if (lookups.Count == 1) { 
3740                                         e = (Expression)lookups[0];
3741                                 } else {
3742                                         if (lookups.Count > 1) {
3743                                                 StringBuilder sb = new StringBuilder();
3744                                                 foreach(Type type in typelookups)
3745                                                         sb.Append("'" + type.FullName + "'");                                           
3746                                                 Error (-1, "The name '" + Name + "' can be resolved to a member of more than one standard module: " + sb.ToString() + ". Please fully qualify it.");
3747                                                 return null;
3748                                         }
3749                                 }
3750                         }
3751
3752 // #52067 - End
3753
3754                         if (e == null)
3755                                 return DoResolveType (ec);
3756
3757                         if (e is TypeExpr)
3758                                 return e;
3759
3760                         if (e is IMemberExpr) {
3761                                 e = MemberAccess.ResolveMemberAccess (ec, e, null, loc, this);
3762                                 if (e == null)
3763                                         return null;
3764
3765                                 IMemberExpr me = e as IMemberExpr;
3766                                 if (me == null)
3767                                         return e;
3768
3769                                 // This fails if ResolveMemberAccess() was unable to decide whether
3770                                 // it's a field or a type of the same name.
3771                                 if (!me.IsStatic && (me.InstanceExpression == null))
3772                                         return e;
3773
3774 /* FIXME    If this is not commented out, it seems that it's not possible to reach class members in mBas.
3775             Maybe a grammar-related problem?
3776
3777                                 if (!me.IsStatic &&
3778                                     TypeManager.IsNestedChildOf (me.InstanceExpression.Type, me.DeclaringType)) {
3779                                         Error (38, "Cannot access nonstatic member '" + me.Name + "' of " +
3780                                                "outer type '" + me.DeclaringType + "' via nested type '" +
3781                                                me.InstanceExpression.Type + "'");
3782                                         return null;
3783                                 }
3784 */
3785                                 if (right_side != null)
3786                                         e = e.DoResolveLValue (ec, right_side);
3787                                 else
3788                                         e = e.DoResolve (ec);
3789
3790                                 return e;
3791                         }
3792
3793                         if (ec.IsStatic || ec.IsFieldInitializer){
3794                                 if (allow_static)
3795                                         return e;
3796
3797                                 return MemberStaticCheck (ec, e);
3798                         } else
3799                                 return e;
3800                 }
3801                 
3802                 public override void Emit (EmitContext ec)
3803                 {
3804                         //
3805                         // If this is ever reached, then we failed to
3806                         // find the name as a namespace
3807                         //
3808
3809                         Error (30451, "The name '" + Name +
3810                                "' does not exist in the class '" +
3811                                ec.DeclSpace.Name + "'");
3812                 }
3813
3814                 public override string ToString ()
3815                 {
3816                         return Name;
3817                 }
3818         }
3819         
3820         /// <summary>
3821         ///   Fully resolved expression that evaluates to a type
3822         /// </summary>
3823         public class TypeExpr : Expression, ITypeExpression {
3824                 public TypeExpr (Type t, Location l)
3825                 {
3826                         Type = t;
3827                         eclass = ExprClass.Type;
3828                         loc = l;
3829                 }
3830
3831                 public virtual Expression DoResolveType (EmitContext ec)
3832                 {
3833                         return this;
3834                 }
3835
3836                 override public Expression DoResolve (EmitContext ec)
3837                 {
3838                         return this;
3839                 }
3840
3841                 override public void Emit (EmitContext ec)
3842                 {
3843                         throw new Exception ("Should never be called");
3844                 }
3845
3846                 public override string ToString ()
3847                 {
3848                         return Type.ToString ();
3849                 }
3850         }
3851
3852         /// <summary>
3853         ///   Used to create types from a fully qualified name.  These are just used
3854         ///   by the parser to setup the core types.  A TypeLookupExpression is always
3855         ///   classified as a type.
3856         /// </summary>
3857         public class TypeLookupExpression : TypeExpr {
3858                 string name;
3859                 
3860                 public TypeLookupExpression (string name) : base (null, Location.Null)
3861                 {
3862                         this.name = name;
3863                 }
3864
3865                 public override Expression DoResolveType (EmitContext ec)
3866                 {
3867                         if (type == null)
3868                                 type = RootContext.LookupType (ec.DeclSpace, name, false, Location.Null);
3869                         return this;
3870                 }
3871
3872                 public override Expression DoResolve (EmitContext ec)
3873                 {
3874                         return DoResolveType (ec);
3875                 }
3876
3877                 public override void Emit (EmitContext ec)
3878                 {
3879                         throw new Exception ("Should never be called");
3880                 }
3881
3882                 public override string ToString ()
3883                 {
3884                         return name;
3885                 }
3886         }
3887
3888         /// <summary>
3889         ///   MethodGroup Expression.
3890         ///  
3891         ///   This is a fully resolved expression that evaluates to a type
3892         /// </summary>
3893         public class MethodGroupExpr : Expression, IMemberExpr {
3894                 public MethodBase [] Methods;
3895                 Expression instance_expression = null;
3896                 bool is_explicit_impl = false;
3897                 
3898                 public MethodGroupExpr (MemberInfo [] mi, Location l)
3899                 {
3900                         Methods = new MethodBase [mi.Length];
3901                         mi.CopyTo (Methods, 0);
3902                         eclass = ExprClass.MethodGroup;
3903                         type = TypeManager.object_type;
3904                         loc = l;
3905                 }
3906
3907                 public MethodGroupExpr (ArrayList list, Location l)
3908                 {
3909                         Methods = new MethodBase [list.Count];
3910
3911                         try {
3912                                 list.CopyTo (Methods, 0);
3913                         } catch {
3914                                 foreach (MemberInfo m in list){
3915                                         if (!(m is MethodBase)){
3916                                                 Console.WriteLine ("Name " + m.Name);
3917                                                 Console.WriteLine ("Found a: " + m.GetType ().FullName);
3918                                         }
3919                                 }
3920                                 throw;
3921                         }
3922                         loc = l;
3923                         eclass = ExprClass.MethodGroup;
3924                         type = TypeManager.object_type;
3925                 }
3926
3927                 public Type DeclaringType {
3928                         get {
3929                                 return Methods [0].DeclaringType;
3930                         }
3931                 }
3932                 
3933                 //
3934                 // 'A method group may have associated an instance expression' 
3935                 // 
3936                 public Expression InstanceExpression {
3937                         get {
3938                                 return instance_expression;
3939                         }
3940
3941                         set {
3942                                 instance_expression = value;
3943                         }
3944                 }
3945
3946                 public bool IsExplicitImpl {
3947                         get {
3948                                 return is_explicit_impl;
3949                         }
3950
3951                         set {
3952                                 is_explicit_impl = value;
3953                         }
3954                 }
3955
3956                 public string Name {
3957                         get {
3958                                 return Methods [0].Name;
3959                         }
3960                 }
3961
3962                 public bool IsInstance {
3963                         get {
3964                                 foreach (MethodBase mb in Methods)
3965                                         if (!mb.IsStatic)
3966                                                 return true;
3967
3968                                 return false;
3969                         }
3970                 }
3971
3972                 public bool IsStatic {
3973                         get {
3974                                 foreach (MethodBase mb in Methods)
3975                                         if (mb.IsStatic)
3976                                                 return true;
3977
3978                                 return false;
3979                         }
3980                 }
3981                 
3982                 override public Expression DoResolve (EmitContext ec)
3983                 {
3984                         if (instance_expression != null) {
3985                                 instance_expression = instance_expression.DoResolve (ec);
3986                                 if (instance_expression == null)
3987                                         return null;
3988                         }
3989
3990                         return this;
3991                 }
3992
3993                 public void ReportUsageError ()
3994                 {
3995                         Report.Error (654, loc, "Method '" + Methods [0].DeclaringType + "." +
3996                                       Methods [0].Name + "()' is referenced without parentheses");
3997                 }
3998
3999                 override public void Emit (EmitContext ec)
4000                 {
4001                         ReportUsageError ();
4002                 }
4003
4004                 bool RemoveMethods (bool keep_static)
4005                 {
4006                         ArrayList smethods = new ArrayList ();
4007
4008                         foreach (MethodBase mb in Methods){
4009                                 if (mb.IsStatic == keep_static)
4010                                         smethods.Add (mb);
4011                         }
4012
4013                         if (smethods.Count == 0)
4014                                 return false;
4015
4016                         Methods = new MethodBase [smethods.Count];
4017                         smethods.CopyTo (Methods, 0);
4018
4019                         return true;
4020                 }
4021                 
4022                 /// <summary>
4023                 ///   Removes any instance methods from the MethodGroup, returns
4024                 ///   false if the resulting set is empty.
4025                 /// </summary>
4026                 public bool RemoveInstanceMethods ()
4027                 {
4028                         return RemoveMethods (true);
4029                 }
4030
4031                 /// <summary>
4032                 ///   Removes any static methods from the MethodGroup, returns
4033                 ///   false if the resulting set is empty.
4034                 /// </summary>
4035                 public bool RemoveStaticMethods ()
4036                 {
4037                         return RemoveMethods (false);
4038                 }
4039         }
4040
4041         /// <summary>
4042         ///   Fully resolved expression that evaluates to a Field
4043         /// </summary>
4044         public class FieldExpr : Expression, IAssignMethod, IMemoryLocation, IMemberExpr {
4045                 public readonly FieldInfo FieldInfo;
4046                 Expression instance_expr;
4047                 
4048                 public FieldExpr (FieldInfo fi, Location l)
4049                 {
4050                         FieldInfo = fi;
4051                         eclass = ExprClass.Variable;
4052                         type = fi.FieldType;
4053                         loc = l;
4054                 }
4055
4056                 public string Name {
4057                         get {
4058                                 return FieldInfo.Name;
4059                         }
4060                 }
4061
4062                 public bool IsInstance {
4063                         get {
4064                                 return !FieldInfo.IsStatic;
4065                         }
4066                 }
4067
4068                 public bool IsStatic {
4069                         get {
4070                                 return FieldInfo.IsStatic;
4071                         }
4072                 }
4073
4074                 public Type DeclaringType {
4075                         get {
4076                                 return FieldInfo.DeclaringType;
4077                         }
4078                 }
4079
4080                 public Expression InstanceExpression {
4081                         get {
4082                                 return instance_expr;
4083                         }
4084
4085                         set {
4086                                 instance_expr = value;
4087                         }
4088                 }
4089
4090                 override public Expression DoResolve (EmitContext ec)
4091                 {
4092                         if (!FieldInfo.IsStatic){
4093                                 if (instance_expr == null){
4094                                         throw new Exception ("non-static FieldExpr without instance var\n" +
4095                                                              "You have to assign the Instance variable\n" +
4096                                                              "Of the FieldExpr to set this\n");
4097                                 }
4098
4099                                 // Resolve the field's instance expression while flow analysis is turned
4100                                 // off: when accessing a field "a.b", we must check whether the field
4101                                 // "a.b" is initialized, not whether the whole struct "a" is initialized.
4102                                 instance_expr = instance_expr.Resolve (ec, ResolveFlags.VariableOrValue |
4103                                                                        ResolveFlags.DisableFlowAnalysis);
4104                                 if (instance_expr == null)
4105                                         return null;
4106                         }
4107
4108                         // If the instance expression is a local variable or parameter.
4109                         IVariable var = instance_expr as IVariable;
4110                         if ((var != null) && !var.IsFieldAssigned (ec, FieldInfo.Name, loc))
4111                                 return null;
4112
4113                         return this;
4114                 }
4115
4116                 void Report_AssignToReadonly (bool is_instance)
4117                 {
4118                         string msg;
4119                         
4120                         if (is_instance)
4121                                 msg = "Readonly field can not be assigned outside " +
4122                                 "of constructor or variable initializer";
4123                         else
4124                                 msg = "A static readonly field can only be assigned in " +
4125                                 "a static constructor";
4126
4127                         Report.Error (is_instance ? 191 : 198, loc, msg);
4128                 }
4129                 
4130                 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
4131                 {
4132                         IVariable var = instance_expr as IVariable;
4133                         if (var != null)
4134                                 var.SetFieldAssigned (ec, FieldInfo.Name);
4135
4136                         Expression e = DoResolve (ec);
4137
4138                         if (e == null)
4139                                 return null;
4140                         
4141                         if (!FieldInfo.IsInitOnly)
4142                                 return this;
4143
4144                         //
4145                         // InitOnly fields can only be assigned in constructors
4146                         //
4147
4148                         if (ec.IsConstructor)
4149                                 return this;
4150
4151                         Report_AssignToReadonly (true);
4152                         
4153                         return null;
4154                 }
4155
4156                 override public void Emit (EmitContext ec)
4157                 {
4158                         ILGenerator ig = ec.ig;
4159                         bool is_volatile = false;
4160
4161                         if (FieldInfo is FieldBuilder){
4162                                 FieldBase f = TypeManager.GetField (FieldInfo);
4163
4164                                 if ((f.ModFlags & Modifiers.VOLATILE) != 0)
4165                                         is_volatile = true;
4166                                 
4167                                 f.status |= Field.Status.USED;
4168                         }
4169                         
4170                         if (FieldInfo.IsStatic){
4171                                 if (is_volatile)
4172                                         ig.Emit (OpCodes.Volatile);
4173                                 
4174                                 ig.Emit (OpCodes.Ldsfld, FieldInfo);
4175                         } else {
4176                                 if (instance_expr.Type.IsValueType){
4177                                         IMemoryLocation ml;
4178                                         LocalTemporary tempo = null;
4179                                         
4180                                         if (!(instance_expr is IMemoryLocation)){
4181                                                 tempo = new LocalTemporary (
4182                                                         ec, instance_expr.Type);
4183
4184                                                 InstanceExpression.Emit (ec);
4185                                                 tempo.Store (ec);
4186                                                 ml = tempo;
4187                                         } else
4188                                                 ml = (IMemoryLocation) instance_expr;
4189
4190                                         ml.AddressOf (ec, AddressOp.Load);
4191                                 } else 
4192                                         instance_expr.Emit (ec);
4193
4194                                 if (is_volatile)
4195                                         ig.Emit (OpCodes.Volatile);
4196                                 
4197                                 ig.Emit (OpCodes.Ldfld, FieldInfo);
4198                         }
4199                 }
4200
4201                 public void EmitAssign (EmitContext ec, Expression source)
4202                 {
4203                         FieldAttributes fa = FieldInfo.Attributes;
4204                         bool is_static = (fa & FieldAttributes.Static) != 0;
4205                         bool is_readonly = (fa & FieldAttributes.InitOnly) != 0;
4206                         ILGenerator ig = ec.ig;
4207
4208                         if (is_readonly && !ec.IsConstructor){
4209                                 Report_AssignToReadonly (!is_static);
4210                                 return;
4211                         }
4212                         
4213                         if (!is_static){
4214                                 Expression instance = instance_expr;
4215
4216                                 if (instance.Type.IsValueType){
4217                                         if (instance is IMemoryLocation){
4218                                                 IMemoryLocation ml = (IMemoryLocation) instance;
4219
4220                                                 ml.AddressOf (ec, AddressOp.Store);
4221                                         } else
4222                                                 throw new Exception ("The " + instance + " of type " +
4223                                                                      instance.Type +
4224                                                                      " represents a ValueType and does " +
4225                                                                      "not implement IMemoryLocation");
4226                                 } else
4227                                         instance.Emit (ec);
4228                         }
4229                         source.Emit (ec);
4230
4231                         if (FieldInfo is FieldBuilder){
4232                                 FieldBase f = TypeManager.GetField (FieldInfo);
4233                                 
4234                                 if ((f.ModFlags & Modifiers.VOLATILE) != 0)
4235                                         ig.Emit (OpCodes.Volatile);
4236                         }
4237                         
4238                         if (is_static)
4239                                 ig.Emit (OpCodes.Stsfld, FieldInfo);
4240                         else 
4241                                 ig.Emit (OpCodes.Stfld, FieldInfo);
4242
4243                         if (FieldInfo is FieldBuilder){
4244                                 FieldBase f = TypeManager.GetField (FieldInfo);
4245
4246                                 f.status |= Field.Status.ASSIGNED;
4247                         }
4248                 }
4249                 
4250                 public void AddressOf (EmitContext ec, AddressOp mode)
4251                 {
4252                         ILGenerator ig = ec.ig;
4253                         
4254                         if (FieldInfo is FieldBuilder){
4255                                 FieldBase f = TypeManager.GetField (FieldInfo);
4256                                 if ((f.ModFlags & Modifiers.VOLATILE) != 0)
4257                                         ig.Emit (OpCodes.Volatile);
4258                         }
4259
4260                         if (FieldInfo is FieldBuilder){
4261                                 FieldBase f = TypeManager.GetField (FieldInfo);
4262
4263                                 if ((mode & AddressOp.Store) != 0)
4264                                         f.status |= Field.Status.ASSIGNED;
4265                                 if ((mode & AddressOp.Load) != 0)
4266                                         f.status |= Field.Status.USED;
4267                         }
4268
4269                         //
4270                         // Handle initonly fields specially: make a copy and then
4271                         // get the address of the copy.
4272                         //
4273                         if (FieldInfo.IsInitOnly && !ec.IsConstructor){
4274                                 LocalBuilder local;
4275                                 
4276                                 Emit (ec);
4277                                 local = ig.DeclareLocal (type);
4278                                 ig.Emit (OpCodes.Stloc, local);
4279                                 ig.Emit (OpCodes.Ldloca, local);
4280                                 return;
4281                         }
4282
4283                         if (FieldInfo.IsStatic)
4284                                 ig.Emit (OpCodes.Ldsflda, FieldInfo);
4285                         else {
4286                                 if (instance_expr is IMemoryLocation)
4287                                         ((IMemoryLocation)instance_expr).AddressOf (ec, AddressOp.LoadStore);
4288                                 else
4289                                         instance_expr.Emit (ec);
4290                                 ig.Emit (OpCodes.Ldflda, FieldInfo);
4291                         }
4292                 }
4293         }
4294         
4295         /// <summary>
4296         ///   Expression that evaluates to a Property.  The Assign class
4297         ///   might set the 'Value' expression if we are in an assignment.
4298         ///
4299         ///   This is not an LValue because we need to re-write the expression, we
4300         ///   can not take data from the stack and store it.  
4301         /// </summary>
4302         public class PropertyExpr : ExpressionStatement, IAssignMethod, IMemberExpr {
4303                 public readonly PropertyInfo PropertyInfo;
4304                 public bool IsBase;
4305                 MethodInfo getter, setter;
4306                 bool is_static;
4307                 public ArrayList PropertyArgs;
4308
4309                 Expression instance_expr;
4310
4311                 public PropertyExpr (EmitContext ec, PropertyInfo pi, Location l)
4312                 {
4313                         PropertyInfo = pi;
4314                         eclass = ExprClass.PropertyAccess;
4315                         PropertyArgs = new ArrayList();
4316                         is_static = false;
4317                         loc = l;
4318
4319                         type = TypeManager.TypeToCoreType (pi.PropertyType);
4320
4321                         ResolveAccessors (ec);
4322                 }
4323
4324                 public string Name {
4325                         get {
4326                                 return PropertyInfo.Name;
4327                         }
4328                 }
4329
4330                 public bool IsInstance {
4331                         get {
4332                                 return !is_static;
4333                         }
4334                 }
4335
4336                 public bool IsStatic {
4337                         get {
4338                                 return is_static;
4339                         }
4340                 }
4341                 
4342                 public Type DeclaringType {
4343                         get {
4344                                 return PropertyInfo.DeclaringType;
4345                         }
4346                 }
4347
4348                 //
4349                 // The instance expression associated with this expression
4350                 //
4351                 public Expression InstanceExpression {
4352                         set {
4353                                 instance_expr = value;
4354                         }
4355
4356                         get {
4357                                 return instance_expr;
4358                         }
4359                 }
4360
4361                 public bool VerifyAssignable ()
4362                 {
4363                         if (!PropertyInfo.CanWrite){
4364                                 Report.Error (200, loc, 
4365                                               "The property '" + PropertyInfo.Name +
4366                                               "' can not be assigned to, as it has not set accessor");
4367                                 return false;
4368                         }
4369
4370                         return true;
4371                 }
4372
4373                 void ResolveAccessors (EmitContext ec)
4374                 {
4375                         BindingFlags flags = BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance;
4376                         MemberInfo [] group;
4377                         
4378                         group = TypeManager.MemberLookup (ec.ContainerType, PropertyInfo.DeclaringType,
4379                                                               MemberTypes.Method, flags, "get_" + PropertyInfo.Name);
4380
4381                         //
4382                         // The first method is the closest to us
4383                         //
4384                         if (group != null && group.Length > 0){
4385                                 getter = (MethodInfo) group [0];
4386
4387                                 if (getter.IsStatic)
4388                                         is_static = true;
4389                         }                       
4390
4391                         //
4392                         // The first method is the closest to us
4393                         //
4394                         group = TypeManager.MemberLookup (ec.ContainerType, PropertyInfo.DeclaringType,
4395                                                           MemberTypes.Method, flags, "set_" + PropertyInfo.Name);
4396                         if (group != null && group.Length > 0){
4397                                 setter = (MethodInfo) group [0];
4398                                 if (setter.IsStatic)
4399                                         is_static = true;
4400                         }
4401                 }
4402
4403                 override public Expression DoResolve (EmitContext ec)
4404                 {
4405                         if (getter == null){
4406                                 Report.Error (154, loc, 
4407                                               "The property '" + PropertyInfo.Name +
4408                                               "' can not be used in " +
4409                                               "this context because it lacks a get accessor");
4410                                 return null;
4411                         }
4412
4413                         if ((instance_expr == null) && ec.IsStatic && !is_static) {
4414                                 SimpleName.Error_ObjectRefRequired (ec, loc, PropertyInfo.Name);
4415                                 return null;
4416                         }
4417
4418                         if (instance_expr != null) {
4419                                 instance_expr = instance_expr.DoResolve (ec);
4420                                 if (instance_expr == null)
4421                                         return null;
4422                         }
4423
4424                         return this;
4425                 }
4426
4427                 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
4428                 {
4429                         if (setter == null){
4430                                 Report.Error (154, loc, 
4431                                               "The property '" + PropertyInfo.Name +
4432                                               "' can not be used in " +
4433                                               "this context because it lacks a set accessor");
4434                                 return null;
4435                         }
4436
4437                         if (instance_expr != null) {
4438                                 instance_expr = instance_expr.DoResolve (ec);
4439                                 if (instance_expr == null)
4440                                         return null;
4441                         }
4442
4443                         return this;
4444                 }
4445
4446                 override public void Emit (EmitContext ec)
4447                 {
4448                         //
4449                         // Special case: length of single dimension array property is turned into ldlen
4450                         //
4451                         if ((getter == TypeManager.system_int_array_get_length) ||
4452                             (getter == TypeManager.int_array_get_length)){
4453                                 Type iet = instance_expr.Type;
4454
4455                                 //
4456                                 // System.Array.Length can be called, but the Type does not
4457                                 // support invoking GetArrayRank, so test for that case first
4458                                 //
4459                                 if (iet != TypeManager.array_type && (iet.GetArrayRank () == 1)){
4460                                         instance_expr.Emit (ec);
4461                                         ec.ig.Emit (OpCodes.Ldlen);
4462                                         return;
4463                                 }
4464                         }
4465                         Invocation.EmitCall (ec, IsBase, IsStatic, instance_expr, getter, null, PropertyArgs, loc);
4466                 }
4467
4468                 //
4469                 // Implements the IAssignMethod interface for assignments
4470                 //
4471                 public void EmitAssign (EmitContext ec, Expression source)
4472                 {
4473                         Argument arg = new Argument (source, Argument.AType.Expression);
4474                         ArrayList args = new ArrayList ();
4475 //HERE
4476                         args.Add (arg);
4477                         Invocation.EmitCall (ec, IsBase, IsStatic, instance_expr, setter, args, PropertyArgs,loc);
4478                 }
4479
4480                 override public void EmitStatement (EmitContext ec)
4481                 {
4482                         Emit (ec);
4483                         ec.ig.Emit (OpCodes.Pop);
4484                 }
4485         }
4486
4487         /// <summary>
4488         ///   Fully resolved expression that evaluates to an Event
4489         /// </summary>
4490         public class EventExpr : Expression, IMemberExpr {
4491                 public readonly EventInfo EventInfo;
4492                 public Expression instance_expr;
4493
4494                 bool is_static;
4495                 MethodInfo add_accessor, remove_accessor;
4496                 
4497                 public EventExpr (EventInfo ei, Location loc)
4498                 {
4499                         EventInfo = ei;
4500                         this.loc = loc;
4501                         eclass = ExprClass.EventAccess;
4502
4503                         add_accessor = TypeManager.GetAddMethod (ei);
4504                         remove_accessor = TypeManager.GetRemoveMethod (ei);
4505                         
4506                         if (add_accessor.IsStatic || remove_accessor.IsStatic)
4507                                 is_static = true;
4508
4509                         if (EventInfo is MyEventBuilder)
4510                                 type = ((MyEventBuilder) EventInfo).EventType;
4511                         else
4512                                 type = EventInfo.EventHandlerType;
4513                 }
4514
4515                 public string Name {
4516                         get {
4517                                 return EventInfo.Name;
4518                         }
4519                 }
4520
4521                 public bool IsInstance {
4522                         get {
4523                                 return !is_static;
4524                         }
4525                 }
4526
4527                 public bool IsStatic {
4528                         get {
4529                                 return is_static;
4530                         }
4531                 }
4532
4533                 public Type DeclaringType {
4534                         get {
4535                                 return EventInfo.DeclaringType;
4536                         }
4537                 }
4538
4539                 public Expression InstanceExpression {
4540                         get {
4541                                 return instance_expr;
4542                         }
4543
4544                         set {
4545                                 instance_expr = value;
4546                         }
4547                 }
4548
4549                 public override Expression DoResolve (EmitContext ec)
4550                 {
4551                         if (instance_expr != null) {
4552                                 instance_expr = instance_expr.DoResolve (ec);
4553                                 if (instance_expr == null)
4554                                         return null;
4555                         }
4556
4557                         return this;
4558                 }
4559
4560                 public override void Emit (EmitContext ec)
4561                 {
4562                         Report.Error (70, loc, "The event '" + Name + "' can only appear on the left hand side of += or -= (except on the defining type)");
4563                 }
4564
4565                 public void EmitAddOrRemove (EmitContext ec, Expression source)
4566                 {
4567                         Expression handler = ((Binary) source).Right;
4568                         
4569                         Argument arg = new Argument (handler, Argument.AType.Expression);
4570                         ArrayList args = new ArrayList ();
4571                                 
4572                         args.Add (arg);
4573                         
4574                         if (((Binary) source).Oper == Binary.Operator.Addition)
4575                                 Invocation.EmitCall (
4576                                         ec, false, IsStatic, instance_expr, add_accessor, args, loc);
4577                         else
4578                                 Invocation.EmitCall (
4579                                         ec, false, IsStatic, instance_expr, remove_accessor, args, loc);
4580                 }
4581         }
4582 }