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