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