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