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