46a3c677a1a5e01ad9ecd576180fd6d508ca82b8
[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
2840                                 ig.Emit (OpCodes.Ldind_Ref);
2841                 }
2842
2843                 //
2844                 // The stack contains the pointer and the value of type `type'
2845                 //
2846                 public static void StoreFromPtr (ILGenerator ig, Type type)
2847                 {
2848                         if (TypeManager.IsEnumType (type))
2849                                 type = TypeManager.EnumToUnderlying (type);
2850                         if (type == TypeManager.int32_type || type == TypeManager.uint32_type)
2851                                 ig.Emit (OpCodes.Stind_I4);
2852                         else if (type == TypeManager.int64_type || type == TypeManager.uint64_type)
2853                                 ig.Emit (OpCodes.Stind_I8);
2854                         else if (type == TypeManager.char_type || type == TypeManager.short_type ||
2855                                  type == TypeManager.ushort_type)
2856                                 ig.Emit (OpCodes.Stind_I2);
2857                         else if (type == TypeManager.float_type)
2858                                 ig.Emit (OpCodes.Stind_R4);
2859                         else if (type == TypeManager.double_type)
2860                                 ig.Emit (OpCodes.Stind_R8);
2861                         else if (type == TypeManager.byte_type || type == TypeManager.sbyte_type ||
2862                                  type == TypeManager.bool_type)
2863                                 ig.Emit (OpCodes.Stind_I1);
2864                         else if (type == TypeManager.intptr_type)
2865                                 ig.Emit (OpCodes.Stind_I);
2866                         else if (type.IsValueType)
2867                                 ig.Emit (OpCodes.Stobj, type);
2868                         else
2869                                 ig.Emit (OpCodes.Stind_Ref);
2870                 }
2871                 
2872                 //
2873                 // Returns the size of type `t' if known, otherwise, 0
2874                 //
2875                 public static int GetTypeSize (Type t)
2876                 {
2877                         t = TypeManager.TypeToCoreType (t);
2878                         if (t == TypeManager.int32_type ||
2879                             t == TypeManager.uint32_type ||
2880                             t == TypeManager.float_type)
2881                                 return 4;
2882                         else if (t == TypeManager.int64_type ||
2883                                  t == TypeManager.uint64_type ||
2884                                  t == TypeManager.double_type)
2885                                 return 8;
2886                         else if (t == TypeManager.byte_type ||
2887                                  t == TypeManager.sbyte_type ||
2888                                  t == TypeManager.bool_type)    
2889                                 return 1;
2890                         else if (t == TypeManager.short_type ||
2891                                  t == TypeManager.char_type ||
2892                                  t == TypeManager.ushort_type)
2893                                 return 2;
2894                         else if (t == TypeManager.decimal_type)
2895                                 return 16;
2896                         else
2897                                 return 0;
2898                 }
2899
2900                 //
2901                 // Default implementation of IAssignMethod.CacheTemporaries
2902                 //
2903                 public void CacheTemporaries (EmitContext ec)
2904                 {
2905                 }
2906
2907                 static void Error_NegativeArrayIndex (Location loc)
2908                 {
2909                         Report.Error (284, loc, "Can not create array with a negative size");
2910                 }
2911                 
2912                 //
2913                 // Converts `source' to an int, uint, long or ulong.
2914                 //
2915                 public Expression ExpressionToArrayArgument (EmitContext ec, Expression source, Location loc)
2916                 {
2917                         Expression target;
2918                         
2919                         bool old_checked = ec.CheckState;
2920                         ec.CheckState = true;
2921                         
2922                         target = ConvertImplicit (ec, source, TypeManager.int32_type, loc);
2923                         if (target == null){
2924                                 target = ConvertImplicit (ec, source, TypeManager.uint32_type, loc);
2925                                 if (target == null){
2926                                         target = ConvertImplicit (ec, source, TypeManager.int64_type, loc);
2927                                         if (target == null){
2928                                                 target = ConvertImplicit (ec, source, TypeManager.uint64_type, loc);
2929                                                 if (target == null)
2930                                                         Expression.Error_CannotConvertImplicit (loc, source.Type, TypeManager.int32_type);
2931                                         }
2932                                 }
2933                         } 
2934                         ec.CheckState = old_checked;
2935
2936                         //
2937                         // Only positive constants are allowed at compile time
2938                         //
2939                         if (target is Constant){
2940                                 if (target is IntConstant){
2941                                         if (((IntConstant) target).Value < 0){
2942                                                 Error_NegativeArrayIndex (loc);
2943                                                 return null;
2944                                         }
2945                                 }
2946
2947                                 if (target is LongConstant){
2948                                         if (((LongConstant) target).Value < 0){
2949                                                 Error_NegativeArrayIndex (loc);
2950                                                 return null;
2951                                         }
2952                                 }
2953                                 
2954                         }
2955
2956                         return target;
2957                 }
2958                 
2959         }
2960
2961         /// <summary>
2962         ///   This is just a base class for expressions that can
2963         ///   appear on statements (invocations, object creation,
2964         ///   assignments, post/pre increment and decrement).  The idea
2965         ///   being that they would support an extra Emition interface that
2966         ///   does not leave a result on the stack.
2967         /// </summary>
2968         public abstract class ExpressionStatement : Expression {
2969
2970                 /// <summary>
2971                 ///   Requests the expression to be emitted in a `statement'
2972                 ///   context.  This means that no new value is left on the
2973                 ///   stack after invoking this method (constrasted with
2974                 ///   Emit that will always leave a value on the stack).
2975                 /// </summary>
2976                 public abstract void EmitStatement (EmitContext ec);
2977         }
2978
2979         /// <summary>
2980         ///   This kind of cast is used to encapsulate the child
2981         ///   whose type is child.Type into an expression that is
2982         ///   reported to return "return_type".  This is used to encapsulate
2983         ///   expressions which have compatible types, but need to be dealt
2984         ///   at higher levels with.
2985         ///
2986         ///   For example, a "byte" expression could be encapsulated in one
2987         ///   of these as an "unsigned int".  The type for the expression
2988         ///   would be "unsigned int".
2989         ///
2990         /// </summary>
2991         public class EmptyCast : Expression {
2992                 protected Expression child;
2993                 
2994                 public EmptyCast (Expression child, Type return_type)
2995                 {
2996                         eclass = child.eclass;
2997                         type = return_type;
2998                         this.child = child;
2999                 }
3000
3001                 public override Expression DoResolve (EmitContext ec)
3002                 {
3003                         // This should never be invoked, we are born in fully
3004                         // initialized state.
3005
3006                         return this;
3007                 }
3008
3009                 public override void Emit (EmitContext ec)
3010                 {
3011                         child.Emit (ec);
3012                 }
3013         }
3014
3015         /// <summary>
3016         ///  This class is used to wrap literals which belong inside Enums
3017         /// </summary>
3018         public class EnumConstant : Constant {
3019                 public Constant Child;
3020
3021                 public EnumConstant (Constant child, Type enum_type)
3022                 {
3023                         eclass = child.eclass;
3024                         this.Child = child;
3025                         type = enum_type;
3026                 }
3027                 
3028                 public override Expression DoResolve (EmitContext ec)
3029                 {
3030                         // This should never be invoked, we are born in fully
3031                         // initialized state.
3032
3033                         return this;
3034                 }
3035
3036                 public override void Emit (EmitContext ec)
3037                 {
3038                         Child.Emit (ec);
3039                 }
3040
3041                 public override object GetValue ()
3042                 {
3043                         return Child.GetValue ();
3044                 }
3045
3046                 //
3047                 // Converts from one of the valid underlying types for an enumeration
3048                 // (int32, uint32, int64, uint64, short, ushort, byte, sbyte) to
3049                 // one of the internal compiler literals: Int/UInt/Long/ULong Literals.
3050                 //
3051                 public Constant WidenToCompilerConstant ()
3052                 {
3053                         Type t = TypeManager.EnumToUnderlying (Child.Type);
3054                         object v = ((Constant) Child).GetValue ();;
3055                         
3056                         if (t == TypeManager.int32_type)
3057                                 return new IntConstant ((int) v);
3058                         if (t == TypeManager.uint32_type)
3059                                 return new UIntConstant ((uint) v);
3060                         if (t == TypeManager.int64_type)
3061                                 return new LongConstant ((long) v);
3062                         if (t == TypeManager.uint64_type)
3063                                 return new ULongConstant ((ulong) v);
3064                         if (t == TypeManager.short_type)
3065                                 return new ShortConstant ((short) v);
3066                         if (t == TypeManager.ushort_type)
3067                                 return new UShortConstant ((ushort) v);
3068                         if (t == TypeManager.byte_type)
3069                                 return new ByteConstant ((byte) v);
3070                         if (t == TypeManager.sbyte_type)
3071                                 return new SByteConstant ((sbyte) v);
3072
3073                         throw new Exception ("Invalid enumeration underlying type: " + t);
3074                 }
3075
3076                 //
3077                 // Extracts the value in the enumeration on its native representation
3078                 //
3079                 public object GetPlainValue ()
3080                 {
3081                         Type t = TypeManager.EnumToUnderlying (Child.Type);
3082                         object v = ((Constant) Child).GetValue ();;
3083                         
3084                         if (t == TypeManager.int32_type)
3085                                 return (int) v;
3086                         if (t == TypeManager.uint32_type)
3087                                 return (uint) v;
3088                         if (t == TypeManager.int64_type)
3089                                 return (long) v;
3090                         if (t == TypeManager.uint64_type)
3091                                 return (ulong) v;
3092                         if (t == TypeManager.short_type)
3093                                 return (short) v;
3094                         if (t == TypeManager.ushort_type)
3095                                 return (ushort) v;
3096                         if (t == TypeManager.byte_type)
3097                                 return (byte) v;
3098                         if (t == TypeManager.sbyte_type)
3099                                 return (sbyte) v;
3100
3101                         return null;
3102                 }
3103                 
3104                 public override string AsString ()
3105                 {
3106                         return Child.AsString ();
3107                 }
3108
3109                 public override DoubleConstant ConvertToDouble ()
3110                 {
3111                         return Child.ConvertToDouble ();
3112                 }
3113
3114                 public override FloatConstant ConvertToFloat ()
3115                 {
3116                         return Child.ConvertToFloat ();
3117                 }
3118
3119                 public override ULongConstant ConvertToULong ()
3120                 {
3121                         return Child.ConvertToULong ();
3122                 }
3123
3124                 public override LongConstant ConvertToLong ()
3125                 {
3126                         return Child.ConvertToLong ();
3127                 }
3128
3129                 public override UIntConstant ConvertToUInt ()
3130                 {
3131                         return Child.ConvertToUInt ();
3132                 }
3133
3134                 public override IntConstant ConvertToInt ()
3135                 {
3136                         return Child.ConvertToInt ();
3137                 }
3138         }
3139
3140         /// <summary>
3141         ///   This kind of cast is used to encapsulate Value Types in objects.
3142         ///
3143         ///   The effect of it is to box the value type emitted by the previous
3144         ///   operation.
3145         /// </summary>
3146         public class BoxedCast : EmptyCast {
3147
3148                 public BoxedCast (Expression expr)
3149                         : base (expr, TypeManager.object_type) 
3150                 {
3151                 }
3152                 
3153                 public override Expression DoResolve (EmitContext ec)
3154                 {
3155                         // This should never be invoked, we are born in fully
3156                         // initialized state.
3157
3158                         return this;
3159                 }
3160
3161                 public override void Emit (EmitContext ec)
3162                 {
3163                         base.Emit (ec);
3164                         
3165                         ec.ig.Emit (OpCodes.Box, child.Type);
3166                 }
3167         }
3168
3169         public class UnboxCast : EmptyCast {
3170                 public UnboxCast (Expression expr, Type return_type)
3171                         : base (expr, return_type)
3172                 {
3173                 }
3174
3175                 public override Expression DoResolve (EmitContext ec)
3176                 {
3177                         // This should never be invoked, we are born in fully
3178                         // initialized state.
3179
3180                         return this;
3181                 }
3182
3183                 public override void Emit (EmitContext ec)
3184                 {
3185                         Type t = type;
3186                         ILGenerator ig = ec.ig;
3187                         
3188                         base.Emit (ec);
3189                         ig.Emit (OpCodes.Unbox, t);
3190
3191                         LoadFromPtr (ig, t);
3192                 }
3193         }
3194         
3195         /// <summary>
3196         ///   This is used to perform explicit numeric conversions.
3197         ///
3198         ///   Explicit numeric conversions might trigger exceptions in a checked
3199         ///   context, so they should generate the conv.ovf opcodes instead of
3200         ///   conv opcodes.
3201         /// </summary>
3202         public class ConvCast : EmptyCast {
3203                 public enum Mode : byte {
3204                         I1_U1, I1_U2, I1_U4, I1_U8, I1_CH,
3205                         U1_I1, U1_CH,
3206                         I2_I1, I2_U1, I2_U2, I2_U4, I2_U8, I2_CH,
3207                         U2_I1, U2_U1, U2_I2, U2_CH,
3208                         I4_I1, I4_U1, I4_I2, I4_U2, I4_U4, I4_U8, I4_CH,
3209                         U4_I1, U4_U1, U4_I2, U4_U2, U4_I4, U4_CH,
3210                         I8_I1, I8_U1, I8_I2, I8_U2, I8_I4, I8_U4, I8_U8, I8_CH,
3211                         U8_I1, U8_U1, U8_I2, U8_U2, U8_I4, U8_U4, U8_I8, U8_CH,
3212                         CH_I1, CH_U1, CH_I2,
3213                         R4_I1, R4_U1, R4_I2, R4_U2, R4_I4, R4_U4, R4_I8, R4_U8, R4_CH,
3214                         R8_I1, R8_U1, R8_I2, R8_U2, R8_I4, R8_U4, R8_I8, R8_U8, R8_CH, R8_R4
3215                 }
3216
3217                 Mode mode;
3218                 bool checked_state;
3219                 
3220                 public ConvCast (EmitContext ec, Expression child, Type return_type, Mode m)
3221                         : base (child, return_type)
3222                 {
3223                         checked_state = ec.CheckState;
3224                         mode = m;
3225                 }
3226
3227                 public override Expression DoResolve (EmitContext ec)
3228                 {
3229                         // This should never be invoked, we are born in fully
3230                         // initialized state.
3231
3232                         return this;
3233                 }
3234
3235                 public override string ToString ()
3236                 {
3237                         return String.Format ("ConvCast ({0}, {1})", mode, child);
3238                 }
3239                 
3240                 public override void Emit (EmitContext ec)
3241                 {
3242                         ILGenerator ig = ec.ig;
3243                         
3244                         base.Emit (ec);
3245
3246                         if (checked_state){
3247                                 switch (mode){
3248                                 case Mode.I1_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
3249                                 case Mode.I1_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
3250                                 case Mode.I1_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
3251                                 case Mode.I1_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
3252                                 case Mode.I1_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
3253
3254                                 case Mode.U1_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
3255                                 case Mode.U1_CH: /* nothing */ break;
3256
3257                                 case Mode.I2_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
3258                                 case Mode.I2_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
3259                                 case Mode.I2_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
3260                                 case Mode.I2_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
3261                                 case Mode.I2_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
3262                                 case Mode.I2_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
3263
3264                                 case Mode.U2_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
3265                                 case Mode.U2_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
3266                                 case Mode.U2_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
3267                                 case Mode.U2_CH: /* nothing */ break;
3268
3269                                 case Mode.I4_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
3270                                 case Mode.I4_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
3271                                 case Mode.I4_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
3272                                 case Mode.I4_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
3273                                 case Mode.I4_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
3274                                 case Mode.I4_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
3275                                 case Mode.I4_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
3276
3277                                 case Mode.U4_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
3278                                 case Mode.U4_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
3279                                 case Mode.U4_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
3280                                 case Mode.U4_U2: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
3281                                 case Mode.U4_I4: ig.Emit (OpCodes.Conv_Ovf_I4_Un); break;
3282                                 case Mode.U4_CH: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
3283
3284                                 case Mode.I8_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
3285                                 case Mode.I8_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
3286                                 case Mode.I8_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
3287                                 case Mode.I8_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
3288                                 case Mode.I8_I4: ig.Emit (OpCodes.Conv_Ovf_I4); break;
3289                                 case Mode.I8_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
3290                                 case Mode.I8_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
3291                                 case Mode.I8_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
3292
3293                                 case Mode.U8_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
3294                                 case Mode.U8_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
3295                                 case Mode.U8_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
3296                                 case Mode.U8_U2: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
3297                                 case Mode.U8_I4: ig.Emit (OpCodes.Conv_Ovf_I4_Un); break;
3298                                 case Mode.U8_U4: ig.Emit (OpCodes.Conv_Ovf_U4_Un); break;
3299                                 case Mode.U8_I8: ig.Emit (OpCodes.Conv_Ovf_I8_Un); break;
3300                                 case Mode.U8_CH: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
3301
3302                                 case Mode.CH_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
3303                                 case Mode.CH_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
3304                                 case Mode.CH_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
3305
3306                                 case Mode.R4_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
3307                                 case Mode.R4_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
3308                                 case Mode.R4_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
3309                                 case Mode.R4_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
3310                                 case Mode.R4_I4: ig.Emit (OpCodes.Conv_Ovf_I4); break;
3311                                 case Mode.R4_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
3312                                 case Mode.R4_I8: ig.Emit (OpCodes.Conv_Ovf_I8); break;
3313                                 case Mode.R4_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
3314                                 case Mode.R4_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
3315
3316                                 case Mode.R8_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
3317                                 case Mode.R8_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
3318                                 case Mode.R8_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
3319                                 case Mode.R8_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
3320                                 case Mode.R8_I4: ig.Emit (OpCodes.Conv_Ovf_I4); break;
3321                                 case Mode.R8_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
3322                                 case Mode.R8_I8: ig.Emit (OpCodes.Conv_Ovf_I8); break;
3323                                 case Mode.R8_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
3324                                 case Mode.R8_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
3325                                 case Mode.R8_R4: ig.Emit (OpCodes.Conv_R4); break;
3326                                 }
3327                         } else {
3328                                 switch (mode){
3329                                 case Mode.I1_U1: ig.Emit (OpCodes.Conv_U1); break;
3330                                 case Mode.I1_U2: ig.Emit (OpCodes.Conv_U2); break;
3331                                 case Mode.I1_U4: ig.Emit (OpCodes.Conv_U4); break;
3332                                 case Mode.I1_U8: ig.Emit (OpCodes.Conv_I8); break;
3333                                 case Mode.I1_CH: ig.Emit (OpCodes.Conv_U2); break;
3334
3335                                 case Mode.U1_I1: ig.Emit (OpCodes.Conv_I1); break;
3336                                 case Mode.U1_CH: ig.Emit (OpCodes.Conv_U2); break;
3337
3338                                 case Mode.I2_I1: ig.Emit (OpCodes.Conv_I1); break;
3339                                 case Mode.I2_U1: ig.Emit (OpCodes.Conv_U1); break;
3340                                 case Mode.I2_U2: ig.Emit (OpCodes.Conv_U2); break;
3341                                 case Mode.I2_U4: ig.Emit (OpCodes.Conv_U4); break;
3342                                 case Mode.I2_U8: ig.Emit (OpCodes.Conv_I8); break;
3343                                 case Mode.I2_CH: ig.Emit (OpCodes.Conv_U2); break;
3344
3345                                 case Mode.U2_I1: ig.Emit (OpCodes.Conv_I1); break;
3346                                 case Mode.U2_U1: ig.Emit (OpCodes.Conv_U1); break;
3347                                 case Mode.U2_I2: ig.Emit (OpCodes.Conv_I2); break;
3348                                 case Mode.U2_CH: /* nothing */ break;
3349
3350                                 case Mode.I4_I1: ig.Emit (OpCodes.Conv_I1); break;
3351                                 case Mode.I4_U1: ig.Emit (OpCodes.Conv_U1); break;
3352                                 case Mode.I4_I2: ig.Emit (OpCodes.Conv_I2); break;
3353                                 case Mode.I4_U4: /* nothing */ break;
3354                                 case Mode.I4_U2: ig.Emit (OpCodes.Conv_U2); break;
3355                                 case Mode.I4_U8: ig.Emit (OpCodes.Conv_I8); break;
3356                                 case Mode.I4_CH: ig.Emit (OpCodes.Conv_U2); break;
3357
3358                                 case Mode.U4_I1: ig.Emit (OpCodes.Conv_I1); break;
3359                                 case Mode.U4_U1: ig.Emit (OpCodes.Conv_U1); break;
3360                                 case Mode.U4_I2: ig.Emit (OpCodes.Conv_I2); break;
3361                                 case Mode.U4_U2: ig.Emit (OpCodes.Conv_U2); break;
3362                                 case Mode.U4_I4: /* nothing */ break;
3363                                 case Mode.U4_CH: ig.Emit (OpCodes.Conv_U2); break;
3364
3365                                 case Mode.I8_I1: ig.Emit (OpCodes.Conv_I1); break;
3366                                 case Mode.I8_U1: ig.Emit (OpCodes.Conv_U1); break;
3367                                 case Mode.I8_I2: ig.Emit (OpCodes.Conv_I2); break;
3368                                 case Mode.I8_U2: ig.Emit (OpCodes.Conv_U2); break;
3369                                 case Mode.I8_I4: ig.Emit (OpCodes.Conv_I4); break;
3370                                 case Mode.I8_U4: ig.Emit (OpCodes.Conv_U4); break;
3371                                 case Mode.I8_U8: /* nothing */ break;
3372                                 case Mode.I8_CH: ig.Emit (OpCodes.Conv_U2); break;
3373
3374                                 case Mode.U8_I1: ig.Emit (OpCodes.Conv_I1); break;
3375                                 case Mode.U8_U1: ig.Emit (OpCodes.Conv_U1); break;
3376                                 case Mode.U8_I2: ig.Emit (OpCodes.Conv_I2); break;
3377                                 case Mode.U8_U2: ig.Emit (OpCodes.Conv_U2); break;
3378                                 case Mode.U8_I4: ig.Emit (OpCodes.Conv_I4); break;
3379                                 case Mode.U8_U4: ig.Emit (OpCodes.Conv_U4); break;
3380                                 case Mode.U8_I8: /* nothing */ break;
3381                                 case Mode.U8_CH: ig.Emit (OpCodes.Conv_U2); break;
3382
3383                                 case Mode.CH_I1: ig.Emit (OpCodes.Conv_I1); break;
3384                                 case Mode.CH_U1: ig.Emit (OpCodes.Conv_U1); break;
3385                                 case Mode.CH_I2: ig.Emit (OpCodes.Conv_I2); break;
3386
3387                                 case Mode.R4_I1: ig.Emit (OpCodes.Conv_I1); break;
3388                                 case Mode.R4_U1: ig.Emit (OpCodes.Conv_U1); break;
3389                                 case Mode.R4_I2: ig.Emit (OpCodes.Conv_I2); break;
3390                                 case Mode.R4_U2: ig.Emit (OpCodes.Conv_U2); break;
3391                                 case Mode.R4_I4: ig.Emit (OpCodes.Conv_I4); break;
3392                                 case Mode.R4_U4: ig.Emit (OpCodes.Conv_U4); break;
3393                                 case Mode.R4_I8: ig.Emit (OpCodes.Conv_I8); break;
3394                                 case Mode.R4_U8: ig.Emit (OpCodes.Conv_U8); break;
3395                                 case Mode.R4_CH: ig.Emit (OpCodes.Conv_U2); break;
3396
3397                                 case Mode.R8_I1: ig.Emit (OpCodes.Conv_I1); break;
3398                                 case Mode.R8_U1: ig.Emit (OpCodes.Conv_U1); break;
3399                                 case Mode.R8_I2: ig.Emit (OpCodes.Conv_I2); break;
3400                                 case Mode.R8_U2: ig.Emit (OpCodes.Conv_U2); break;
3401                                 case Mode.R8_I4: ig.Emit (OpCodes.Conv_I4); break;
3402                                 case Mode.R8_U4: ig.Emit (OpCodes.Conv_U4); break;
3403                                 case Mode.R8_I8: ig.Emit (OpCodes.Conv_I8); break;
3404                                 case Mode.R8_U8: ig.Emit (OpCodes.Conv_U8); break;
3405                                 case Mode.R8_CH: ig.Emit (OpCodes.Conv_U2); break;
3406                                 case Mode.R8_R4: ig.Emit (OpCodes.Conv_R4); break;
3407                                 }
3408                         }
3409                 }
3410         }
3411         
3412         public class OpcodeCast : EmptyCast {
3413                 OpCode op, op2;
3414                 bool second_valid;
3415                 
3416                 public OpcodeCast (Expression child, Type return_type, OpCode op)
3417                         : base (child, return_type)
3418                         
3419                 {
3420                         this.op = op;
3421                         second_valid = false;
3422                 }
3423
3424                 public OpcodeCast (Expression child, Type return_type, OpCode op, OpCode op2)
3425                         : base (child, return_type)
3426                         
3427                 {
3428                         this.op = op;
3429                         this.op2 = op2;
3430                         second_valid = true;
3431                 }
3432
3433                 public override Expression DoResolve (EmitContext ec)
3434                 {
3435                         // This should never be invoked, we are born in fully
3436                         // initialized state.
3437
3438                         return this;
3439                 }
3440
3441                 public override void Emit (EmitContext ec)
3442                 {
3443                         base.Emit (ec);
3444                         ec.ig.Emit (op);
3445
3446                         if (second_valid)
3447                                 ec.ig.Emit (op2);
3448                 }                       
3449         }
3450
3451         /// <summary>
3452         ///   This kind of cast is used to encapsulate a child and cast it
3453         ///   to the class requested
3454         /// </summary>
3455         public class ClassCast : EmptyCast {
3456                 public ClassCast (Expression child, Type return_type)
3457                         : base (child, return_type)
3458                         
3459                 {
3460                 }
3461
3462                 public override Expression DoResolve (EmitContext ec)
3463                 {
3464                         // This should never be invoked, we are born in fully
3465                         // initialized state.
3466
3467                         return this;
3468                 }
3469
3470                 public override void Emit (EmitContext ec)
3471                 {
3472                         base.Emit (ec);
3473
3474                         ec.ig.Emit (OpCodes.Castclass, type);
3475                 }                       
3476                 
3477         }
3478         
3479         /// <summary>
3480         ///   SimpleName expressions are initially formed of a single
3481         ///   word and it only happens at the beginning of the expression.
3482         /// </summary>
3483         ///
3484         /// <remarks>
3485         ///   The expression will try to be bound to a Field, a Method
3486         ///   group or a Property.  If those fail we pass the name to our
3487         ///   caller and the SimpleName is compounded to perform a type
3488         ///   lookup.  The idea behind this process is that we want to avoid
3489         ///   creating a namespace map from the assemblies, as that requires
3490         ///   the GetExportedTypes function to be called and a hashtable to
3491         ///   be constructed which reduces startup time.  If later we find
3492         ///   that this is slower, we should create a `NamespaceExpr' expression
3493         ///   that fully participates in the resolution process. 
3494         ///   
3495         ///   For example `System.Console.WriteLine' is decomposed into
3496         ///   MemberAccess (MemberAccess (SimpleName ("System"), "Console"), "WriteLine")
3497         ///   
3498         ///   The first SimpleName wont produce a match on its own, so it will
3499         ///   be turned into:
3500         ///   MemberAccess (SimpleName ("System.Console"), "WriteLine").
3501         ///   
3502         ///   System.Console will produce a TypeExpr match.
3503         ///   
3504         ///   The downside of this is that we might be hitting `LookupType' too many
3505         ///   times with this scheme.
3506         /// </remarks>
3507         public class SimpleName : Expression {
3508                 public readonly string Name;
3509
3510                 //
3511                 // If true, then we are a simple name, not composed with a ".
3512                 //
3513                 bool is_base;
3514
3515                 public SimpleName (string a, string b, Location l)
3516                 {
3517                         Name = String.Concat (a, ".", b);
3518                         loc = l;
3519                         is_base = false;
3520                 }
3521                 
3522                 public SimpleName (string name, Location l)
3523                 {
3524                         Name = name;
3525                         loc = l;
3526                         is_base = true;
3527                 }
3528
3529                 public static void Error_ObjectRefRequired (EmitContext ec, Location l, string name)
3530                 {
3531                         if (ec.IsFieldInitializer)
3532                                 Report.Error (
3533                                         236, l,
3534                                         "A field initializer cannot reference the non-static field, " +
3535                                         "method or property `"+name+"'");
3536                         else
3537                                 Report.Error (
3538                                         120, l,
3539                                         "An object reference is required " +
3540                                         "for the non-static field `"+name+"'");
3541                 }
3542                 
3543                 //
3544                 // Checks whether we are trying to access an instance
3545                 // property, method or field from a static body.
3546                 //
3547                 Expression MemberStaticCheck (EmitContext ec, Expression e)
3548                 {
3549                         if (e is IMemberExpr){
3550                                 IMemberExpr member = (IMemberExpr) e;
3551                                 
3552                                 if (!member.IsStatic){
3553                                         Error_ObjectRefRequired (ec, loc, Name);
3554                                         return null;
3555                                 }
3556                         }
3557
3558                         return e;
3559                 }
3560                 
3561                 public override Expression DoResolve (EmitContext ec)
3562                 {
3563                         return SimpleNameResolve (ec, null, false);
3564                 }
3565
3566                 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
3567                 {
3568                         return SimpleNameResolve (ec, right_side, false);
3569                 }
3570                 
3571
3572                 public Expression DoResolveAllowStatic (EmitContext ec)
3573                 {
3574                         return SimpleNameResolve (ec, null, true);
3575                 }
3576
3577                 public override Expression ResolveAsTypeStep (EmitContext ec)
3578                 {
3579                         DeclSpace ds = ec.DeclSpace;
3580                         Namespace ns = ds.Namespace;
3581                         Type t;
3582                         string alias_value;
3583
3584                         //
3585                         // Since we are cheating: we only do the Alias lookup for
3586                         // namespaces if the name does not include any dots in it
3587                         //
3588                         if (ns != null && is_base)
3589                                 alias_value = ns.LookupAlias (Name);
3590                         else
3591                                 alias_value = null;
3592                                 
3593                         if (ec.ResolvingTypeTree){
3594                                 if (alias_value != null){
3595                                         if ((t = RootContext.LookupType (ds, alias_value, true, loc)) != null)
3596                                                 return new TypeExpr (t, loc);
3597                                 }
3598                                 
3599                                 int errors = Report.Errors;
3600                                 Type dt = ec.DeclSpace.FindType (loc, Name);
3601                                 if (Report.Errors != errors)
3602                                         return null;
3603                                 
3604                                 if (dt != null)
3605                                         return new TypeExpr (dt, loc);
3606                         }
3607
3608                         //
3609                         // First, the using aliases
3610                         //
3611                         if (alias_value != null){
3612                                 if ((t = RootContext.LookupType (ds, alias_value, true, loc)) != null)
3613                                         return new TypeExpr (t, loc);
3614                                 
3615                                 // we have alias value, but it isn't Type, so try if it's namespace
3616                                 return new SimpleName (alias_value, loc);
3617                         }
3618                         
3619                         //
3620                         // Stage 2: Lookup up if we are an alias to a type
3621                         // or a namespace.
3622                         //
3623                                 
3624                         if ((t = RootContext.LookupType (ds, Name, true, loc)) != null)
3625                                 return new TypeExpr (t, loc);
3626                                 
3627                         // No match, maybe our parent can compose us
3628                         // into something meaningful.
3629                         return this;
3630                 }
3631
3632                 /// <remarks>
3633                 ///   7.5.2: Simple Names. 
3634                 ///
3635                 ///   Local Variables and Parameters are handled at
3636                 ///   parse time, so they never occur as SimpleNames.
3637                 ///
3638                 ///   The `allow_static' flag is used by MemberAccess only
3639                 ///   and it is used to inform us that it is ok for us to 
3640                 ///   avoid the static check, because MemberAccess might end
3641                 ///   up resolving the Name as a Type name and the access as
3642                 ///   a static type access.
3643                 ///
3644                 ///   ie: Type Type; .... { Type.GetType (""); }
3645                 ///
3646                 ///   Type is both an instance variable and a Type;  Type.GetType
3647                 ///   is the static method not an instance method of type.
3648                 /// </remarks>
3649                 Expression SimpleNameResolve (EmitContext ec, Expression right_side, bool allow_static)
3650                 {
3651                         Expression e = null;
3652
3653                         //
3654                         // Stage 1: Performed by the parser (binding to locals or parameters).
3655                         //
3656                         Block current_block = ec.CurrentBlock;
3657                         if (current_block != null && current_block.GetVariableInfo (Name) != null){
3658                                 LocalVariableReference var;
3659
3660                                 var = new LocalVariableReference (ec.CurrentBlock, Name, loc);
3661
3662                                 if (right_side != null)
3663                                         return var.ResolveLValue (ec, right_side);
3664                                 else
3665                                         return var.Resolve (ec);
3666                         }
3667
3668                         if (current_block != null){
3669                                 int idx = -1;
3670                                 Parameter par = null;
3671                                 Parameters pars = current_block.Parameters;
3672                                 if (pars != null)
3673                                         par = pars.GetParameterByName (Name, out idx);
3674
3675                                 if (par != null) {
3676                                         ParameterReference param;
3677                                         
3678                                         param = new ParameterReference (pars, idx, Name, loc);
3679
3680                                         if (right_side != null)
3681                                                 return param.ResolveLValue (ec, right_side);
3682                                         else
3683                                                 return param.Resolve (ec);
3684                                 }
3685                         }
3686
3687                         //
3688                         // Stage 2: Lookup members 
3689                         //
3690
3691                         DeclSpace lookup_ds = ec.DeclSpace;
3692                         do {
3693                                 if (lookup_ds.TypeBuilder == null)
3694                                         break;
3695
3696                                 e = MemberLookup (ec, lookup_ds.TypeBuilder, Name, loc);
3697                                 if (e != null)
3698                                         break;
3699
3700                                 lookup_ds =lookup_ds.Parent;
3701                         } while (lookup_ds != null);
3702                                 
3703                         if (e == null && ec.ContainerType != null)
3704                                 e = MemberLookup (ec, ec.ContainerType, Name, loc);
3705
3706                         if (e == null)
3707                                 return ResolveAsTypeStep (ec);
3708
3709                         if (e is TypeExpr)
3710                                 return e;
3711
3712                         if (e is IMemberExpr) {
3713                                 e = MemberAccess.ResolveMemberAccess (ec, e, null, loc, this);
3714                                 if (e == null)
3715                                         return null;
3716
3717                                 IMemberExpr me = e as IMemberExpr;
3718                                 if (me == null)
3719                                         return e;
3720
3721                                 // This fails if ResolveMemberAccess() was unable to decide whether
3722                                 // it's a field or a type of the same name.
3723                                 if (!me.IsStatic && (me.InstanceExpression == null))
3724                                         return e;
3725
3726                                 if (!me.IsStatic &&
3727                                     TypeManager.IsNestedChildOf (me.InstanceExpression.Type, me.DeclaringType) &&
3728                                     !me.InstanceExpression.Type.IsSubclassOf (me.DeclaringType)) {
3729                                         Error (38, "Cannot access nonstatic member `" + me.Name + "' of " +
3730                                                "outer type `" + me.DeclaringType + "' via nested type `" +
3731                                                me.InstanceExpression.Type + "'");
3732                                         return null;
3733                                 }
3734
3735                                 if (right_side != null)
3736                                         e = e.DoResolveLValue (ec, right_side);
3737                                 else
3738                                         e = e.DoResolve (ec);
3739
3740                                 return e;                               
3741                         }
3742
3743                         if (ec.IsStatic || ec.IsFieldInitializer){
3744                                 if (allow_static)
3745                                         return e;
3746
3747                                 return MemberStaticCheck (ec, e);
3748                         } else
3749                                 return e;
3750                 }
3751                 
3752                 public override void Emit (EmitContext ec)
3753                 {
3754                         //
3755                         // If this is ever reached, then we failed to
3756                         // find the name as a namespace
3757                         //
3758
3759                         Error (103, "The name `" + Name +
3760                                "' does not exist in the class `" +
3761                                ec.DeclSpace.Name + "'");
3762                 }
3763
3764                 public override string ToString ()
3765                 {
3766                         return Name;
3767                 }
3768         }
3769         
3770         /// <summary>
3771         ///   Fully resolved expression that evaluates to a type
3772         /// </summary>
3773         public class TypeExpr : Expression {
3774                 public TypeExpr (Type t, Location l)
3775                 {
3776                         Type = t;
3777                         eclass = ExprClass.Type;
3778                         loc = l;
3779                 }
3780
3781                 public override Expression ResolveAsTypeStep (EmitContext ec)
3782                 {
3783                         return this;
3784                 }
3785
3786                 override public Expression DoResolve (EmitContext ec)
3787                 {
3788                         return this;
3789                 }
3790
3791                 override public void Emit (EmitContext ec)
3792                 {
3793                         throw new Exception ("Should never be called");
3794                 }
3795
3796                 public override string ToString ()
3797                 {
3798                         return Type.ToString ();
3799                 }
3800         }
3801
3802         /// <summary>
3803         ///   Used to create types from a fully qualified name.  These are just used
3804         ///   by the parser to setup the core types.  A TypeLookupExpression is always
3805         ///   classified as a type.
3806         /// </summary>
3807         public class TypeLookupExpression : TypeExpr {
3808                 string name;
3809                 
3810                 public TypeLookupExpression (string name) : base (null, Location.Null)
3811                 {
3812                         this.name = name;
3813                 }
3814
3815                 public override Expression ResolveAsTypeStep (EmitContext ec)
3816                 {
3817                         if (type == null)
3818                                 type = RootContext.LookupType (ec.DeclSpace, name, false, Location.Null);
3819                         return this;
3820                 }
3821
3822                 public override Expression DoResolve (EmitContext ec)
3823                 {
3824                         return ResolveAsTypeStep (ec);
3825                 }
3826
3827                 public override void Emit (EmitContext ec)
3828                 {
3829                         throw new Exception ("Should never be called");
3830                 }
3831
3832                 public override string ToString ()
3833                 {
3834                         return name;
3835                 }
3836         }
3837
3838         /// <summary>
3839         ///   MethodGroup Expression.
3840         ///  
3841         ///   This is a fully resolved expression that evaluates to a type
3842         /// </summary>
3843         public class MethodGroupExpr : Expression, IMemberExpr {
3844                 public MethodBase [] Methods;
3845                 Expression instance_expression = null;
3846                 bool is_explicit_impl = false;
3847                 
3848                 public MethodGroupExpr (MemberInfo [] mi, Location l)
3849                 {
3850                         Methods = new MethodBase [mi.Length];
3851                         mi.CopyTo (Methods, 0);
3852                         eclass = ExprClass.MethodGroup;
3853                         type = TypeManager.object_type;
3854                         loc = l;
3855                 }
3856
3857                 public MethodGroupExpr (ArrayList list, Location l)
3858                 {
3859                         Methods = new MethodBase [list.Count];
3860
3861                         try {
3862                                 list.CopyTo (Methods, 0);
3863                         } catch {
3864                                 foreach (MemberInfo m in list){
3865                                         if (!(m is MethodBase)){
3866                                                 Console.WriteLine ("Name " + m.Name);
3867                                                 Console.WriteLine ("Found a: " + m.GetType ().FullName);
3868                                         }
3869                                 }
3870                                 throw;
3871                         }
3872                         loc = l;
3873                         eclass = ExprClass.MethodGroup;
3874                         type = TypeManager.object_type;
3875                 }
3876
3877                 public Type DeclaringType {
3878                         get {
3879                                 return Methods [0].DeclaringType;
3880                         }
3881                 }
3882                 
3883                 //
3884                 // `A method group may have associated an instance expression' 
3885                 // 
3886                 public Expression InstanceExpression {
3887                         get {
3888                                 return instance_expression;
3889                         }
3890
3891                         set {
3892                                 instance_expression = value;
3893                         }
3894                 }
3895
3896                 public bool IsExplicitImpl {
3897                         get {
3898                                 return is_explicit_impl;
3899                         }
3900
3901                         set {
3902                                 is_explicit_impl = value;
3903                         }
3904                 }
3905
3906                 public string Name {
3907                         get {
3908                                 return Methods [0].Name;
3909                         }
3910                 }
3911
3912                 public bool IsInstance {
3913                         get {
3914                                 foreach (MethodBase mb in Methods)
3915                                         if (!mb.IsStatic)
3916                                                 return true;
3917
3918                                 return false;
3919                         }
3920                 }
3921
3922                 public bool IsStatic {
3923                         get {
3924                                 foreach (MethodBase mb in Methods)
3925                                         if (mb.IsStatic)
3926                                                 return true;
3927
3928                                 return false;
3929                         }
3930                 }
3931                 
3932                 override public Expression DoResolve (EmitContext ec)
3933                 {
3934                         if (instance_expression != null) {
3935                                 instance_expression = instance_expression.DoResolve (ec);
3936                                 if (instance_expression == null)
3937                                         return null;
3938                         }
3939
3940                         return this;
3941                 }
3942
3943                 public void ReportUsageError ()
3944                 {
3945                         Report.Error (654, loc, "Method `" + Methods [0].DeclaringType + "." +
3946                                       Methods [0].Name + "()' is referenced without parentheses");
3947                 }
3948
3949                 override public void Emit (EmitContext ec)
3950                 {
3951                         ReportUsageError ();
3952                 }
3953
3954                 bool RemoveMethods (bool keep_static)
3955                 {
3956                         ArrayList smethods = new ArrayList ();
3957
3958                         foreach (MethodBase mb in Methods){
3959                                 if (mb.IsStatic == keep_static)
3960                                         smethods.Add (mb);
3961                         }
3962
3963                         if (smethods.Count == 0)
3964                                 return false;
3965
3966                         Methods = new MethodBase [smethods.Count];
3967                         smethods.CopyTo (Methods, 0);
3968
3969                         return true;
3970                 }
3971                 
3972                 /// <summary>
3973                 ///   Removes any instance methods from the MethodGroup, returns
3974                 ///   false if the resulting set is empty.
3975                 /// </summary>
3976                 public bool RemoveInstanceMethods ()
3977                 {
3978                         return RemoveMethods (true);
3979                 }
3980
3981                 /// <summary>
3982                 ///   Removes any static methods from the MethodGroup, returns
3983                 ///   false if the resulting set is empty.
3984                 /// </summary>
3985                 public bool RemoveStaticMethods ()
3986                 {
3987                         return RemoveMethods (false);
3988                 }
3989         }
3990
3991         /// <summary>
3992         ///   Fully resolved expression that evaluates to a Field
3993         /// </summary>
3994         public class FieldExpr : Expression, IAssignMethod, IMemoryLocation, IMemberExpr {
3995                 public readonly FieldInfo FieldInfo;
3996                 Expression instance_expr;
3997                 
3998                 public FieldExpr (FieldInfo fi, Location l)
3999                 {
4000                         FieldInfo = fi;
4001                         eclass = ExprClass.Variable;
4002                         type = fi.FieldType;
4003                         loc = l;
4004                 }
4005
4006                 public string Name {
4007                         get {
4008                                 return FieldInfo.Name;
4009                         }
4010                 }
4011
4012                 public bool IsInstance {
4013                         get {
4014                                 return !FieldInfo.IsStatic;
4015                         }
4016                 }
4017
4018                 public bool IsStatic {
4019                         get {
4020                                 return FieldInfo.IsStatic;
4021                         }
4022                 }
4023
4024                 public Type DeclaringType {
4025                         get {
4026                                 return FieldInfo.DeclaringType;
4027                         }
4028                 }
4029
4030                 public Expression InstanceExpression {
4031                         get {
4032                                 return instance_expr;
4033                         }
4034
4035                         set {
4036                                 instance_expr = value;
4037                         }
4038                 }
4039
4040                 override public Expression DoResolve (EmitContext ec)
4041                 {
4042                         if (!FieldInfo.IsStatic){
4043                                 if (instance_expr == null){
4044                                         //
4045                                         // This can happen when referencing an instance field using
4046                                         // a fully qualified type expression: TypeName.InstanceField = xxx
4047                                         // 
4048                                         SimpleName.Error_ObjectRefRequired (ec, loc, FieldInfo.Name);
4049                                         return null;
4050                                 }
4051
4052                                 // Resolve the field's instance expression while flow analysis is turned
4053                                 // off: when accessing a field "a.b", we must check whether the field
4054                                 // "a.b" is initialized, not whether the whole struct "a" is initialized.
4055                                 instance_expr = instance_expr.Resolve (ec, ResolveFlags.VariableOrValue |
4056                                                                        ResolveFlags.DisableFlowAnalysis);
4057                                 if (instance_expr == null)
4058                                         return null;
4059                         }
4060
4061                         // If the instance expression is a local variable or parameter.
4062                         IVariable var = instance_expr as IVariable;
4063                         if ((var != null) && !var.IsFieldAssigned (ec, FieldInfo.Name, loc))
4064                                 return null;
4065
4066                         return this;
4067                 }
4068
4069                 void Report_AssignToReadonly (bool is_instance)
4070                 {
4071                         string msg;
4072                         
4073                         if (is_instance)
4074                                 msg = "Readonly field can not be assigned outside " +
4075                                 "of constructor or variable initializer";
4076                         else
4077                                 msg = "A static readonly field can only be assigned in " +
4078                                 "a static constructor";
4079
4080                         Report.Error (is_instance ? 191 : 198, loc, msg);
4081                 }
4082                 
4083                 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
4084                 {
4085                         IVariable var = instance_expr as IVariable;
4086                         if (var != null)
4087                                 var.SetFieldAssigned (ec, FieldInfo.Name);
4088
4089                         Expression e = DoResolve (ec);
4090
4091                         if (e == null)
4092                                 return null;
4093                         
4094                         if (!FieldInfo.IsInitOnly)
4095                                 return this;
4096
4097                         //
4098                         // InitOnly fields can only be assigned in constructors
4099                         //
4100
4101                         if (ec.IsConstructor){
4102                                 if (ec.ContainerType == FieldInfo.DeclaringType)
4103                                         return this;
4104                         }
4105
4106                         Report_AssignToReadonly (true);
4107                         
4108                         return null;
4109                 }
4110
4111                 override public void Emit (EmitContext ec)
4112                 {
4113                         ILGenerator ig = ec.ig;
4114                         bool is_volatile = false;
4115
4116                         if (FieldInfo is FieldBuilder){
4117                                 FieldBase f = TypeManager.GetField (FieldInfo);
4118
4119                                 if ((f.ModFlags & Modifiers.VOLATILE) != 0)
4120                                         is_volatile = true;
4121                                 
4122                                 f.status |= Field.Status.USED;
4123                         }
4124                         
4125                         if (FieldInfo.IsStatic){
4126                                 if (is_volatile)
4127                                         ig.Emit (OpCodes.Volatile);
4128                                 
4129                                 ig.Emit (OpCodes.Ldsfld, FieldInfo);
4130                         } else {
4131                                 if (instance_expr.Type.IsValueType){
4132                                         IMemoryLocation ml;
4133                                         LocalTemporary tempo = null;
4134
4135                                         if (!(instance_expr is IMemoryLocation)){
4136                                                 tempo = new LocalTemporary (
4137                                                         ec, instance_expr.Type);
4138
4139                                                 InstanceExpression.Emit (ec);
4140                                                 tempo.Store (ec);
4141                                                 ml = tempo;
4142                                         } else
4143                                                 ml = (IMemoryLocation) instance_expr;
4144
4145                                         ml.AddressOf (ec, AddressOp.Load);
4146                                 } else 
4147                                         instance_expr.Emit (ec);
4148
4149                                 if (is_volatile)
4150                                         ig.Emit (OpCodes.Volatile);
4151                                 
4152                                 ig.Emit (OpCodes.Ldfld, FieldInfo);
4153                         }
4154                 }
4155
4156                 public void EmitAssign (EmitContext ec, Expression source)
4157                 {
4158                         FieldAttributes fa = FieldInfo.Attributes;
4159                         bool is_static = (fa & FieldAttributes.Static) != 0;
4160                         bool is_readonly = (fa & FieldAttributes.InitOnly) != 0;
4161                         ILGenerator ig = ec.ig;
4162
4163                         if (is_readonly && !ec.IsConstructor){
4164                                 Report_AssignToReadonly (!is_static);
4165                                 return;
4166                         }
4167                         
4168                         if (!is_static){
4169                                 Expression instance = instance_expr;
4170
4171                                 if (instance.Type.IsValueType){
4172                                         if (instance is IMemoryLocation){
4173                                                 IMemoryLocation ml = (IMemoryLocation) instance;
4174
4175                                                 ml.AddressOf (ec, AddressOp.Store);
4176                                         } else
4177                                                 throw new Exception ("The " + instance + " of type " +
4178                                                                      instance.Type +
4179                                                                      " represents a ValueType and does " +
4180                                                                      "not implement IMemoryLocation");
4181                                 } else
4182                                         instance.Emit (ec);
4183                         }
4184                         source.Emit (ec);
4185
4186                         if (FieldInfo is FieldBuilder){
4187                                 FieldBase f = TypeManager.GetField (FieldInfo);
4188                                 
4189                                 if ((f.ModFlags & Modifiers.VOLATILE) != 0)
4190                                         ig.Emit (OpCodes.Volatile);
4191                         }
4192                         
4193                         if (is_static)
4194                                 ig.Emit (OpCodes.Stsfld, FieldInfo);
4195                         else 
4196                                 ig.Emit (OpCodes.Stfld, FieldInfo);
4197
4198                         if (FieldInfo is FieldBuilder){
4199                                 FieldBase f = TypeManager.GetField (FieldInfo);
4200
4201                                 f.status |= Field.Status.ASSIGNED;
4202                         }
4203                 }
4204                 
4205                 public void AddressOf (EmitContext ec, AddressOp mode)
4206                 {
4207                         ILGenerator ig = ec.ig;
4208                         
4209                         if (FieldInfo is FieldBuilder){
4210                                 FieldBase f = TypeManager.GetField (FieldInfo);
4211                                 if ((f.ModFlags & Modifiers.VOLATILE) != 0)
4212                                         ig.Emit (OpCodes.Volatile);
4213                         }
4214
4215                         if (FieldInfo is FieldBuilder){
4216                                 FieldBase f = TypeManager.GetField (FieldInfo);
4217
4218                                 if ((mode & AddressOp.Store) != 0)
4219                                         f.status |= Field.Status.ASSIGNED;
4220                                 if ((mode & AddressOp.Load) != 0)
4221                                         f.status |= Field.Status.USED;
4222                         }
4223
4224                         //
4225                         // Handle initonly fields specially: make a copy and then
4226                         // get the address of the copy.
4227                         //
4228                         if (FieldInfo.IsInitOnly && !ec.IsConstructor){
4229                                 LocalBuilder local;
4230                                 
4231                                 Emit (ec);
4232                                 local = ig.DeclareLocal (type);
4233                                 ig.Emit (OpCodes.Stloc, local);
4234                                 ig.Emit (OpCodes.Ldloca, local);
4235                                 return;
4236                         }
4237
4238                         if (FieldInfo.IsStatic)
4239                                 ig.Emit (OpCodes.Ldsflda, FieldInfo);
4240                         else {
4241                                 //
4242                                 // In the case of `This', we call the AddressOf method, which will
4243                                 // only load the pointer, and not perform an Ldobj immediately after
4244                                 // the value has been loaded into the stack.
4245                                 //
4246                                 if (instance_expr is This)
4247                                         ((This)instance_expr).AddressOf (ec, AddressOp.LoadStore);
4248                                 else if (instance_expr.Type.IsValueType && instance_expr is IMemoryLocation){
4249                                         IMemoryLocation ml = (IMemoryLocation) instance_expr;
4250
4251                                         ml.AddressOf (ec, AddressOp.LoadStore);
4252                                 } else
4253                                         instance_expr.Emit (ec);
4254                                 ig.Emit (OpCodes.Ldflda, FieldInfo);
4255                         }
4256                 }
4257         }
4258         
4259         /// <summary>
4260         ///   Expression that evaluates to a Property.  The Assign class
4261         ///   might set the `Value' expression if we are in an assignment.
4262         ///
4263         ///   This is not an LValue because we need to re-write the expression, we
4264         ///   can not take data from the stack and store it.  
4265         /// </summary>
4266         public class PropertyExpr : ExpressionStatement, IAssignMethod, IMemberExpr {
4267                 public readonly PropertyInfo PropertyInfo;
4268
4269                 //
4270                 // This is set externally by the  `BaseAccess' class
4271                 //
4272                 public bool IsBase;
4273                 MethodInfo getter, setter;
4274                 bool is_static;
4275                 bool must_do_cs1540_check;
4276                 
4277                 Expression instance_expr;
4278
4279                 public PropertyExpr (EmitContext ec, PropertyInfo pi, Location l)
4280                 {
4281                         PropertyInfo = pi;
4282                         eclass = ExprClass.PropertyAccess;
4283                         is_static = false;
4284                         loc = l;
4285
4286                         type = TypeManager.TypeToCoreType (pi.PropertyType);
4287
4288                         ResolveAccessors (ec);
4289                 }
4290
4291                 public string Name {
4292                         get {
4293                                 return PropertyInfo.Name;
4294                         }
4295                 }
4296
4297                 public bool IsInstance {
4298                         get {
4299                                 return !is_static;
4300                         }
4301                 }
4302
4303                 public bool IsStatic {
4304                         get {
4305                                 return is_static;
4306                         }
4307                 }
4308                 
4309                 public Type DeclaringType {
4310                         get {
4311                                 return PropertyInfo.DeclaringType;
4312                         }
4313                 }
4314
4315                 //
4316                 // The instance expression associated with this expression
4317                 //
4318                 public Expression InstanceExpression {
4319                         set {
4320                                 instance_expr = value;
4321                         }
4322
4323                         get {
4324                                 return instance_expr;
4325                         }
4326                 }
4327
4328                 public bool VerifyAssignable ()
4329                 {
4330                         if (setter == null) {
4331                                 Report.Error (200, loc, 
4332                                               "The property `" + PropertyInfo.Name +
4333                                               "' can not be assigned to, as it has not set accessor");
4334                                 return false;
4335                         }
4336
4337                         return true;
4338                 }
4339
4340                 MethodInfo GetAccessor (Type invocation_type, string accessor_name)
4341                 {
4342                         BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic |
4343                                 BindingFlags.Static | BindingFlags.Instance;
4344                         MemberInfo[] group;
4345
4346                         group = TypeManager.MemberLookup (
4347                                 invocation_type, invocation_type, PropertyInfo.DeclaringType,
4348                                 MemberTypes.Method, flags, accessor_name + "_" + PropertyInfo.Name);
4349
4350                         //
4351                         // The first method is the closest to us
4352                         //
4353                         if (group == null)
4354                                 return null;
4355
4356                         foreach (MethodInfo mi in group) {
4357                                 MethodAttributes ma = mi.Attributes & MethodAttributes.MemberAccessMask;
4358
4359                                 //
4360                                 // If only accessible to the current class or children
4361                                 //
4362                                 if (ma == MethodAttributes.Private) {
4363                                         Type declaring_type = mi.DeclaringType;
4364                                         
4365                                         if (invocation_type != declaring_type){
4366                                                 if (TypeManager.IsSubclassOrNestedChildOf (invocation_type, mi.DeclaringType))
4367                                                         return mi;
4368                                                 else
4369                                                         continue;
4370                                         } else
4371                                                 return mi;
4372                                 }
4373                                 //
4374                                 // FamAndAssem requires that we not only derivate, but we are on the
4375                                 // same assembly.  
4376                                 //
4377                                 if (ma == MethodAttributes.FamANDAssem){
4378                                         if (mi.DeclaringType.Assembly != invocation_type.Assembly)
4379                                                 continue;
4380                                         else
4381                                                 return mi;
4382                                 }
4383
4384                                 // Assembly and FamORAssem succeed if we're in the same assembly.
4385                                 if ((ma == MethodAttributes.Assembly) || (ma == MethodAttributes.FamORAssem)){
4386                                         if (mi.DeclaringType.Assembly != invocation_type.Assembly)
4387                                                 continue;
4388                                         else
4389                                                 return mi;
4390                                 }
4391
4392                                 // We already know that we aren't in the same assembly.
4393                                 if (ma == MethodAttributes.Assembly)
4394                                         continue;
4395
4396                                 // Family and FamANDAssem require that we derive.
4397                                 if ((ma == MethodAttributes.Family) || (ma == MethodAttributes.FamANDAssem)){
4398                                         if (!TypeManager.IsSubclassOrNestedChildOf (invocation_type, mi.DeclaringType))
4399                                                 continue;
4400                                         else {
4401                                                 must_do_cs1540_check = true;
4402
4403                                                 return mi;
4404                                         }
4405                                 }
4406
4407                                 return mi;
4408                         }
4409
4410                         return null;
4411                 }
4412
4413                 //
4414                 // We also perform the permission checking here, as the PropertyInfo does not
4415                 // hold the information for the accessibility of its setter/getter
4416                 //
4417                 void ResolveAccessors (EmitContext ec)
4418                 {
4419                         getter = GetAccessor (ec.ContainerType, "get");
4420                         if ((getter != null) && getter.IsStatic)
4421                                 is_static = true;
4422
4423                         setter = GetAccessor (ec.ContainerType, "set");
4424                         if ((setter != null) && setter.IsStatic)
4425                                 is_static = true;
4426
4427                         if (setter == null && getter == null){
4428                                 Error (122, "`" + PropertyInfo.Name + "' " +
4429                                        "is inaccessible because of its protection level");
4430                                 
4431                         }
4432                 }
4433
4434                 bool InstanceResolve (EmitContext ec)
4435                 {
4436                         if ((instance_expr == null) && ec.IsStatic && !is_static) {
4437                                 SimpleName.Error_ObjectRefRequired (ec, loc, PropertyInfo.Name);
4438                                 return false;
4439                         }
4440
4441                         if (instance_expr != null) {
4442                                 instance_expr = instance_expr.DoResolve (ec);
4443                                 if (instance_expr == null)
4444                                         return false;
4445                         }
4446
4447                         if (must_do_cs1540_check && (instance_expr != null)) {
4448                                 if ((instance_expr.Type != ec.ContainerType) &&
4449                                     ec.ContainerType.IsSubclassOf (instance_expr.Type)) {
4450                                         Report.Error (1540, loc, "Cannot access protected member `" +
4451                                                       PropertyInfo.DeclaringType + "." + PropertyInfo.Name + 
4452                                                       "' via a qualifier of type `" +
4453                                                       TypeManager.CSharpName (instance_expr.Type) +
4454                                                       "'; the qualifier must be of type `" +
4455                                                       TypeManager.CSharpName (ec.ContainerType) +
4456                                                       "' (or derived from it)");
4457                                         return false;
4458                                 }
4459                         }
4460
4461                         return true;
4462                 }
4463                 
4464                 override public Expression DoResolve (EmitContext ec)
4465                 {
4466                         if (getter == null){
4467                                 //
4468                                 // The following condition happens if the PropertyExpr was
4469                                 // created, but is invalid (ie, the property is inaccessible),
4470                                 // and we did not want to embed the knowledge about this in
4471                                 // the caller routine.  This only avoids double error reporting.
4472                                 //
4473                                 if (setter == null)
4474                                         return null;
4475                                 
4476                                 Report.Error (154, loc, 
4477                                               "The property `" + PropertyInfo.Name +
4478                                               "' can not be used in " +
4479                                               "this context because it lacks a get accessor");
4480                                 return null;
4481                         } 
4482
4483                         if (!InstanceResolve (ec))
4484                                 return null;
4485
4486                         //
4487                         // Only base will allow this invocation to happen.
4488                         //
4489                         if (IsBase && getter.IsAbstract){
4490                                 Report.Error (205, loc, "Cannot call an abstract base property: " +
4491                                               PropertyInfo.DeclaringType + "." +PropertyInfo.Name);
4492                                 return null;
4493                         }
4494
4495                         return this;
4496                 }
4497
4498                 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
4499                 {
4500                         if (setter == null){
4501                                 //
4502                                 // The following condition happens if the PropertyExpr was
4503                                 // created, but is invalid (ie, the property is inaccessible),
4504                                 // and we did not want to embed the knowledge about this in
4505                                 // the caller routine.  This only avoids double error reporting.
4506                                 //
4507                                 if (getter == null)
4508                                         return null;
4509                                 
4510                                 Report.Error (154, loc, 
4511                                               "The property `" + PropertyInfo.Name +
4512                                               "' can not be used in " +
4513                                               "this context because it lacks a set accessor");
4514                                 return null;
4515                         }
4516
4517                         if (!InstanceResolve (ec))
4518                                 return null;
4519                         
4520                         //
4521                         // Only base will allow this invocation to happen.
4522                         //
4523                         if (IsBase && setter.IsAbstract){
4524                                 Report.Error (205, loc, "Cannot call an abstract base property: " +
4525                                               PropertyInfo.DeclaringType + "." +PropertyInfo.Name);
4526                                 return null;
4527                         }
4528                         return this;
4529                 }
4530
4531                 override public void Emit (EmitContext ec)
4532                 {
4533                         //
4534                         // Special case: length of single dimension array property is turned into ldlen
4535                         //
4536                         if ((getter == TypeManager.system_int_array_get_length) ||
4537                             (getter == TypeManager.int_array_get_length)){
4538                                 Type iet = instance_expr.Type;
4539
4540                                 //
4541                                 // System.Array.Length can be called, but the Type does not
4542                                 // support invoking GetArrayRank, so test for that case first
4543                                 //
4544                                 if (iet != TypeManager.array_type && (iet.GetArrayRank () == 1)){
4545                                         instance_expr.Emit (ec);
4546                                         ec.ig.Emit (OpCodes.Ldlen);
4547                                         return;
4548                                 }
4549                         }
4550
4551                         Invocation.EmitCall (ec, IsBase, IsStatic, instance_expr, getter, null, loc);
4552                         
4553                 }
4554
4555                 //
4556                 // Implements the IAssignMethod interface for assignments
4557                 //
4558                 public void EmitAssign (EmitContext ec, Expression source)
4559                 {
4560                         Argument arg = new Argument (source, Argument.AType.Expression);
4561                         ArrayList args = new ArrayList ();
4562
4563                         args.Add (arg);
4564                         Invocation.EmitCall (ec, IsBase, IsStatic, instance_expr, setter, args, loc);
4565                 }
4566
4567                 override public void EmitStatement (EmitContext ec)
4568                 {
4569                         Emit (ec);
4570                         ec.ig.Emit (OpCodes.Pop);
4571                 }
4572         }
4573
4574         /// <summary>
4575         ///   Fully resolved expression that evaluates to an Event
4576         /// </summary>
4577         public class EventExpr : Expression, IMemberExpr {
4578                 public readonly EventInfo EventInfo;
4579                 public Expression instance_expr;
4580
4581                 bool is_static;
4582                 MethodInfo add_accessor, remove_accessor;
4583                 
4584                 public EventExpr (EventInfo ei, Location loc)
4585                 {
4586                         EventInfo = ei;
4587                         this.loc = loc;
4588                         eclass = ExprClass.EventAccess;
4589
4590                         add_accessor = TypeManager.GetAddMethod (ei);
4591                         remove_accessor = TypeManager.GetRemoveMethod (ei);
4592                         
4593                         if (add_accessor.IsStatic || remove_accessor.IsStatic)
4594                                 is_static = true;
4595
4596                         if (EventInfo is MyEventBuilder){
4597                                 MyEventBuilder eb = (MyEventBuilder) EventInfo;
4598                                 type = eb.EventType;
4599                                 eb.SetUsed ();
4600                         } else
4601                                 type = EventInfo.EventHandlerType;
4602                 }
4603
4604                 public string Name {
4605                         get {
4606                                 return EventInfo.Name;
4607                         }
4608                 }
4609
4610                 public bool IsInstance {
4611                         get {
4612                                 return !is_static;
4613                         }
4614                 }
4615
4616                 public bool IsStatic {
4617                         get {
4618                                 return is_static;
4619                         }
4620                 }
4621
4622                 public Type DeclaringType {
4623                         get {
4624                                 return EventInfo.DeclaringType;
4625                         }
4626                 }
4627
4628                 public Expression InstanceExpression {
4629                         get {
4630                                 return instance_expr;
4631                         }
4632
4633                         set {
4634                                 instance_expr = value;
4635                         }
4636                 }
4637
4638                 public override Expression DoResolve (EmitContext ec)
4639                 {
4640                         if (instance_expr != null) {
4641                                 instance_expr = instance_expr.DoResolve (ec);
4642                                 if (instance_expr == null)
4643                                         return null;
4644                         }
4645
4646                         
4647                         return this;
4648                 }
4649
4650                 public override void Emit (EmitContext ec)
4651                 {
4652                         Report.Error (70, loc, "The event `" + Name + "' can only appear on the left hand side of += or -= (except on the defining type)");
4653                 }
4654
4655                 public void EmitAddOrRemove (EmitContext ec, Expression source)
4656                 {
4657                         Expression handler = ((Binary) source).Right;
4658                         
4659                         Argument arg = new Argument (handler, Argument.AType.Expression);
4660                         ArrayList args = new ArrayList ();
4661                                 
4662                         args.Add (arg);
4663                         
4664                         if (((Binary) source).Oper == Binary.Operator.Addition)
4665                                 Invocation.EmitCall (
4666                                         ec, false, IsStatic, instance_expr, add_accessor, args, loc);
4667                         else
4668                                 Invocation.EmitCall (
4669                                         ec, false, IsStatic, instance_expr, remove_accessor, args, loc);
4670                 }
4671         }
4672 }