2004-03-13 Martin Baulig <martin@ximian.com>
[mono.git] / mcs / gmcs / 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, 2002, 2003 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                 VariableInfo VariableInfo {
100                         get;
101                 }
102
103                 bool VerifyFixed (bool is_expression);
104         }
105
106         /// <summary>
107         ///   This interface denotes an expression which evaluates to a member
108         ///   of a struct or a class.
109         /// </summary>
110         public interface IMemberExpr
111         {
112                 /// <summary>
113                 ///   The name of this member.
114                 /// </summary>
115                 string Name {
116                         get;
117                 }
118
119                 /// <summary>
120                 ///   Whether this is an instance member.
121                 /// </summary>
122                 bool IsInstance {
123                         get;
124                 }
125
126                 /// <summary>
127                 ///   Whether this is a static member.
128                 /// </summary>
129                 bool IsStatic {
130                         get;
131                 }
132
133                 /// <summary>
134                 ///   The type which declares this member.
135                 /// </summary>
136                 Type DeclaringType {
137                         get;
138                 }
139
140                 /// <summary>
141                 ///   The instance expression associated with this member, if it's a
142                 ///   non-static member.
143                 /// </summary>
144                 Expression InstanceExpression {
145                         get; set;
146                 }
147         }
148
149         /// <remarks>
150         ///   Base class for expressions
151         /// </remarks>
152         public abstract class Expression {
153                 public ExprClass eclass;
154                 protected Type type;
155                 protected Location loc;
156                 
157                 public Type Type {
158                         get {
159                                 return type;
160                         }
161
162                         set {
163                                 type = value;
164                         }
165                 }
166
167                 public Location Location {
168                         get {
169                                 return loc;
170                         }
171                 }
172
173                 /// <summary>
174                 ///   Utility wrapper routine for Error, just to beautify the code
175                 /// </summary>
176                 public void Error (int error, string s)
177                 {
178                         if (!Location.IsNull (loc))
179                                 Report.Error (error, loc, s);
180                         else
181                                 Report.Error (error, s);
182                 }
183
184                 /// <summary>
185                 ///   Utility wrapper routine for Warning, just to beautify the code
186                 /// </summary>
187                 public void Warning (int warning, string s)
188                 {
189                         if (!Location.IsNull (loc))
190                                 Report.Warning (warning, loc, s);
191                         else
192                                 Report.Warning (warning, s);
193                 }
194
195                 /// <summary>
196                 ///   Utility wrapper routine for Warning, only prints the warning if
197                 ///   warnings of level `level' are enabled.
198                 /// </summary>
199                 public void Warning (int warning, int level, string s)
200                 {
201                         if (level <= RootContext.WarningLevel)
202                                 Warning (warning, s);
203                 }
204
205                 /// <summary>
206                 ///   Performs semantic analysis on the Expression
207                 /// </summary>
208                 ///
209                 /// <remarks>
210                 ///   The Resolve method is invoked to perform the semantic analysis
211                 ///   on the node.
212                 ///
213                 ///   The return value is an expression (it can be the
214                 ///   same expression in some cases) or a new
215                 ///   expression that better represents this node.
216                 ///   
217                 ///   For example, optimizations of Unary (LiteralInt)
218                 ///   would return a new LiteralInt with a negated
219                 ///   value.
220                 ///   
221                 ///   If there is an error during semantic analysis,
222                 ///   then an error should be reported (using Report)
223                 ///   and a null value should be returned.
224                 ///   
225                 ///   There are two side effects expected from calling
226                 ///   Resolve(): the the field variable "eclass" should
227                 ///   be set to any value of the enumeration
228                 ///   `ExprClass' and the type variable should be set
229                 ///   to a valid type (this is the type of the
230                 ///   expression).
231                 /// </remarks>
232                 public abstract Expression DoResolve (EmitContext ec);
233
234                 public virtual Expression DoResolveLValue (EmitContext ec, Expression right_side)
235                 {
236                         return DoResolve (ec);
237                 }
238
239                 //
240                 // This is used if the expression should be resolved as a type.
241                 // the default implementation fails.   Use this method in
242                 // those participants in the SimpleName chain system.
243                 //
244                 public virtual Expression ResolveAsTypeStep (EmitContext ec)
245                 {
246                         return null;
247                 }
248
249                 //
250                 // This is used to resolve the expression as a type, a null
251                 // value will be returned if the expression is not a type
252                 // reference
253                 //
254                 public TypeExpr ResolveAsTypeTerminal (EmitContext ec)
255                 {
256                         return ResolveAsTypeStep (ec) as TypeExpr;
257                 }
258                
259                 /// <summary>
260                 ///   Resolves an expression and performs semantic analysis on it.
261                 /// </summary>
262                 ///
263                 /// <remarks>
264                 ///   Currently Resolve wraps DoResolve to perform sanity
265                 ///   checking and assertion checking on what we expect from Resolve.
266                 /// </remarks>
267                 public Expression Resolve (EmitContext ec, ResolveFlags flags)
268                 {
269                         if ((flags & ResolveFlags.MaskExprClass) == ResolveFlags.Type) 
270                                 return ResolveAsTypeStep (ec);
271
272                         bool old_do_flow_analysis = ec.DoFlowAnalysis;
273                         if ((flags & ResolveFlags.DisableFlowAnalysis) != 0)
274                                 ec.DoFlowAnalysis = false;
275
276                         Expression e;
277                         if (this is SimpleName)
278                                 e = ((SimpleName) this).DoResolveAllowStatic (ec);
279                         else 
280                                 e = DoResolve (ec);
281
282                         ec.DoFlowAnalysis = old_do_flow_analysis;
283
284                         if (e == null)
285                                 return null;
286
287                         if (e is SimpleName){
288                                 SimpleName s = (SimpleName) e;
289
290                                 if ((flags & ResolveFlags.SimpleName) == 0) {
291                                         MemberLookupFailed (ec, null, ec.ContainerType, s.Name,
292                                                             ec.DeclSpace.Name, loc);
293                                         return null;
294                                 }
295
296                                 return s;
297                         }
298
299                         if ((e is TypeExpr) || (e is ComposedCast)) {
300                                 if ((flags & ResolveFlags.Type) == 0) {
301                                         e.Error_UnexpectedKind (flags);
302                                         return null;
303                                 }
304
305                                 return e;
306                         }
307
308                         switch (e.eclass) {
309                         case ExprClass.Type:
310                                 if ((flags & ResolveFlags.VariableOrValue) == 0) {
311                                         e.Error_UnexpectedKind (flags);
312                                         return null;
313                                 }
314                                 break;
315
316                         case ExprClass.MethodGroup:
317                                 if (!RootContext.V2){
318                                 if ((flags & ResolveFlags.MethodGroup) == 0) {
319                                         ((MethodGroupExpr) e).ReportUsageError ();
320                                         return null;
321                                 }
322                                 }
323                                 break;
324
325                         case ExprClass.Value:
326                         case ExprClass.Variable:
327                         case ExprClass.PropertyAccess:
328                         case ExprClass.EventAccess:
329                         case ExprClass.IndexerAccess:
330                                 if ((flags & ResolveFlags.VariableOrValue) == 0) {
331                                         Console.WriteLine ("I got: {0} and {1}", e.GetType (), e);
332                                         Console.WriteLine ("I am {0} and {1}", this.GetType (), this);
333                                         FieldInfo fi = ((FieldExpr) e).FieldInfo;
334                                         
335                                         Console.WriteLine ("{0} and {1}", fi.DeclaringType, fi.Name);
336                                         e.Error_UnexpectedKind (flags);
337                                         return null;
338                                 }
339                                 break;
340
341                         default:
342                                 throw new Exception ("Expression " + e.GetType () +
343                                                      " ExprClass is Invalid after resolve");
344                         }
345
346                         if (e.type == null)
347                                 throw new Exception (
348                                         "Expression " + e.GetType () +
349                                         " did not set its type after Resolve\n" +
350                                         "called from: " + this.GetType ());
351
352                         return e;
353                 }
354
355                 /// <summary>
356                 ///   Resolves an expression and performs semantic analysis on it.
357                 /// </summary>
358                 public Expression Resolve (EmitContext ec)
359                 {
360                         return Resolve (ec, ResolveFlags.VariableOrValue);
361                 }
362
363                 /// <summary>
364                 ///   Resolves an expression for LValue assignment
365                 /// </summary>
366                 ///
367                 /// <remarks>
368                 ///   Currently ResolveLValue wraps DoResolveLValue to perform sanity
369                 ///   checking and assertion checking on what we expect from Resolve
370                 /// </remarks>
371                 public Expression ResolveLValue (EmitContext ec, Expression right_side)
372                 {
373                         Expression e = DoResolveLValue (ec, right_side);
374
375                         if (e != null){
376                                 if (e is SimpleName){
377                                         SimpleName s = (SimpleName) e;
378                                         MemberLookupFailed (ec, null, ec.ContainerType, s.Name,
379                                                             ec.DeclSpace.Name, loc);
380                                         return null;
381                                 }
382
383                                 if (e.eclass == ExprClass.Invalid)
384                                         throw new Exception ("Expression " + e +
385                                                              " ExprClass is Invalid after resolve");
386
387                                 if (e.eclass == ExprClass.MethodGroup) {
388                                         ((MethodGroupExpr) e).ReportUsageError ();
389                                         return null;
390                                 }
391
392                                 if (e.type == null)
393                                         throw new Exception ("Expression " + e +
394                                                              " did not set its type after Resolve");
395                         }
396
397                         return e;
398                 }
399                 
400                 /// <summary>
401                 ///   Emits the code for the expression
402                 /// </summary>
403                 ///
404                 /// <remarks>
405                 ///   The Emit method is invoked to generate the code
406                 ///   for the expression.  
407                 /// </remarks>
408                 public abstract void Emit (EmitContext ec);
409
410                 public virtual void EmitBranchable (EmitContext ec, Label target, bool onTrue)
411                 {
412                         Emit (ec);
413                         ec.ig.Emit (onTrue ? OpCodes.Brtrue : OpCodes.Brfalse, target);
414                 }
415
416                 /// <summary>
417                 ///   Protected constructor.  Only derivate types should
418                 ///   be able to be created
419                 /// </summary>
420
421                 protected Expression ()
422                 {
423                         eclass = ExprClass.Invalid;
424                         type = null;
425                 }
426
427                 /// <summary>
428                 ///   Returns a literalized version of a literal FieldInfo
429                 /// </summary>
430                 ///
431                 /// <remarks>
432                 ///   The possible return values are:
433                 ///      IntConstant, UIntConstant
434                 ///      LongLiteral, ULongConstant
435                 ///      FloatConstant, DoubleConstant
436                 ///      StringConstant
437                 ///
438                 ///   The value returned is already resolved.
439                 /// </remarks>
440                 public static Constant Constantify (object v, Type t)
441                 {
442                         if (t == TypeManager.int32_type)
443                                 return new IntConstant ((int) v);
444                         else if (t == TypeManager.uint32_type)
445                                 return new UIntConstant ((uint) v);
446                         else if (t == TypeManager.int64_type)
447                                 return new LongConstant ((long) v);
448                         else if (t == TypeManager.uint64_type)
449                                 return new ULongConstant ((ulong) v);
450                         else if (t == TypeManager.float_type)
451                                 return new FloatConstant ((float) v);
452                         else if (t == TypeManager.double_type)
453                                 return new DoubleConstant ((double) v);
454                         else if (t == TypeManager.string_type)
455                                 return new StringConstant ((string) v);
456                         else if (t == TypeManager.short_type)
457                                 return new ShortConstant ((short)v);
458                         else if (t == TypeManager.ushort_type)
459                                 return new UShortConstant ((ushort)v);
460                         else if (t == TypeManager.sbyte_type)
461                                 return new SByteConstant (((sbyte)v));
462                         else if (t == TypeManager.byte_type)
463                                 return new ByteConstant ((byte)v);
464                         else if (t == TypeManager.char_type)
465                                 return new CharConstant ((char)v);
466                         else if (t == TypeManager.bool_type)
467                                 return new BoolConstant ((bool) v);
468                         else if (TypeManager.IsEnumType (t)){
469                                 Constant e = Constantify (v, TypeManager.TypeToCoreType (v.GetType ()));
470
471                                 return new EnumConstant (e, t);
472                         } else
473                                 throw new Exception ("Unknown type for constant (" + t +
474                                                      "), details: " + v);
475                 }
476
477                 /// <summary>
478                 ///   Returns a fully formed expression after a MemberLookup
479                 /// </summary>
480                 public static Expression ExprClassFromMemberInfo (EmitContext ec, MemberInfo mi, Location loc)
481                 {
482                         if (mi is EventInfo)
483                                 return new EventExpr ((EventInfo) mi, loc);
484                         else if (mi is FieldInfo)
485                                 return new FieldExpr ((FieldInfo) mi, loc);
486                         else if (mi is PropertyInfo)
487                                 return new PropertyExpr (ec, (PropertyInfo) mi, loc);
488                         else if (mi is Type){
489                                 return new TypeExpression ((System.Type) mi, loc);
490                         }
491
492                         return null;
493                 }
494
495                 //
496                 // FIXME: Probably implement a cache for (t,name,current_access_set)?
497                 //
498                 // This code could use some optimizations, but we need to do some
499                 // measurements.  For example, we could use a delegate to `flag' when
500                 // something can not any longer be a method-group (because it is something
501                 // else).
502                 //
503                 // Return values:
504                 //     If the return value is an Array, then it is an array of
505                 //     MethodBases
506                 //   
507                 //     If the return value is an MemberInfo, it is anything, but a Method
508                 //
509                 //     null on error.
510                 //
511                 // FIXME: When calling MemberLookup inside an `Invocation', we should pass
512                 // the arguments here and have MemberLookup return only the methods that
513                 // match the argument count/type, unlike we are doing now (we delay this
514                 // decision).
515                 //
516                 // This is so we can catch correctly attempts to invoke instance methods
517                 // from a static body (scan for error 120 in ResolveSimpleName).
518                 //
519                 //
520                 // FIXME: Potential optimization, have a static ArrayList
521                 //
522
523                 public static Expression MemberLookup (EmitContext ec, Type queried_type, string name,
524                                                        MemberTypes mt, BindingFlags bf, Location loc)
525                 {
526                         return MemberLookup (ec, ec.ContainerType, null, queried_type, name, mt, bf, loc);
527                 }
528
529                 //
530                 // Lookup type `queried_type' for code in class `container_type' with a qualifier of
531                 // `qualifier_type' or null to lookup members in the current class.
532                 //
533
534                 public static Expression MemberLookup (EmitContext ec, Type container_type,
535                                                        Type qualifier_type, Type queried_type,
536                                                        string name, MemberTypes mt,
537                                                        BindingFlags bf, Location loc)
538                 {
539                         MemberInfo [] mi = TypeManager.MemberLookup (container_type, qualifier_type,
540                                                                      queried_type, mt, bf, name);
541
542                         if (mi == null)
543                                 return null;
544
545                         int count = mi.Length;
546
547                         if (mi [0] is MethodBase)
548                                 return new MethodGroupExpr (mi, loc);
549
550                         if (count > 1)
551                                 return null;
552
553                         return ExprClassFromMemberInfo (ec, mi [0], loc);
554                 }
555
556                 public const MemberTypes AllMemberTypes =
557                         MemberTypes.Constructor |
558                         MemberTypes.Event       |
559                         MemberTypes.Field       |
560                         MemberTypes.Method      |
561                         MemberTypes.NestedType  |
562                         MemberTypes.Property;
563                 
564                 public const BindingFlags AllBindingFlags =
565                         BindingFlags.Public |
566                         BindingFlags.Static |
567                         BindingFlags.Instance;
568
569                 public static Expression MemberLookup (EmitContext ec, Type queried_type,
570                                                        string name, Location loc)
571                 {
572                         return MemberLookup (ec, ec.ContainerType, null, queried_type, name,
573                                              AllMemberTypes, AllBindingFlags, loc);
574                 }
575
576                 public static Expression MemberLookup (EmitContext ec, Type qualifier_type,
577                                                        Type queried_type, string name, Location loc)
578                 {
579                         return MemberLookup (ec, ec.ContainerType, qualifier_type, queried_type,
580                                              name, AllMemberTypes, AllBindingFlags, loc);
581                 }
582
583                 public static Expression MethodLookup (EmitContext ec, Type queried_type,
584                                                        string name, Location loc)
585                 {
586                         return MemberLookup (ec, ec.ContainerType, null, queried_type, name,
587                                              MemberTypes.Method, AllBindingFlags, loc);
588                 }
589
590                 /// <summary>
591                 ///   This is a wrapper for MemberLookup that is not used to "probe", but
592                 ///   to find a final definition.  If the final definition is not found, we
593                 ///   look for private members and display a useful debugging message if we
594                 ///   find it.
595                 /// </summary>
596                 public static Expression MemberLookupFinal (EmitContext ec, Type qualifier_type,
597                                                             Type queried_type, string name, Location loc)
598                 {
599                         return MemberLookupFinal (ec, qualifier_type, queried_type, name,
600                                                   AllMemberTypes, AllBindingFlags, loc);
601                 }
602
603                 public static Expression MemberLookupFinal (EmitContext ec, Type qualifier_type,
604                                                             Type queried_type, string name,
605                                                             MemberTypes mt, BindingFlags bf,
606                                                             Location loc)
607                 {
608                         Expression e;
609
610                         int errors = Report.Errors;
611
612                         e = MemberLookup (ec, ec.ContainerType, qualifier_type, queried_type,
613                                           name, mt, bf, loc);
614
615                         if (e != null)
616                                 return e;
617
618                         // Error has already been reported.
619                         if (errors < Report.Errors)
620                                 return null;
621
622                         MemberLookupFailed (ec, qualifier_type, queried_type, name, null, loc);
623                         return null;
624                 }
625
626                 public static void MemberLookupFailed (EmitContext ec, Type qualifier_type,
627                                                        Type queried_type, string name,
628                                                        string class_name, Location loc)
629                 {
630                         object lookup = TypeManager.MemberLookup (queried_type, null, queried_type,
631                                                                   AllMemberTypes, AllBindingFlags |
632                                                                   BindingFlags.NonPublic, name);
633
634                         if (lookup == null) {
635                                 if (class_name != null)
636                                         Report.Error (103, loc, "The name `" + name + "' could not be " +
637                                                       "found in `" + class_name + "'");
638                                 else
639                                         Report.Error (
640                                                 117, loc, "`" + queried_type + "' does not contain a " +
641                                                 "definition for `" + name + "'");
642                                 return;
643                         }
644
645                         if ((qualifier_type != null) && (qualifier_type != ec.ContainerType) &&
646                             ec.ContainerType.IsSubclassOf (qualifier_type)) {
647                                 // Although a derived class can access protected members of
648                                 // its base class it cannot do so through an instance of the
649                                 // base class (CS1540).  If the qualifier_type is a parent of the
650                                 // ec.ContainerType and the lookup succeeds with the latter one,
651                                 // then we are in this situation.
652
653                                 lookup = TypeManager.MemberLookup (
654                                         ec.ContainerType, ec.ContainerType, ec.ContainerType,
655                                         AllMemberTypes, AllBindingFlags, name);
656
657                                 if (lookup != null) {
658                                         Report.Error (
659                                                 1540, loc, "Cannot access protected member `" +
660                                                 TypeManager.CSharpName (qualifier_type) + "." +
661                                                 name + "' " + "via a qualifier of type `" +
662                                                 TypeManager.CSharpName (qualifier_type) + "'; the " +
663                                                 "qualifier must be of type `" +
664                                                 TypeManager.CSharpName (ec.ContainerType) + "' " +
665                                                 "(or derived from it)");
666                                         return;
667                                 }
668                         }
669
670                         if (qualifier_type != null)
671                                 Report.Error (
672                                         122, loc, "`" + TypeManager.CSharpName (qualifier_type) + "." +
673                                         name + "' is inaccessible due to its protection level");
674                         else if (name == ".ctor") {
675                                 Report.Error (143, loc, String.Format ("The type {0} has no constructors defined",
676                                                                        TypeManager.CSharpName (queried_type)));
677                         } else {
678                                 Report.Error (
679                                         122, loc, "`" + name + "' is inaccessible due to its " +
680                                         "protection level");
681                 }
682                 }
683
684                 static public MemberInfo GetFieldFromEvent (EventExpr event_expr)
685                 {
686                         EventInfo ei = event_expr.EventInfo;
687
688                         return TypeManager.GetPrivateFieldOfEvent (ei);
689                 }
690                 
691                 /// <summary>
692                 ///   Returns an expression that can be used to invoke operator true
693                 ///   on the expression if it exists.
694                 /// </summary>
695                 static public StaticCallExpr GetOperatorTrue (EmitContext ec, Expression e, Location loc)
696                 {
697                         return GetOperatorTrueOrFalse (ec, e, true, loc);
698                 }
699
700                 /// <summary>
701                 ///   Returns an expression that can be used to invoke operator false
702                 ///   on the expression if it exists.
703                 /// </summary>
704                 static public StaticCallExpr GetOperatorFalse (EmitContext ec, Expression e, Location loc)
705                 {
706                         return GetOperatorTrueOrFalse (ec, e, false, loc);
707                 }
708
709                 static StaticCallExpr GetOperatorTrueOrFalse (EmitContext ec, Expression e, bool is_true, Location loc)
710                 {
711                         MethodBase method;
712                         Expression operator_group;
713
714                         operator_group = MethodLookup (ec, e.Type, is_true ? "op_True" : "op_False", loc);
715                         if (operator_group == null)
716                                 return null;
717
718                         ArrayList arguments = new ArrayList ();
719                         arguments.Add (new Argument (e, Argument.AType.Expression));
720                         method = Invocation.OverloadResolve (ec, (MethodGroupExpr) operator_group, arguments, loc);
721
722                         if (method == null)
723                                 return null;
724
725                         return new StaticCallExpr ((MethodInfo) method, arguments, loc);
726                 }
727
728                 /// <summary>
729                 ///   Resolves the expression `e' into a boolean expression: either through
730                 ///   an implicit conversion, or through an `operator true' invocation
731                 /// </summary>
732                 public static Expression ResolveBoolean (EmitContext ec, Expression e, Location loc)
733                 {
734                         e = e.Resolve (ec);
735                         if (e == null)
736                                 return null;
737
738                         Expression converted = e;
739                         if (e.Type != TypeManager.bool_type)
740                                 converted = Convert.ImplicitConversion (ec, e, TypeManager.bool_type, new Location (-1));
741
742                         //
743                         // If no implicit conversion to bool exists, try using `operator true'
744                         //
745                         if (converted == null){
746                                 Expression operator_true = Expression.GetOperatorTrue (ec, e, loc);
747                                 if (operator_true == null){
748                                         Report.Error (
749                                                 31, loc, "Can not convert the expression to a boolean");
750                                         return null;
751                                 }
752                                 e = operator_true;
753                         } else
754                                 e = converted;
755
756                         return e;
757                 }
758                 
759                 static string ExprClassName (ExprClass c)
760                 {
761                         switch (c){
762                         case ExprClass.Invalid:
763                                 return "Invalid";
764                         case ExprClass.Value:
765                                 return "value";
766                         case ExprClass.Variable:
767                                 return "variable";
768                         case ExprClass.Namespace:
769                                 return "namespace";
770                         case ExprClass.Type:
771                                 return "type";
772                         case ExprClass.MethodGroup:
773                                 return "method group";
774                         case ExprClass.PropertyAccess:
775                                 return "property access";
776                         case ExprClass.EventAccess:
777                                 return "event access";
778                         case ExprClass.IndexerAccess:
779                                 return "indexer access";
780                         case ExprClass.Nothing:
781                                 return "null";
782                         }
783                         throw new Exception ("Should not happen");
784                 }
785                 
786                 /// <summary>
787                 ///   Reports that we were expecting `expr' to be of class `expected'
788                 /// </summary>
789                 public void Error_UnexpectedKind (string expected)
790                 {
791                         string kind = "Unknown";
792                         
793                         kind = ExprClassName (eclass);
794
795                         Error (118, "Expression denotes a `" + kind +
796                                "' where a `" + expected + "' was expected");
797                 }
798
799                 public void Error_UnexpectedKind (ResolveFlags flags)
800                 {
801                         ArrayList valid = new ArrayList (10);
802
803                         if ((flags & ResolveFlags.VariableOrValue) != 0) {
804                                 valid.Add ("variable");
805                                 valid.Add ("value");
806                         }
807
808                         if ((flags & ResolveFlags.Type) != 0)
809                                 valid.Add ("type");
810
811                         if ((flags & ResolveFlags.MethodGroup) != 0)
812                                 valid.Add ("method group");
813
814                         if ((flags & ResolveFlags.SimpleName) != 0)
815                                 valid.Add ("simple name");
816
817                         if (valid.Count == 0)
818                                 valid.Add ("unknown");
819
820                         StringBuilder sb = new StringBuilder ();
821                         for (int i = 0; i < valid.Count; i++) {
822                                 if (i > 0)
823                                         sb.Append (", ");
824                                 else if (i == valid.Count)
825                                         sb.Append (" or ");
826                                 sb.Append (valid [i]);
827                         }
828
829                         string kind = ExprClassName (eclass);
830
831                         Error (119, "Expression denotes a `" + kind + "' where " +
832                                "a `" + sb.ToString () + "' was expected");
833                 }
834                 
835                 static public void Error_ConstantValueCannotBeConverted (Location l, string val, Type t)
836                 {
837                         Report.Error (31, l, "Constant value `" + val + "' cannot be converted to " +
838                                       TypeManager.CSharpName (t));
839                 }
840
841                 public static void UnsafeError (Location loc)
842                 {
843                         Report.Error (214, loc, "Pointers may only be used in an unsafe context");
844                 }
845                 
846                 /// <summary>
847                 ///   Converts the IntConstant, UIntConstant, LongConstant or
848                 ///   ULongConstant into the integral target_type.   Notice
849                 ///   that we do not return an `Expression' we do return
850                 ///   a boxed integral type.
851                 ///
852                 ///   FIXME: Since I added the new constants, we need to
853                 ///   also support conversions from CharConstant, ByteConstant,
854                 ///   SByteConstant, UShortConstant, ShortConstant
855                 ///
856                 ///   This is used by the switch statement, so the domain
857                 ///   of work is restricted to the literals above, and the
858                 ///   targets are int32, uint32, char, byte, sbyte, ushort,
859                 ///   short, uint64 and int64
860                 /// </summary>
861                 public static object ConvertIntLiteral (Constant c, Type target_type, Location loc)
862                 {
863                         if (!Convert.ImplicitStandardConversionExists (c, target_type)){
864                                 Convert.Error_CannotImplicitConversion (loc, c.Type, target_type);
865                                 return null;
866                         }
867                         
868                         string s = "";
869
870                         if (c.Type == target_type)
871                                 return ((Constant) c).GetValue ();
872
873                         //
874                         // Make into one of the literals we handle, we dont really care
875                         // about this value as we will just return a few limited types
876                         // 
877                         if (c is EnumConstant)
878                                 c = ((EnumConstant)c).WidenToCompilerConstant ();
879
880                         if (c is IntConstant){
881                                 int v = ((IntConstant) c).Value;
882                                 
883                                 if (target_type == TypeManager.uint32_type){
884                                         if (v >= 0)
885                                                 return (uint) v;
886                                 } else if (target_type == TypeManager.char_type){
887                                         if (v >= Char.MinValue && v <= Char.MaxValue)
888                                                 return (char) v;
889                                 } else if (target_type == TypeManager.byte_type){
890                                         if (v >= Byte.MinValue && v <= Byte.MaxValue)
891                                                 return (byte) v;
892                                 } else if (target_type == TypeManager.sbyte_type){
893                                         if (v >= SByte.MinValue && v <= SByte.MaxValue)
894                                                 return (sbyte) v;
895                                 } else if (target_type == TypeManager.short_type){
896                                         if (v >= Int16.MinValue && v <= UInt16.MaxValue)
897                                                 return (short) v;
898                                 } else if (target_type == TypeManager.ushort_type){
899                                         if (v >= UInt16.MinValue && v <= UInt16.MaxValue)
900                                                 return (ushort) v;
901                                 } else if (target_type == TypeManager.int64_type)
902                                         return (long) v;
903                                 else if (target_type == TypeManager.uint64_type){
904                                         if (v > 0)
905                                                 return (ulong) v;
906                                 }
907
908                                 s = v.ToString ();
909                         } else if (c is UIntConstant){
910                                 uint v = ((UIntConstant) c).Value;
911
912                                 if (target_type == TypeManager.int32_type){
913                                         if (v <= Int32.MaxValue)
914                                                 return (int) v;
915                                 } else if (target_type == TypeManager.char_type){
916                                         if (v >= Char.MinValue && v <= Char.MaxValue)
917                                                 return (char) v;
918                                 } else if (target_type == TypeManager.byte_type){
919                                         if (v <= Byte.MaxValue)
920                                                 return (byte) v;
921                                 } else if (target_type == TypeManager.sbyte_type){
922                                         if (v <= SByte.MaxValue)
923                                                 return (sbyte) v;
924                                 } else if (target_type == TypeManager.short_type){
925                                         if (v <= UInt16.MaxValue)
926                                                 return (short) v;
927                                 } else if (target_type == TypeManager.ushort_type){
928                                         if (v <= UInt16.MaxValue)
929                                                 return (ushort) v;
930                                 } else if (target_type == TypeManager.int64_type)
931                                         return (long) v;
932                                 else if (target_type == TypeManager.uint64_type)
933                                         return (ulong) v;
934                                 s = v.ToString ();
935                         } else if (c is LongConstant){ 
936                                 long v = ((LongConstant) c).Value;
937
938                                 if (target_type == TypeManager.int32_type){
939                                         if (v >= UInt32.MinValue && v <= UInt32.MaxValue)
940                                                 return (int) v;
941                                 } else if (target_type == TypeManager.uint32_type){
942                                         if (v >= 0 && v <= UInt32.MaxValue)
943                                                 return (uint) v;
944                                 } else if (target_type == TypeManager.char_type){
945                                         if (v >= Char.MinValue && v <= Char.MaxValue)
946                                                 return (char) v;
947                                 } else if (target_type == TypeManager.byte_type){
948                                         if (v >= Byte.MinValue && v <= Byte.MaxValue)
949                                                 return (byte) v;
950                                 } else if (target_type == TypeManager.sbyte_type){
951                                         if (v >= SByte.MinValue && v <= SByte.MaxValue)
952                                                 return (sbyte) v;
953                                 } else if (target_type == TypeManager.short_type){
954                                         if (v >= Int16.MinValue && v <= UInt16.MaxValue)
955                                                 return (short) v;
956                                 } else if (target_type == TypeManager.ushort_type){
957                                         if (v >= UInt16.MinValue && v <= UInt16.MaxValue)
958                                                 return (ushort) v;
959                                 } else if (target_type == TypeManager.uint64_type){
960                                         if (v > 0)
961                                                 return (ulong) v;
962                                 }
963                                 s = v.ToString ();
964                         } else if (c is ULongConstant){
965                                 ulong v = ((ULongConstant) c).Value;
966
967                                 if (target_type == TypeManager.int32_type){
968                                         if (v <= Int32.MaxValue)
969                                                 return (int) v;
970                                 } else if (target_type == TypeManager.uint32_type){
971                                         if (v <= UInt32.MaxValue)
972                                                 return (uint) v;
973                                 } else if (target_type == TypeManager.char_type){
974                                         if (v >= Char.MinValue && v <= Char.MaxValue)
975                                                 return (char) v;
976                                 } else if (target_type == TypeManager.byte_type){
977                                         if (v >= Byte.MinValue && v <= Byte.MaxValue)
978                                                 return (byte) v;
979                                 } else if (target_type == TypeManager.sbyte_type){
980                                         if (v <= (int) SByte.MaxValue)
981                                                 return (sbyte) v;
982                                 } else if (target_type == TypeManager.short_type){
983                                         if (v <= UInt16.MaxValue)
984                                                 return (short) v;
985                                 } else if (target_type == TypeManager.ushort_type){
986                                         if (v <= UInt16.MaxValue)
987                                                 return (ushort) v;
988                                 } else if (target_type == TypeManager.int64_type){
989                                         if (v <= Int64.MaxValue)
990                                                 return (long) v;
991                                 }
992                                 s = v.ToString ();
993                         } else if (c is ByteConstant){
994                                 byte v = ((ByteConstant) c).Value;
995                                 
996                                 if (target_type == TypeManager.int32_type)
997                                         return (int) v;
998                                 else if (target_type == TypeManager.uint32_type)
999                                         return (uint) v;
1000                                 else if (target_type == TypeManager.char_type)
1001                                         return (char) v;
1002                                 else if (target_type == TypeManager.sbyte_type){
1003                                         if (v <= SByte.MaxValue)
1004                                                 return (sbyte) v;
1005                                 } else if (target_type == TypeManager.short_type)
1006                                         return (short) v;
1007                                 else if (target_type == TypeManager.ushort_type)
1008                                         return (ushort) v;
1009                                 else if (target_type == TypeManager.int64_type)
1010                                         return (long) v;
1011                                 else if (target_type == TypeManager.uint64_type)
1012                                         return (ulong) v;
1013                                 s = v.ToString ();
1014                         } else if (c is SByteConstant){
1015                                 sbyte v = ((SByteConstant) c).Value;
1016                                 
1017                                 if (target_type == TypeManager.int32_type)
1018                                         return (int) v;
1019                                 else if (target_type == TypeManager.uint32_type){
1020                                         if (v >= 0)
1021                                                 return (uint) v;
1022                                 } else if (target_type == TypeManager.char_type){
1023                                         if (v >= 0)
1024                                                 return (char) v;
1025                                 } else if (target_type == TypeManager.byte_type){
1026                                         if (v >= 0)
1027                                                 return (byte) v;
1028                                 } else if (target_type == TypeManager.short_type)
1029                                         return (short) v;
1030                                 else if (target_type == TypeManager.ushort_type){
1031                                         if (v >= 0)
1032                                                 return (ushort) v;
1033                                 } else if (target_type == TypeManager.int64_type)
1034                                         return (long) v;
1035                                 else if (target_type == TypeManager.uint64_type){
1036                                         if (v >= 0)
1037                                                 return (ulong) v;
1038                                 }
1039                                 s = v.ToString ();
1040                         } else if (c is ShortConstant){
1041                                 short v = ((ShortConstant) c).Value;
1042                                 
1043                                 if (target_type == TypeManager.int32_type){
1044                                         return (int) v;
1045                                 } else if (target_type == TypeManager.uint32_type){
1046                                         if (v >= 0)
1047                                                 return (uint) v;
1048                                 } else if (target_type == TypeManager.char_type){
1049                                         if (v >= 0)
1050                                                 return (char) v;
1051                                 } else if (target_type == TypeManager.byte_type){
1052                                         if (v >= Byte.MinValue && v <= Byte.MaxValue)
1053                                                 return (byte) v;
1054                                 } else if (target_type == TypeManager.sbyte_type){
1055                                         if (v >= SByte.MinValue && v <= SByte.MaxValue)
1056                                                 return (sbyte) v;
1057                                 } else if (target_type == TypeManager.ushort_type){
1058                                         if (v >= 0)
1059                                                 return (ushort) v;
1060                                 } else if (target_type == TypeManager.int64_type)
1061                                         return (long) v;
1062                                 else if (target_type == TypeManager.uint64_type)
1063                                         return (ulong) v;
1064
1065                                 s = v.ToString ();
1066                         } else if (c is UShortConstant){
1067                                 ushort v = ((UShortConstant) c).Value;
1068                                 
1069                                 if (target_type == TypeManager.int32_type)
1070                                         return (int) v;
1071                                 else if (target_type == TypeManager.uint32_type)
1072                                         return (uint) v;
1073                                 else if (target_type == TypeManager.char_type){
1074                                         if (v >= Char.MinValue && v <= Char.MaxValue)
1075                                                 return (char) v;
1076                                 } else if (target_type == TypeManager.byte_type){
1077                                         if (v >= Byte.MinValue && v <= Byte.MaxValue)
1078                                                 return (byte) v;
1079                                 } else if (target_type == TypeManager.sbyte_type){
1080                                         if (v <= SByte.MaxValue)
1081                                                 return (byte) v;
1082                                 } else if (target_type == TypeManager.short_type){
1083                                         if (v <= Int16.MaxValue)
1084                                                 return (short) v;
1085                                 } else if (target_type == TypeManager.int64_type)
1086                                         return (long) v;
1087                                 else if (target_type == TypeManager.uint64_type)
1088                                         return (ulong) v;
1089
1090                                 s = v.ToString ();
1091                         } else if (c is CharConstant){
1092                                 char v = ((CharConstant) c).Value;
1093                                 
1094                                 if (target_type == TypeManager.int32_type)
1095                                         return (int) v;
1096                                 else if (target_type == TypeManager.uint32_type)
1097                                         return (uint) v;
1098                                 else if (target_type == TypeManager.byte_type){
1099                                         if (v >= Byte.MinValue && v <= Byte.MaxValue)
1100                                                 return (byte) v;
1101                                 } else if (target_type == TypeManager.sbyte_type){
1102                                         if (v <= SByte.MaxValue)
1103                                                 return (sbyte) v;
1104                                 } else if (target_type == TypeManager.short_type){
1105                                         if (v <= Int16.MaxValue)
1106                                                 return (short) v;
1107                                 } else if (target_type == TypeManager.ushort_type)
1108                                         return (short) v;
1109                                 else if (target_type == TypeManager.int64_type)
1110                                         return (long) v;
1111                                 else if (target_type == TypeManager.uint64_type)
1112                                         return (ulong) v;
1113
1114                                 s = v.ToString ();
1115                         }
1116                         Error_ConstantValueCannotBeConverted (loc, s, target_type);
1117                         return null;
1118                 }
1119
1120                 //
1121                 // Load the object from the pointer.  
1122                 //
1123                 public static void LoadFromPtr (ILGenerator ig, Type t)
1124                 {
1125                         if (t == TypeManager.int32_type)
1126                                 ig.Emit (OpCodes.Ldind_I4);
1127                         else if (t == TypeManager.uint32_type)
1128                                 ig.Emit (OpCodes.Ldind_U4);
1129                         else if (t == TypeManager.short_type)
1130                                 ig.Emit (OpCodes.Ldind_I2);
1131                         else if (t == TypeManager.ushort_type)
1132                                 ig.Emit (OpCodes.Ldind_U2);
1133                         else if (t == TypeManager.char_type)
1134                                 ig.Emit (OpCodes.Ldind_U2);
1135                         else if (t == TypeManager.byte_type)
1136                                 ig.Emit (OpCodes.Ldind_U1);
1137                         else if (t == TypeManager.sbyte_type)
1138                                 ig.Emit (OpCodes.Ldind_I1);
1139                         else if (t == TypeManager.uint64_type)
1140                                 ig.Emit (OpCodes.Ldind_I8);
1141                         else if (t == TypeManager.int64_type)
1142                                 ig.Emit (OpCodes.Ldind_I8);
1143                         else if (t == TypeManager.float_type)
1144                                 ig.Emit (OpCodes.Ldind_R4);
1145                         else if (t == TypeManager.double_type)
1146                                 ig.Emit (OpCodes.Ldind_R8);
1147                         else if (t == TypeManager.bool_type)
1148                                 ig.Emit (OpCodes.Ldind_I1);
1149                         else if (t == TypeManager.intptr_type)
1150                                 ig.Emit (OpCodes.Ldind_I);
1151                         else if (TypeManager.IsEnumType (t)) {
1152                                 if (t == TypeManager.enum_type)
1153                                         ig.Emit (OpCodes.Ldind_Ref);
1154                                 else
1155                                         LoadFromPtr (ig, TypeManager.EnumToUnderlying (t));
1156                         } else if (t.IsValueType)
1157                                 ig.Emit (OpCodes.Ldobj, t);
1158                         else if (t.IsPointer)
1159                                 ig.Emit (OpCodes.Ldind_I);
1160                         else 
1161                                 ig.Emit (OpCodes.Ldind_Ref);
1162                 }
1163
1164                 //
1165                 // The stack contains the pointer and the value of type `type'
1166                 //
1167                 public static void StoreFromPtr (ILGenerator ig, Type type)
1168                 {
1169                         if (TypeManager.IsEnumType (type))
1170                                 type = TypeManager.EnumToUnderlying (type);
1171                         if (type == TypeManager.int32_type || type == TypeManager.uint32_type)
1172                                 ig.Emit (OpCodes.Stind_I4);
1173                         else if (type == TypeManager.int64_type || type == TypeManager.uint64_type)
1174                                 ig.Emit (OpCodes.Stind_I8);
1175                         else if (type == TypeManager.char_type || type == TypeManager.short_type ||
1176                                  type == TypeManager.ushort_type)
1177                                 ig.Emit (OpCodes.Stind_I2);
1178                         else if (type == TypeManager.float_type)
1179                                 ig.Emit (OpCodes.Stind_R4);
1180                         else if (type == TypeManager.double_type)
1181                                 ig.Emit (OpCodes.Stind_R8);
1182                         else if (type == TypeManager.byte_type || type == TypeManager.sbyte_type ||
1183                                  type == TypeManager.bool_type)
1184                                 ig.Emit (OpCodes.Stind_I1);
1185                         else if (type == TypeManager.intptr_type)
1186                                 ig.Emit (OpCodes.Stind_I);
1187                         else if (type.IsValueType)
1188                                 ig.Emit (OpCodes.Stobj, type);
1189                         else
1190                                 ig.Emit (OpCodes.Stind_Ref);
1191                 }
1192                 
1193                 //
1194                 // Returns the size of type `t' if known, otherwise, 0
1195                 //
1196                 public static int GetTypeSize (Type t)
1197                 {
1198                         t = TypeManager.TypeToCoreType (t);
1199                         if (t == TypeManager.int32_type ||
1200                             t == TypeManager.uint32_type ||
1201                             t == TypeManager.float_type)
1202                                 return 4;
1203                         else if (t == TypeManager.int64_type ||
1204                                  t == TypeManager.uint64_type ||
1205                                  t == TypeManager.double_type)
1206                                 return 8;
1207                         else if (t == TypeManager.byte_type ||
1208                                  t == TypeManager.sbyte_type ||
1209                                  t == TypeManager.bool_type)    
1210                                 return 1;
1211                         else if (t == TypeManager.short_type ||
1212                                  t == TypeManager.char_type ||
1213                                  t == TypeManager.ushort_type)
1214                                 return 2;
1215                         else if (t == TypeManager.decimal_type)
1216                                 return 16;
1217                         else
1218                                 return 0;
1219                 }
1220
1221                 //
1222                 // Default implementation of IAssignMethod.CacheTemporaries
1223                 //
1224                 public void CacheTemporaries (EmitContext ec)
1225                 {
1226                 }
1227
1228                 static void Error_NegativeArrayIndex (Location loc)
1229                 {
1230                         Report.Error (284, loc, "Can not create array with a negative size");
1231                 }
1232                 
1233                 //
1234                 // Converts `source' to an int, uint, long or ulong.
1235                 //
1236                 public Expression ExpressionToArrayArgument (EmitContext ec, Expression source, Location loc)
1237                 {
1238                         Expression target;
1239                         
1240                         bool old_checked = ec.CheckState;
1241                         ec.CheckState = true;
1242                         
1243                         target = Convert.ImplicitConversion (ec, source, TypeManager.int32_type, loc);
1244                         if (target == null){
1245                                 target = Convert.ImplicitConversion (ec, source, TypeManager.uint32_type, loc);
1246                                 if (target == null){
1247                                         target = Convert.ImplicitConversion (ec, source, TypeManager.int64_type, loc);
1248                                         if (target == null){
1249                                                 target = Convert.ImplicitConversion (ec, source, TypeManager.uint64_type, loc);
1250                                                 if (target == null)
1251                                                         Convert.Error_CannotImplicitConversion (loc, source.Type, TypeManager.int32_type);
1252                                         }
1253                                 }
1254                         } 
1255                         ec.CheckState = old_checked;
1256
1257                         //
1258                         // Only positive constants are allowed at compile time
1259                         //
1260                         if (target is Constant){
1261                                 if (target is IntConstant){
1262                                         if (((IntConstant) target).Value < 0){
1263                                                 Error_NegativeArrayIndex (loc);
1264                                                 return null;
1265                                         }
1266                                 }
1267
1268                                 if (target is LongConstant){
1269                                         if (((LongConstant) target).Value < 0){
1270                                                 Error_NegativeArrayIndex (loc);
1271                                                 return null;
1272                                         }
1273                                 }
1274                                 
1275                         }
1276
1277                         return target;
1278                 }
1279                 
1280         }
1281
1282         /// <summary>
1283         ///   This is just a base class for expressions that can
1284         ///   appear on statements (invocations, object creation,
1285         ///   assignments, post/pre increment and decrement).  The idea
1286         ///   being that they would support an extra Emition interface that
1287         ///   does not leave a result on the stack.
1288         /// </summary>
1289         public abstract class ExpressionStatement : Expression {
1290
1291                 public virtual ExpressionStatement ResolveStatement (EmitContext ec)
1292                 {
1293                         Expression e = Resolve (ec);
1294                         if (e == null)
1295                                 return null;
1296
1297                         ExpressionStatement es = e as ExpressionStatement;
1298                         if (es == null)
1299                                 Error (201, "Only assignment, call, increment, decrement and new object " +
1300                                        "expressions can be used as a statement");
1301
1302                         return es;
1303                 }
1304
1305                 /// <summary>
1306                 ///   Requests the expression to be emitted in a `statement'
1307                 ///   context.  This means that no new value is left on the
1308                 ///   stack after invoking this method (constrasted with
1309                 ///   Emit that will always leave a value on the stack).
1310                 /// </summary>
1311                 public abstract void EmitStatement (EmitContext ec);
1312         }
1313
1314         /// <summary>
1315         ///   This kind of cast is used to encapsulate the child
1316         ///   whose type is child.Type into an expression that is
1317         ///   reported to return "return_type".  This is used to encapsulate
1318         ///   expressions which have compatible types, but need to be dealt
1319         ///   at higher levels with.
1320         ///
1321         ///   For example, a "byte" expression could be encapsulated in one
1322         ///   of these as an "unsigned int".  The type for the expression
1323         ///   would be "unsigned int".
1324         ///
1325         /// </summary>
1326         public class EmptyCast : Expression {
1327                 protected Expression child;
1328                 
1329                 public Expression Child {
1330                         get {
1331                                 return child;
1332                         }
1333                 }               
1334
1335                 public EmptyCast (Expression child, Type return_type)
1336                 {
1337                         eclass = child.eclass;
1338                         type = return_type;
1339                         this.child = child;
1340                 }
1341
1342                 public override Expression DoResolve (EmitContext ec)
1343                 {
1344                         // This should never be invoked, we are born in fully
1345                         // initialized state.
1346
1347                         return this;
1348                 }
1349
1350                 public override void Emit (EmitContext ec)
1351                 {
1352                         child.Emit (ec);
1353                 }
1354         }
1355
1356         //
1357         // We need to special case this since an empty cast of
1358         // a NullLiteral is still a Constant
1359         //
1360         public class NullCast : Constant {
1361                 protected Expression child;
1362                                 
1363                 public NullCast (Expression child, Type return_type)
1364                 {
1365                         eclass = child.eclass;
1366                         type = return_type;
1367                         this.child = child;
1368                 }
1369
1370                 override public string AsString ()
1371                 {
1372                         return "null";
1373                 }
1374
1375                 public override object GetValue ()
1376                 {
1377                         return null;
1378                 }
1379
1380                 public override Expression DoResolve (EmitContext ec)
1381                 {
1382                         // This should never be invoked, we are born in fully
1383                         // initialized state.
1384
1385                         return this;
1386                 }
1387
1388                 public override void Emit (EmitContext ec)
1389                 {
1390                         child.Emit (ec);
1391                 }
1392         }
1393
1394
1395         /// <summary>
1396         ///  This class is used to wrap literals which belong inside Enums
1397         /// </summary>
1398         public class EnumConstant : Constant {
1399                 public Constant Child;
1400
1401                 public EnumConstant (Constant child, Type enum_type)
1402                 {
1403                         eclass = child.eclass;
1404                         this.Child = child;
1405                         type = enum_type;
1406                 }
1407                 
1408                 public override Expression DoResolve (EmitContext ec)
1409                 {
1410                         // This should never be invoked, we are born in fully
1411                         // initialized state.
1412
1413                         return this;
1414                 }
1415
1416                 public override void Emit (EmitContext ec)
1417                 {
1418                         Child.Emit (ec);
1419                 }
1420
1421                 public override object GetValue ()
1422                 {
1423                         return Child.GetValue ();
1424                 }
1425
1426                 //
1427                 // Converts from one of the valid underlying types for an enumeration
1428                 // (int32, uint32, int64, uint64, short, ushort, byte, sbyte) to
1429                 // one of the internal compiler literals: Int/UInt/Long/ULong Literals.
1430                 //
1431                 public Constant WidenToCompilerConstant ()
1432                 {
1433                         Type t = TypeManager.EnumToUnderlying (Child.Type);
1434                         object v = ((Constant) Child).GetValue ();;
1435                         
1436                         if (t == TypeManager.int32_type)
1437                                 return new IntConstant ((int) v);
1438                         if (t == TypeManager.uint32_type)
1439                                 return new UIntConstant ((uint) v);
1440                         if (t == TypeManager.int64_type)
1441                                 return new LongConstant ((long) v);
1442                         if (t == TypeManager.uint64_type)
1443                                 return new ULongConstant ((ulong) v);
1444                         if (t == TypeManager.short_type)
1445                                 return new ShortConstant ((short) v);
1446                         if (t == TypeManager.ushort_type)
1447                                 return new UShortConstant ((ushort) v);
1448                         if (t == TypeManager.byte_type)
1449                                 return new ByteConstant ((byte) v);
1450                         if (t == TypeManager.sbyte_type)
1451                                 return new SByteConstant ((sbyte) v);
1452
1453                         throw new Exception ("Invalid enumeration underlying type: " + t);
1454                 }
1455
1456                 //
1457                 // Extracts the value in the enumeration on its native representation
1458                 //
1459                 public object GetPlainValue ()
1460                 {
1461                         Type t = TypeManager.EnumToUnderlying (Child.Type);
1462                         object v = ((Constant) Child).GetValue ();;
1463                         
1464                         if (t == TypeManager.int32_type)
1465                                 return (int) v;
1466                         if (t == TypeManager.uint32_type)
1467                                 return (uint) v;
1468                         if (t == TypeManager.int64_type)
1469                                 return (long) v;
1470                         if (t == TypeManager.uint64_type)
1471                                 return (ulong) v;
1472                         if (t == TypeManager.short_type)
1473                                 return (short) v;
1474                         if (t == TypeManager.ushort_type)
1475                                 return (ushort) v;
1476                         if (t == TypeManager.byte_type)
1477                                 return (byte) v;
1478                         if (t == TypeManager.sbyte_type)
1479                                 return (sbyte) v;
1480
1481                         return null;
1482                 }
1483                 
1484                 public override string AsString ()
1485                 {
1486                         return Child.AsString ();
1487                 }
1488
1489                 public override DoubleConstant ConvertToDouble ()
1490                 {
1491                         return Child.ConvertToDouble ();
1492                 }
1493
1494                 public override FloatConstant ConvertToFloat ()
1495                 {
1496                         return Child.ConvertToFloat ();
1497                 }
1498
1499                 public override ULongConstant ConvertToULong ()
1500                 {
1501                         return Child.ConvertToULong ();
1502                 }
1503
1504                 public override LongConstant ConvertToLong ()
1505                 {
1506                         return Child.ConvertToLong ();
1507                 }
1508
1509                 public override UIntConstant ConvertToUInt ()
1510                 {
1511                         return Child.ConvertToUInt ();
1512                 }
1513
1514                 public override IntConstant ConvertToInt ()
1515                 {
1516                         return Child.ConvertToInt ();
1517                 }
1518         }
1519
1520         /// <summary>
1521         ///   This kind of cast is used to encapsulate Value Types in objects.
1522         ///
1523         ///   The effect of it is to box the value type emitted by the previous
1524         ///   operation.
1525         /// </summary>
1526         public class BoxedCast : EmptyCast {
1527
1528                 public BoxedCast (Expression expr)
1529                         : base (expr, TypeManager.object_type) 
1530                 {
1531                 }
1532
1533                 public BoxedCast (Expression expr, Type target_type)
1534                         : base (expr, target_type)
1535                 {
1536                 }
1537                 
1538                 public override Expression DoResolve (EmitContext ec)
1539                 {
1540                         // This should never be invoked, we are born in fully
1541                         // initialized state.
1542
1543                         return this;
1544                 }
1545
1546                 public override void Emit (EmitContext ec)
1547                 {
1548                         base.Emit (ec);
1549                         
1550                         ec.ig.Emit (OpCodes.Box, child.Type);
1551                 }
1552         }
1553
1554         public class UnboxCast : EmptyCast {
1555                 public UnboxCast (Expression expr, Type return_type)
1556                         : base (expr, return_type)
1557                 {
1558                 }
1559
1560                 public override Expression DoResolve (EmitContext ec)
1561                 {
1562                         // This should never be invoked, we are born in fully
1563                         // initialized state.
1564
1565                         return this;
1566                 }
1567
1568                 public override void Emit (EmitContext ec)
1569                 {
1570                         Type t = type;
1571                         ILGenerator ig = ec.ig;
1572                         
1573                         base.Emit (ec);
1574                         ig.Emit (OpCodes.Unbox, t);
1575
1576                         LoadFromPtr (ig, t);
1577                 }
1578         }
1579         
1580         /// <summary>
1581         ///   This is used to perform explicit numeric conversions.
1582         ///
1583         ///   Explicit numeric conversions might trigger exceptions in a checked
1584         ///   context, so they should generate the conv.ovf opcodes instead of
1585         ///   conv opcodes.
1586         /// </summary>
1587         public class ConvCast : EmptyCast {
1588                 public enum Mode : byte {
1589                         I1_U1, I1_U2, I1_U4, I1_U8, I1_CH,
1590                         U1_I1, U1_CH,
1591                         I2_I1, I2_U1, I2_U2, I2_U4, I2_U8, I2_CH,
1592                         U2_I1, U2_U1, U2_I2, U2_CH,
1593                         I4_I1, I4_U1, I4_I2, I4_U2, I4_U4, I4_U8, I4_CH,
1594                         U4_I1, U4_U1, U4_I2, U4_U2, U4_I4, U4_CH,
1595                         I8_I1, I8_U1, I8_I2, I8_U2, I8_I4, I8_U4, I8_U8, I8_CH,
1596                         U8_I1, U8_U1, U8_I2, U8_U2, U8_I4, U8_U4, U8_I8, U8_CH,
1597                         CH_I1, CH_U1, CH_I2,
1598                         R4_I1, R4_U1, R4_I2, R4_U2, R4_I4, R4_U4, R4_I8, R4_U8, R4_CH,
1599                         R8_I1, R8_U1, R8_I2, R8_U2, R8_I4, R8_U4, R8_I8, R8_U8, R8_CH, R8_R4
1600                 }
1601
1602                 Mode mode;
1603                 bool checked_state;
1604                 
1605                 public ConvCast (EmitContext ec, Expression child, Type return_type, Mode m)
1606                         : base (child, return_type)
1607                 {
1608                         checked_state = ec.CheckState;
1609                         mode = m;
1610                 }
1611
1612                 public override Expression DoResolve (EmitContext ec)
1613                 {
1614                         // This should never be invoked, we are born in fully
1615                         // initialized state.
1616
1617                         return this;
1618                 }
1619
1620                 public override string ToString ()
1621                 {
1622                         return String.Format ("ConvCast ({0}, {1})", mode, child);
1623                 }
1624                 
1625                 public override void Emit (EmitContext ec)
1626                 {
1627                         ILGenerator ig = ec.ig;
1628                         
1629                         base.Emit (ec);
1630
1631                         if (checked_state){
1632                                 switch (mode){
1633                                 case Mode.I1_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1634                                 case Mode.I1_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1635                                 case Mode.I1_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1636                                 case Mode.I1_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1637                                 case Mode.I1_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1638
1639                                 case Mode.U1_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1640                                 case Mode.U1_CH: /* nothing */ break;
1641
1642                                 case Mode.I2_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1643                                 case Mode.I2_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1644                                 case Mode.I2_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1645                                 case Mode.I2_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1646                                 case Mode.I2_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1647                                 case Mode.I2_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1648
1649                                 case Mode.U2_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1650                                 case Mode.U2_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1651                                 case Mode.U2_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1652                                 case Mode.U2_CH: /* nothing */ break;
1653
1654                                 case Mode.I4_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1655                                 case Mode.I4_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1656                                 case Mode.I4_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1657                                 case Mode.I4_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1658                                 case Mode.I4_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1659                                 case Mode.I4_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1660                                 case Mode.I4_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1661
1662                                 case Mode.U4_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1663                                 case Mode.U4_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1664                                 case Mode.U4_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1665                                 case Mode.U4_U2: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1666                                 case Mode.U4_I4: ig.Emit (OpCodes.Conv_Ovf_I4_Un); break;
1667                                 case Mode.U4_CH: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1668
1669                                 case Mode.I8_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1670                                 case Mode.I8_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1671                                 case Mode.I8_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1672                                 case Mode.I8_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1673                                 case Mode.I8_I4: ig.Emit (OpCodes.Conv_Ovf_I4); break;
1674                                 case Mode.I8_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1675                                 case Mode.I8_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1676                                 case Mode.I8_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1677
1678                                 case Mode.U8_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1679                                 case Mode.U8_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1680                                 case Mode.U8_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1681                                 case Mode.U8_U2: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1682                                 case Mode.U8_I4: ig.Emit (OpCodes.Conv_Ovf_I4_Un); break;
1683                                 case Mode.U8_U4: ig.Emit (OpCodes.Conv_Ovf_U4_Un); break;
1684                                 case Mode.U8_I8: ig.Emit (OpCodes.Conv_Ovf_I8_Un); break;
1685                                 case Mode.U8_CH: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1686
1687                                 case Mode.CH_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1688                                 case Mode.CH_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1689                                 case Mode.CH_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1690
1691                                 case Mode.R4_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1692                                 case Mode.R4_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1693                                 case Mode.R4_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1694                                 case Mode.R4_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1695                                 case Mode.R4_I4: ig.Emit (OpCodes.Conv_Ovf_I4); break;
1696                                 case Mode.R4_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1697                                 case Mode.R4_I8: ig.Emit (OpCodes.Conv_Ovf_I8); break;
1698                                 case Mode.R4_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1699                                 case Mode.R4_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1700
1701                                 case Mode.R8_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1702                                 case Mode.R8_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1703                                 case Mode.R8_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1704                                 case Mode.R8_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1705                                 case Mode.R8_I4: ig.Emit (OpCodes.Conv_Ovf_I4); break;
1706                                 case Mode.R8_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1707                                 case Mode.R8_I8: ig.Emit (OpCodes.Conv_Ovf_I8); break;
1708                                 case Mode.R8_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1709                                 case Mode.R8_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1710                                 case Mode.R8_R4: ig.Emit (OpCodes.Conv_R4); break;
1711                                 }
1712                         } else {
1713                                 switch (mode){
1714                                 case Mode.I1_U1: ig.Emit (OpCodes.Conv_U1); break;
1715                                 case Mode.I1_U2: ig.Emit (OpCodes.Conv_U2); break;
1716                                 case Mode.I1_U4: ig.Emit (OpCodes.Conv_U4); break;
1717                                 case Mode.I1_U8: ig.Emit (OpCodes.Conv_I8); break;
1718                                 case Mode.I1_CH: ig.Emit (OpCodes.Conv_U2); break;
1719
1720                                 case Mode.U1_I1: ig.Emit (OpCodes.Conv_I1); break;
1721                                 case Mode.U1_CH: ig.Emit (OpCodes.Conv_U2); break;
1722
1723                                 case Mode.I2_I1: ig.Emit (OpCodes.Conv_I1); break;
1724                                 case Mode.I2_U1: ig.Emit (OpCodes.Conv_U1); break;
1725                                 case Mode.I2_U2: ig.Emit (OpCodes.Conv_U2); break;
1726                                 case Mode.I2_U4: ig.Emit (OpCodes.Conv_U4); break;
1727                                 case Mode.I2_U8: ig.Emit (OpCodes.Conv_I8); break;
1728                                 case Mode.I2_CH: ig.Emit (OpCodes.Conv_U2); break;
1729
1730                                 case Mode.U2_I1: ig.Emit (OpCodes.Conv_I1); break;
1731                                 case Mode.U2_U1: ig.Emit (OpCodes.Conv_U1); break;
1732                                 case Mode.U2_I2: ig.Emit (OpCodes.Conv_I2); break;
1733                                 case Mode.U2_CH: /* nothing */ break;
1734
1735                                 case Mode.I4_I1: ig.Emit (OpCodes.Conv_I1); break;
1736                                 case Mode.I4_U1: ig.Emit (OpCodes.Conv_U1); break;
1737                                 case Mode.I4_I2: ig.Emit (OpCodes.Conv_I2); break;
1738                                 case Mode.I4_U4: /* nothing */ break;
1739                                 case Mode.I4_U2: ig.Emit (OpCodes.Conv_U2); break;
1740                                 case Mode.I4_U8: ig.Emit (OpCodes.Conv_I8); break;
1741                                 case Mode.I4_CH: ig.Emit (OpCodes.Conv_U2); break;
1742
1743                                 case Mode.U4_I1: ig.Emit (OpCodes.Conv_I1); break;
1744                                 case Mode.U4_U1: ig.Emit (OpCodes.Conv_U1); break;
1745                                 case Mode.U4_I2: ig.Emit (OpCodes.Conv_I2); break;
1746                                 case Mode.U4_U2: ig.Emit (OpCodes.Conv_U2); break;
1747                                 case Mode.U4_I4: /* nothing */ break;
1748                                 case Mode.U4_CH: ig.Emit (OpCodes.Conv_U2); break;
1749
1750                                 case Mode.I8_I1: ig.Emit (OpCodes.Conv_I1); break;
1751                                 case Mode.I8_U1: ig.Emit (OpCodes.Conv_U1); break;
1752                                 case Mode.I8_I2: ig.Emit (OpCodes.Conv_I2); break;
1753                                 case Mode.I8_U2: ig.Emit (OpCodes.Conv_U2); break;
1754                                 case Mode.I8_I4: ig.Emit (OpCodes.Conv_I4); break;
1755                                 case Mode.I8_U4: ig.Emit (OpCodes.Conv_U4); break;
1756                                 case Mode.I8_U8: /* nothing */ break;
1757                                 case Mode.I8_CH: ig.Emit (OpCodes.Conv_U2); break;
1758
1759                                 case Mode.U8_I1: ig.Emit (OpCodes.Conv_I1); break;
1760                                 case Mode.U8_U1: ig.Emit (OpCodes.Conv_U1); break;
1761                                 case Mode.U8_I2: ig.Emit (OpCodes.Conv_I2); break;
1762                                 case Mode.U8_U2: ig.Emit (OpCodes.Conv_U2); break;
1763                                 case Mode.U8_I4: ig.Emit (OpCodes.Conv_I4); break;
1764                                 case Mode.U8_U4: ig.Emit (OpCodes.Conv_U4); break;
1765                                 case Mode.U8_I8: /* nothing */ break;
1766                                 case Mode.U8_CH: ig.Emit (OpCodes.Conv_U2); break;
1767
1768                                 case Mode.CH_I1: ig.Emit (OpCodes.Conv_I1); break;
1769                                 case Mode.CH_U1: ig.Emit (OpCodes.Conv_U1); break;
1770                                 case Mode.CH_I2: ig.Emit (OpCodes.Conv_I2); break;
1771
1772                                 case Mode.R4_I1: ig.Emit (OpCodes.Conv_I1); break;
1773                                 case Mode.R4_U1: ig.Emit (OpCodes.Conv_U1); break;
1774                                 case Mode.R4_I2: ig.Emit (OpCodes.Conv_I2); break;
1775                                 case Mode.R4_U2: ig.Emit (OpCodes.Conv_U2); break;
1776                                 case Mode.R4_I4: ig.Emit (OpCodes.Conv_I4); break;
1777                                 case Mode.R4_U4: ig.Emit (OpCodes.Conv_U4); break;
1778                                 case Mode.R4_I8: ig.Emit (OpCodes.Conv_I8); break;
1779                                 case Mode.R4_U8: ig.Emit (OpCodes.Conv_U8); break;
1780                                 case Mode.R4_CH: ig.Emit (OpCodes.Conv_U2); break;
1781
1782                                 case Mode.R8_I1: ig.Emit (OpCodes.Conv_I1); break;
1783                                 case Mode.R8_U1: ig.Emit (OpCodes.Conv_U1); break;
1784                                 case Mode.R8_I2: ig.Emit (OpCodes.Conv_I2); break;
1785                                 case Mode.R8_U2: ig.Emit (OpCodes.Conv_U2); break;
1786                                 case Mode.R8_I4: ig.Emit (OpCodes.Conv_I4); break;
1787                                 case Mode.R8_U4: ig.Emit (OpCodes.Conv_U4); break;
1788                                 case Mode.R8_I8: ig.Emit (OpCodes.Conv_I8); break;
1789                                 case Mode.R8_U8: ig.Emit (OpCodes.Conv_U8); break;
1790                                 case Mode.R8_CH: ig.Emit (OpCodes.Conv_U2); break;
1791                                 case Mode.R8_R4: ig.Emit (OpCodes.Conv_R4); break;
1792                                 }
1793                         }
1794                 }
1795         }
1796         
1797         public class OpcodeCast : EmptyCast {
1798                 OpCode op, op2;
1799                 bool second_valid;
1800                 
1801                 public OpcodeCast (Expression child, Type return_type, OpCode op)
1802                         : base (child, return_type)
1803                         
1804                 {
1805                         this.op = op;
1806                         second_valid = false;
1807                 }
1808
1809                 public OpcodeCast (Expression child, Type return_type, OpCode op, OpCode op2)
1810                         : base (child, return_type)
1811                         
1812                 {
1813                         this.op = op;
1814                         this.op2 = op2;
1815                         second_valid = true;
1816                 }
1817
1818                 public override Expression DoResolve (EmitContext ec)
1819                 {
1820                         // This should never be invoked, we are born in fully
1821                         // initialized state.
1822
1823                         return this;
1824                 }
1825
1826                 public override void Emit (EmitContext ec)
1827                 {
1828                         base.Emit (ec);
1829                         ec.ig.Emit (op);
1830
1831                         if (second_valid)
1832                                 ec.ig.Emit (op2);
1833                 }                       
1834         }
1835
1836         /// <summary>
1837         ///   This kind of cast is used to encapsulate a child and cast it
1838         ///   to the class requested
1839         /// </summary>
1840         public class ClassCast : EmptyCast {
1841                 public ClassCast (Expression child, Type return_type)
1842                         : base (child, return_type)
1843                         
1844                 {
1845                 }
1846
1847                 public override Expression DoResolve (EmitContext ec)
1848                 {
1849                         // This should never be invoked, we are born in fully
1850                         // initialized state.
1851
1852                         return this;
1853                 }
1854
1855                 public override void Emit (EmitContext ec)
1856                 {
1857                         base.Emit (ec);
1858
1859                         ec.ig.Emit (OpCodes.Castclass, type);
1860                 }                       
1861                 
1862         }
1863         
1864         /// <summary>
1865         ///   SimpleName expressions are initially formed of a single
1866         ///   word and it only happens at the beginning of the expression.
1867         /// </summary>
1868         ///
1869         /// <remarks>
1870         ///   The expression will try to be bound to a Field, a Method
1871         ///   group or a Property.  If those fail we pass the name to our
1872         ///   caller and the SimpleName is compounded to perform a type
1873         ///   lookup.  The idea behind this process is that we want to avoid
1874         ///   creating a namespace map from the assemblies, as that requires
1875         ///   the GetExportedTypes function to be called and a hashtable to
1876         ///   be constructed which reduces startup time.  If later we find
1877         ///   that this is slower, we should create a `NamespaceExpr' expression
1878         ///   that fully participates in the resolution process. 
1879         ///   
1880         ///   For example `System.Console.WriteLine' is decomposed into
1881         ///   MemberAccess (MemberAccess (SimpleName ("System"), "Console"), "WriteLine")
1882         ///   
1883         ///   The first SimpleName wont produce a match on its own, so it will
1884         ///   be turned into:
1885         ///   MemberAccess (SimpleName ("System.Console"), "WriteLine").
1886         ///   
1887         ///   System.Console will produce a TypeExpr match.
1888         ///   
1889         ///   The downside of this is that we might be hitting `LookupType' too many
1890         ///   times with this scheme.
1891         /// </remarks>
1892         public class SimpleName : Expression {
1893                 public string Name;
1894                 public int NumTypeParameters;
1895
1896                 //
1897                 // If true, then we are a simple name, not composed with a ".
1898                 //
1899                 bool is_base;
1900
1901                 public SimpleName (string a, string b, Location l)
1902                 {
1903                         Name = String.Concat (a, ".", b);
1904                         loc = l;
1905                         is_base = false;
1906                 }
1907                 
1908                 public SimpleName (string name, Location l)
1909                 {
1910                         Name = name;
1911                         loc = l;
1912                         is_base = true;
1913                 }
1914
1915                 public SimpleName (string name, int num_type_params, Location l)
1916                 {
1917                         Name = name;
1918                         NumTypeParameters = num_type_params;
1919                         loc = l;
1920                         is_base = true;
1921                 }
1922
1923                 public static void Error_ObjectRefRequired (EmitContext ec, Location l, string name)
1924                 {
1925                         if (ec.IsFieldInitializer)
1926                                 Report.Error (
1927                                         236, l,
1928                                         "A field initializer cannot reference the non-static field, " +
1929                                         "method or property `"+name+"'");
1930                         else
1931                                 Report.Error (
1932                                         120, l,
1933                                         "An object reference is required " +
1934                                         "for the non-static field `"+name+"'");
1935                 }
1936                 
1937                 //
1938                 // Checks whether we are trying to access an instance
1939                 // property, method or field from a static body.
1940                 //
1941                 Expression MemberStaticCheck (EmitContext ec, Expression e)
1942                 {
1943                         if (e is IMemberExpr){
1944                                 IMemberExpr member = (IMemberExpr) e;
1945                                 
1946                                 if (!member.IsStatic){
1947                                         Error_ObjectRefRequired (ec, loc, Name);
1948                                         return null;
1949                                 }
1950                         }
1951
1952                         return e;
1953                 }
1954                 
1955                 public override Expression DoResolve (EmitContext ec)
1956                 {
1957                         return SimpleNameResolve (ec, null, false);
1958                 }
1959
1960                 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
1961                 {
1962                         return SimpleNameResolve (ec, right_side, false);
1963                 }
1964                 
1965
1966                 public Expression DoResolveAllowStatic (EmitContext ec)
1967                 {
1968                         return SimpleNameResolve (ec, null, true);
1969                 }
1970
1971                 public override Expression ResolveAsTypeStep (EmitContext ec)
1972                 {
1973                         DeclSpace ds = ec.DeclSpace;
1974                         NamespaceEntry ns = ds.NamespaceEntry;
1975                         Type t;
1976                         string alias_value;
1977
1978                         //
1979                         // Since we are cheating: we only do the Alias lookup for
1980                         // namespaces if the name does not include any dots in it
1981                         //
1982                         if (ns != null && is_base)
1983                                 alias_value = ns.LookupAlias (Name);
1984                         else
1985                                 alias_value = null;
1986
1987                         if (ec.ResolvingTypeTree){
1988                                 int errors = Report.Errors;
1989                                 Type dt = ds.FindType (loc, Name, NumTypeParameters);
1990                                 
1991                                 if (Report.Errors != errors)
1992                                         return null;
1993                                 
1994                                 if (dt != null)
1995                                         return new TypeExpression (dt, loc);
1996
1997                                 if (alias_value != null){
1998                                         if ((t = RootContext.LookupType (ds, alias_value, true, NumTypeParameters, loc)) != null)
1999                                                 return new TypeExpression (t, loc);
2000                                 }
2001                         }
2002
2003                         //
2004                         // First, the using aliases
2005                         //
2006                         if (alias_value != null){
2007                                 if ((t = RootContext.LookupType (ds, alias_value, true, loc)) != null)
2008                                         return new TypeExpression (t, loc);
2009                                 
2010                                 // we have alias value, but it isn't Type, so try if it's namespace
2011                                 return new SimpleName (alias_value, loc);
2012                         }
2013
2014                         TypeParameterExpr generic_type = ds.LookupGeneric (Name, loc);
2015                         if (generic_type != null)
2016                                 return generic_type.ResolveAsTypeTerminal (ec);
2017
2018                         //
2019                         // Stage 2: Lookup up if we are an alias to a type
2020                         // or a namespace.
2021                         //
2022
2023                         if ((t = RootContext.LookupType (ds, Name, true, NumTypeParameters, loc)) != null)
2024                                 return new TypeExpression (t, loc);
2025                                 
2026                         // No match, maybe our parent can compose us
2027                         // into something meaningful.
2028                         return this;
2029                 }
2030
2031                 /// <remarks>
2032                 ///   7.5.2: Simple Names. 
2033                 ///
2034                 ///   Local Variables and Parameters are handled at
2035                 ///   parse time, so they never occur as SimpleNames.
2036                 ///
2037                 ///   The `allow_static' flag is used by MemberAccess only
2038                 ///   and it is used to inform us that it is ok for us to 
2039                 ///   avoid the static check, because MemberAccess might end
2040                 ///   up resolving the Name as a Type name and the access as
2041                 ///   a static type access.
2042                 ///
2043                 ///   ie: Type Type; .... { Type.GetType (""); }
2044                 ///
2045                 ///   Type is both an instance variable and a Type;  Type.GetType
2046                 ///   is the static method not an instance method of type.
2047                 /// </remarks>
2048                 Expression SimpleNameResolve (EmitContext ec, Expression right_side, bool allow_static)
2049                 {
2050                         Expression e = null;
2051
2052                         //
2053                         // Stage 1: Performed by the parser (binding to locals or parameters).
2054                         //
2055                         Block current_block = ec.CurrentBlock;
2056                         if (current_block != null){
2057                                 LocalInfo vi = current_block.GetLocalInfo (Name);
2058                                 if (vi != null){
2059                                         Expression var;
2060                                         
2061                                         var = new LocalVariableReference (ec.CurrentBlock, Name, loc);
2062                                         
2063                                         if (right_side != null)
2064                                                 return var.ResolveLValue (ec, right_side);
2065                                         else
2066                                                 return var.Resolve (ec);
2067                                 }
2068
2069                                 int idx = -1;
2070                                 Parameter par = null;
2071                                 Parameters pars = current_block.Parameters;
2072                                 if (pars != null)
2073                                         par = pars.GetParameterByName (Name, out idx);
2074
2075                                 if (par != null) {
2076                                         ParameterReference param;
2077                                         
2078                                         param = new ParameterReference (pars, current_block, idx, Name, loc);
2079
2080                                         if (right_side != null)
2081                                                 return param.ResolveLValue (ec, right_side);
2082                                         else
2083                                                 return param.Resolve (ec);
2084                                 }
2085                         }
2086                         
2087                         //
2088                         // Stage 2: Lookup members 
2089                         //
2090
2091                         DeclSpace lookup_ds = ec.DeclSpace;
2092                         do {
2093                                 if (lookup_ds.TypeBuilder == null)
2094                                         break;
2095
2096                                 e = MemberLookup (ec, lookup_ds.TypeBuilder, Name, loc);
2097                                 if (e != null)
2098                                         break;
2099
2100                                 lookup_ds =lookup_ds.Parent;
2101                         } while (lookup_ds != null);
2102
2103                         if (e == null && ec.ContainerType != null)
2104                                 e = MemberLookup (ec, ec.ContainerType, Name, loc);
2105
2106                         if (e == null) {
2107                                 //
2108                                 // Since we are cheating (is_base is our hint
2109                                 // that we are the beginning of the name): we
2110                                 // only do the Alias lookup for namespaces if
2111                                 // the name does not include any dots in it
2112                                 //
2113                                 NamespaceEntry ns = ec.DeclSpace.NamespaceEntry;
2114                                 if (is_base && ns != null){
2115                                         string alias_value = ns.LookupAlias (Name);
2116                                         if (alias_value != null){
2117                                                 Name = alias_value;
2118                                                 Type t;
2119
2120                                                 if ((t = TypeManager.LookupType (Name)) != null)
2121                                                         return new TypeExpression (t, loc);
2122                                         
2123                                                 // No match, maybe our parent can compose us
2124                                                 // into something meaningful.
2125                                                 return this;
2126                                         }
2127                                 }
2128
2129                                 return ResolveAsTypeStep (ec);
2130                         }
2131
2132                         if (e is TypeExpr)
2133                                 return e;
2134
2135                         if (e is IMemberExpr) {
2136                                 e = MemberAccess.ResolveMemberAccess (ec, e, null, loc, this);
2137                                 if (e == null)
2138                                         return null;
2139
2140                                 IMemberExpr me = e as IMemberExpr;
2141                                 if (me == null)
2142                                         return e;
2143
2144                                 // This fails if ResolveMemberAccess() was unable to decide whether
2145                                 // it's a field or a type of the same name.
2146                                 if (!me.IsStatic && (me.InstanceExpression == null))
2147                                         return e;
2148
2149                                 if (!me.IsStatic &&
2150                                     TypeManager.IsNestedChildOf (me.InstanceExpression.Type, me.DeclaringType) &&
2151                                     !me.InstanceExpression.Type.IsSubclassOf (me.DeclaringType)) {
2152                                         Error (38, "Cannot access nonstatic member `" + me.Name + "' of " +
2153                                                "outer type `" + me.DeclaringType + "' via nested type `" +
2154                                                me.InstanceExpression.Type + "'");
2155                                         return null;
2156                                 }
2157
2158                                 if (right_side != null)
2159                                         e = e.DoResolveLValue (ec, right_side);
2160                                 else
2161                                         e = e.DoResolve (ec);
2162
2163                                 return e;                               
2164                         }
2165
2166                         if (ec.IsStatic || ec.IsFieldInitializer){
2167                                 if (allow_static)
2168                                         return e;
2169
2170                                 return MemberStaticCheck (ec, e);
2171                         } else
2172                                 return e;
2173                 }
2174                 
2175                 public override void Emit (EmitContext ec)
2176                 {
2177                         //
2178                         // If this is ever reached, then we failed to
2179                         // find the name as a namespace
2180                         //
2181
2182                         Error (103, "The name `" + Name +
2183                                "' does not exist in the class `" +
2184                                ec.DeclSpace.Name + "'");
2185                 }
2186
2187                 public override string ToString ()
2188                 {
2189                         return Name;
2190                 }
2191         }
2192         
2193         /// <summary>
2194         ///   Fully resolved expression that evaluates to a type
2195         /// </summary>
2196         public abstract class TypeExpr : Expression {
2197                 override public Expression ResolveAsTypeStep (EmitContext ec)
2198                 {
2199                         TypeExpr t = DoResolveAsTypeStep (ec);
2200                         if (t == null)
2201                                 return null;
2202
2203                         eclass = ExprClass.Type;
2204                         return t;
2205                 }
2206
2207                 override public Expression DoResolve (EmitContext ec)
2208                 {
2209                         return ResolveAsTypeTerminal (ec);
2210                 }
2211
2212                 override public void Emit (EmitContext ec)
2213                 {
2214                         throw new Exception ("Should never be called");
2215                 }
2216
2217                 public virtual bool CheckAccessLevel (DeclSpace ds)
2218                 {
2219                         return ds.CheckAccessLevel (Type);
2220                 }
2221
2222                 public virtual bool AsAccessible (DeclSpace ds, int flags)
2223                 {
2224                         return ds.AsAccessible (Type, flags);
2225                 }
2226
2227                 public virtual bool IsClass {
2228                         get { return Type.IsClass; }
2229                 }
2230
2231                 public virtual bool IsValueType {
2232                         get { return Type.IsValueType; }
2233                 }
2234
2235                 public virtual bool IsInterface {
2236                         get { return Type.IsInterface; }
2237                 }
2238
2239                 public virtual bool IsSealed {
2240                         get { return Type.IsSealed; }
2241                 }
2242
2243                 public virtual bool CanInheritFrom ()
2244                 {
2245                         if (Type == TypeManager.enum_type ||
2246                             (Type == TypeManager.value_type && RootContext.StdLib) ||
2247                             Type == TypeManager.delegate_type ||
2248                             Type == TypeManager.array_type)
2249                                 return false;
2250
2251                         return true;
2252                 }
2253
2254                 public virtual bool IsAttribute {
2255                         get {
2256                                 return Type == TypeManager.attribute_type ||
2257                                         Type.IsSubclassOf (TypeManager.attribute_type);
2258                         }
2259                 }
2260
2261                 public virtual TypeExpr[] GetInterfaces ()
2262                 {
2263                         return TypeManager.GetInterfaces (Type);
2264                 }
2265
2266                 public abstract TypeExpr DoResolveAsTypeStep (EmitContext ec);
2267
2268                 public virtual Type ResolveType (EmitContext ec)
2269                 {
2270                         TypeExpr t = ResolveAsTypeTerminal (ec);
2271                         if (t == null)
2272                                 return null;
2273
2274                         return t.Type;
2275                 }
2276
2277                 public abstract string Name {
2278                         get;
2279                 }
2280
2281                 public override bool Equals (object obj)
2282                 {
2283                         TypeExpr tobj = obj as TypeExpr;
2284                         if (tobj == null)
2285                                 return false;
2286
2287                         return Type == tobj.Type;
2288                 }
2289
2290                 public override string ToString ()
2291                 {
2292                         return Name;
2293                 }
2294         }
2295
2296         public class TypeExpression : TypeExpr {
2297                 public TypeExpression (Type t, Location l)
2298                 {
2299                         Type = t;
2300                         eclass = ExprClass.Type;
2301                         loc = l;
2302                 }
2303
2304                 public override TypeExpr DoResolveAsTypeStep (EmitContext ec)
2305                 {
2306                         return this;
2307                 }
2308
2309                 public override string Name {
2310                         get {
2311                                 return Type.ToString ();
2312                         }
2313                 }
2314         }
2315
2316         /// <summary>
2317         ///   Used to create types from a fully qualified name.  These are just used
2318         ///   by the parser to setup the core types.  A TypeLookupExpression is always
2319         ///   classified as a type.
2320         /// </summary>
2321         public class TypeLookupExpression : TypeExpr {
2322                 string name;
2323                 
2324                 public TypeLookupExpression (string name)
2325                 {
2326                         this.name = name;
2327                 }
2328
2329                 public override TypeExpr DoResolveAsTypeStep (EmitContext ec)
2330                 {
2331                         if (type == null)
2332                                 type = RootContext.LookupType (ec.DeclSpace, name, false, Location.Null);
2333                         return this;
2334                 }
2335
2336                 public override string Name {
2337                         get {
2338                                 return name;
2339                         }
2340                 }
2341         }
2342
2343         /// <summary>
2344         ///   MethodGroup Expression.
2345         ///  
2346         ///   This is a fully resolved expression that evaluates to a type
2347         /// </summary>
2348         public class MethodGroupExpr : Expression, IMemberExpr {
2349                 public MethodBase [] Methods;
2350                 Expression instance_expression = null;
2351                 bool is_explicit_impl = false;
2352                 
2353                 public MethodGroupExpr (MemberInfo [] mi, Location l)
2354                 {
2355                         Methods = new MethodBase [mi.Length];
2356                         mi.CopyTo (Methods, 0);
2357                         eclass = ExprClass.MethodGroup;
2358                         type = TypeManager.object_type;
2359                         loc = l;
2360                 }
2361
2362                 public MethodGroupExpr (ArrayList list, Location l)
2363                 {
2364                         Methods = new MethodBase [list.Count];
2365
2366                         try {
2367                                 list.CopyTo (Methods, 0);
2368                         } catch {
2369                                 foreach (MemberInfo m in list){
2370                                         if (!(m is MethodBase)){
2371                                                 Console.WriteLine ("Name " + m.Name);
2372                                                 Console.WriteLine ("Found a: " + m.GetType ().FullName);
2373                                         }
2374                                 }
2375                                 throw;
2376                         }
2377
2378                         loc = l;
2379                         eclass = ExprClass.MethodGroup;
2380                         type = TypeManager.object_type;
2381                 }
2382
2383                 public Type DeclaringType {
2384                         get {
2385                                 //
2386                                 // We assume that the top-level type is in the end
2387                                 //
2388                                 return Methods [Methods.Length - 1].DeclaringType;
2389                                 //return Methods [0].DeclaringType;
2390                         }
2391                 }
2392                 
2393                 //
2394                 // `A method group may have associated an instance expression' 
2395                 // 
2396                 public Expression InstanceExpression {
2397                         get {
2398                                 return instance_expression;
2399                         }
2400
2401                         set {
2402                                 instance_expression = value;
2403                         }
2404                 }
2405
2406                 public bool IsExplicitImpl {
2407                         get {
2408                                 return is_explicit_impl;
2409                         }
2410
2411                         set {
2412                                 is_explicit_impl = value;
2413                         }
2414                 }
2415
2416                 public string Name {
2417                         get {
2418                                 //return Methods [0].Name;
2419                                 return Methods [Methods.Length - 1].Name;
2420                         }
2421                 }
2422
2423                 public bool IsInstance {
2424                         get {
2425                                 foreach (MethodBase mb in Methods)
2426                                         if (!mb.IsStatic)
2427                                                 return true;
2428
2429                                 return false;
2430                         }
2431                 }
2432
2433                 public bool IsStatic {
2434                         get {
2435                                 foreach (MethodBase mb in Methods)
2436                                         if (mb.IsStatic)
2437                                                 return true;
2438
2439                                 return false;
2440                         }
2441                 }
2442                 
2443                 override public Expression DoResolve (EmitContext ec)
2444                 {
2445                         if (!IsInstance)
2446                                 instance_expression = null;
2447
2448                         if (instance_expression != null) {
2449                                 instance_expression = instance_expression.DoResolve (ec);
2450                                 if (instance_expression == null)
2451                                         return null;
2452                         }
2453
2454                         return this;
2455                 }
2456
2457                 public void ReportUsageError ()
2458                 {
2459                         Report.Error (654, loc, "Method `" + DeclaringType + "." +
2460                                       Name + "()' is referenced without parentheses");
2461                 }
2462
2463                 override public void Emit (EmitContext ec)
2464                 {
2465                         ReportUsageError ();
2466                 }
2467
2468                 bool RemoveMethods (bool keep_static)
2469                 {
2470                         ArrayList smethods = new ArrayList ();
2471
2472                         foreach (MethodBase mb in Methods){
2473                                 if (mb.IsStatic == keep_static)
2474                                         smethods.Add (mb);
2475                         }
2476
2477                         if (smethods.Count == 0)
2478                                 return false;
2479
2480                         Methods = new MethodBase [smethods.Count];
2481                         smethods.CopyTo (Methods, 0);
2482
2483                         return true;
2484                 }
2485                 
2486                 /// <summary>
2487                 ///   Removes any instance methods from the MethodGroup, returns
2488                 ///   false if the resulting set is empty.
2489                 /// </summary>
2490                 public bool RemoveInstanceMethods ()
2491                 {
2492                         return RemoveMethods (true);
2493                 }
2494
2495                 /// <summary>
2496                 ///   Removes any static methods from the MethodGroup, returns
2497                 ///   false if the resulting set is empty.
2498                 /// </summary>
2499                 public bool RemoveStaticMethods ()
2500                 {
2501                         return RemoveMethods (false);
2502                 }
2503         }
2504
2505         /// <summary>
2506         ///   Fully resolved expression that evaluates to a Field
2507         /// </summary>
2508         public class FieldExpr : Expression, IAssignMethod, IMemoryLocation, IMemberExpr, IVariable {
2509                 public readonly FieldInfo FieldInfo;
2510                 Expression instance_expr;
2511                 VariableInfo variable_info;
2512                 
2513                 public FieldExpr (FieldInfo fi, Location l)
2514                 {
2515                         FieldInfo = fi;
2516                         eclass = ExprClass.Variable;
2517                         type = TypeManager.TypeToCoreType (fi.FieldType);
2518                         loc = l;
2519                 }
2520
2521                 public string Name {
2522                         get {
2523                                 return FieldInfo.Name;
2524                         }
2525                 }
2526
2527                 public bool IsInstance {
2528                         get {
2529                                 return !FieldInfo.IsStatic;
2530                         }
2531                 }
2532
2533                 public bool IsStatic {
2534                         get {
2535                                 return FieldInfo.IsStatic;
2536                         }
2537                 }
2538
2539                 public Type DeclaringType {
2540                         get {
2541                                 return FieldInfo.DeclaringType;
2542                         }
2543                 }
2544
2545                 public Expression InstanceExpression {
2546                         get {
2547                                 return instance_expr;
2548                         }
2549
2550                         set {
2551                                 instance_expr = value;
2552                         }
2553                 }
2554
2555                 public VariableInfo VariableInfo {
2556                         get {
2557                                 return variable_info;
2558                         }
2559                 }
2560
2561                 override public Expression DoResolve (EmitContext ec)
2562                 {
2563                         if (!FieldInfo.IsStatic){
2564                                 if (instance_expr == null){
2565                                         //
2566                                         // This can happen when referencing an instance field using
2567                                         // a fully qualified type expression: TypeName.InstanceField = xxx
2568                                         // 
2569                                         SimpleName.Error_ObjectRefRequired (ec, loc, FieldInfo.Name);
2570                                         return null;
2571                                 }
2572
2573                                 // Resolve the field's instance expression while flow analysis is turned
2574                                 // off: when accessing a field "a.b", we must check whether the field
2575                                 // "a.b" is initialized, not whether the whole struct "a" is initialized.
2576                                 instance_expr = instance_expr.Resolve (ec, ResolveFlags.VariableOrValue |
2577                                                                        ResolveFlags.DisableFlowAnalysis);
2578                                 if (instance_expr == null)
2579                                         return null;
2580                         }
2581
2582                         // If the instance expression is a local variable or parameter.
2583                         IVariable var = instance_expr as IVariable;
2584                         if ((var == null) || (var.VariableInfo == null))
2585                                 return this;
2586
2587                         VariableInfo vi = var.VariableInfo;
2588                         if (!vi.IsFieldAssigned (ec, FieldInfo.Name, loc))
2589                                 return null;
2590
2591                         variable_info = vi.GetSubStruct (FieldInfo.Name);
2592                         return this;
2593                 }
2594
2595                 void Report_AssignToReadonly (bool is_instance)
2596                 {
2597                         string msg;
2598                         
2599                         if (is_instance)
2600                                 msg = "Readonly field can not be assigned outside " +
2601                                 "of constructor or variable initializer";
2602                         else
2603                                 msg = "A static readonly field can only be assigned in " +
2604                                 "a static constructor";
2605
2606                         Report.Error (is_instance ? 191 : 198, loc, msg);
2607                 }
2608                 
2609                 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
2610                 {
2611                         IVariable var = instance_expr as IVariable;
2612                         if ((var != null) && (var.VariableInfo != null))
2613                                 var.VariableInfo.SetFieldAssigned (ec, FieldInfo.Name);
2614
2615                         Expression e = DoResolve (ec);
2616
2617                         if (e == null)
2618                                 return null;
2619
2620                         if (!FieldInfo.IsStatic && (instance_expr.Type.IsValueType && !(instance_expr is IMemoryLocation))) {
2621                                 // FIXME: Provide better error reporting.
2622                                 Error (1612, "Cannot modify expression because it is not a variable.");
2623                                 return null;
2624                         }
2625
2626                         if (!FieldInfo.IsInitOnly)
2627                                 return this;
2628
2629                         FieldBase fb = TypeManager.GetField (FieldInfo);
2630                         if (fb != null)
2631                                 fb.SetAssigned ();
2632
2633                         //
2634                         // InitOnly fields can only be assigned in constructors
2635                         //
2636
2637                         if (ec.IsConstructor){
2638                                 if (IsStatic && !ec.IsStatic)
2639                                         Report_AssignToReadonly (false);
2640
2641                                 Type ctype;
2642                                 if (ec.TypeContainer.CurrentType != null)
2643                                         ctype = ec.TypeContainer.CurrentType.ResolveType (ec);
2644                                 else
2645                                         ctype = ec.ContainerType;
2646
2647                                 if (TypeManager.IsEqual (ctype, FieldInfo.DeclaringType))
2648                                         return this;
2649                         }
2650
2651                         Report_AssignToReadonly (true);
2652                         
2653                         return null;
2654                 }
2655
2656                 public bool VerifyFixed (bool is_expression)
2657                 {
2658                         IVariable variable = instance_expr as IVariable;
2659                         if ((variable == null) || !variable.VerifyFixed (true))
2660                                 return false;
2661
2662                         return true;
2663                 }
2664
2665                 override public void Emit (EmitContext ec)
2666                 {
2667                         ILGenerator ig = ec.ig;
2668                         bool is_volatile = false;
2669
2670                         if (FieldInfo is FieldBuilder){
2671                                 FieldBase f = TypeManager.GetField (FieldInfo);
2672                                 if (f != null){
2673                                         if ((f.ModFlags & Modifiers.VOLATILE) != 0)
2674                                                 is_volatile = true;
2675                                         
2676                                         f.status |= Field.Status.USED;
2677                                 }
2678                         } 
2679                         
2680                         if (FieldInfo.IsStatic){
2681                                 if (is_volatile)
2682                                         ig.Emit (OpCodes.Volatile);
2683                                 
2684                                 ig.Emit (OpCodes.Ldsfld, FieldInfo);
2685                                 return;
2686                         }
2687                         
2688                         if (instance_expr.Type.IsValueType){
2689                                 IMemoryLocation ml;
2690                                 LocalTemporary tempo = null;
2691                                 
2692                                 if (!(instance_expr is IMemoryLocation)){
2693                                         tempo = new LocalTemporary (ec, instance_expr.Type);
2694                                         
2695                                         if (ec.RemapToProxy)
2696                                                 ec.EmitThis ();
2697                         
2698                                         InstanceExpression.Emit (ec);
2699                                         tempo.Store (ec);
2700                                         ml = tempo;
2701                                 } else
2702                                         ml = (IMemoryLocation) instance_expr;
2703                                 
2704                                 ml.AddressOf (ec, AddressOp.Load);
2705                         } else {
2706                                 if (ec.RemapToProxy)
2707                                         ec.EmitThis ();
2708                                 else
2709                                         instance_expr.Emit (ec);
2710                         }
2711                         if (is_volatile)
2712                                 ig.Emit (OpCodes.Volatile);
2713                         
2714                         ig.Emit (OpCodes.Ldfld, FieldInfo);
2715                 }
2716
2717                 public void EmitAssign (EmitContext ec, Expression source)
2718                 {
2719                         FieldAttributes fa = FieldInfo.Attributes;
2720                         bool is_static = (fa & FieldAttributes.Static) != 0;
2721                         bool is_readonly = (fa & FieldAttributes.InitOnly) != 0;
2722                         ILGenerator ig = ec.ig;
2723
2724                         if (is_readonly && !ec.IsConstructor){
2725                                 Report_AssignToReadonly (!is_static);
2726                                 return;
2727                         }
2728
2729                         if (!is_static){
2730                                 Expression instance = instance_expr;
2731
2732                                 if (instance.Type.IsValueType){
2733                                         IMemoryLocation ml = (IMemoryLocation) instance;
2734
2735                                         ml.AddressOf (ec, AddressOp.Store);
2736                                 } else {
2737                                         if (ec.RemapToProxy)
2738                                                 ec.EmitThis ();
2739                                         else
2740                                                 instance.Emit (ec);
2741                                 }
2742                         }
2743
2744                         source.Emit (ec);
2745
2746                         if (FieldInfo is FieldBuilder){
2747                                 FieldBase f = TypeManager.GetField (FieldInfo);
2748                                 if (f != null){
2749                                         if ((f.ModFlags & Modifiers.VOLATILE) != 0)
2750                                                 ig.Emit (OpCodes.Volatile);
2751                                         
2752                                         f.status |= Field.Status.ASSIGNED;
2753                                 }
2754                         } 
2755
2756                         if (is_static)
2757                                 ig.Emit (OpCodes.Stsfld, FieldInfo);
2758                         else 
2759                                 ig.Emit (OpCodes.Stfld, FieldInfo);
2760                 }
2761                 
2762                 public void AddressOf (EmitContext ec, AddressOp mode)
2763                 {
2764                         ILGenerator ig = ec.ig;
2765                         
2766                         if (FieldInfo is FieldBuilder){
2767                                 FieldBase f = TypeManager.GetField (FieldInfo);
2768                                 if (f != null){
2769                                         if ((f.ModFlags & Modifiers.VOLATILE) != 0){
2770                                                 Error (676, "volatile variable: can not take its address, or pass as ref/out parameter");
2771                                                 return;
2772                                         }
2773                                         
2774                                         if ((mode & AddressOp.Store) != 0)
2775                                                 f.status |= Field.Status.ASSIGNED;
2776                                         if ((mode & AddressOp.Load) != 0)
2777                                                 f.status |= Field.Status.USED;
2778                                 }
2779                         } 
2780
2781                         //
2782                         // Handle initonly fields specially: make a copy and then
2783                         // get the address of the copy.
2784                         //
2785                         bool need_copy;
2786                         if (FieldInfo.IsInitOnly){
2787                                 need_copy = true;
2788                                 if (ec.IsConstructor){
2789                                         if (FieldInfo.IsStatic){
2790                                                 if (ec.IsStatic)
2791                                                         need_copy = false;
2792                                         } else
2793                                                 need_copy = false;
2794                                 }
2795                         } else
2796                                 need_copy = false;
2797                         
2798                         if (need_copy){
2799                                 LocalBuilder local;
2800                                 Emit (ec);
2801                                 local = ig.DeclareLocal (type);
2802                                 ig.Emit (OpCodes.Stloc, local);
2803                                 ig.Emit (OpCodes.Ldloca, local);
2804                                 return;
2805                         }
2806
2807
2808                         if (FieldInfo.IsStatic){
2809                                 ig.Emit (OpCodes.Ldsflda, FieldInfo);
2810                         } else {
2811                                 //
2812                                 // In the case of `This', we call the AddressOf method, which will
2813                                 // only load the pointer, and not perform an Ldobj immediately after
2814                                 // the value has been loaded into the stack.
2815                                 //
2816                                 if (instance_expr is This)
2817                                         ((This)instance_expr).AddressOf (ec, AddressOp.LoadStore);
2818                                 else if (instance_expr.Type.IsValueType && instance_expr is IMemoryLocation){
2819                                         IMemoryLocation ml = (IMemoryLocation) instance_expr;
2820
2821                                         ml.AddressOf (ec, AddressOp.LoadStore);
2822                                 } else
2823                                         instance_expr.Emit (ec);
2824                                 ig.Emit (OpCodes.Ldflda, FieldInfo);
2825                         }
2826                 }
2827         }
2828
2829         //
2830         // A FieldExpr whose address can not be taken
2831         //
2832         public class FieldExprNoAddress : FieldExpr, IMemoryLocation {
2833                 public FieldExprNoAddress (FieldInfo fi, Location loc) : base (fi, loc)
2834                 {
2835                 }
2836                 
2837                 public new void AddressOf (EmitContext ec, AddressOp mode)
2838                 {
2839                         Report.Error (-215, "Report this: Taking the address of a remapped parameter not supported");
2840                 }
2841         }
2842         
2843         /// <summary>
2844         ///   Expression that evaluates to a Property.  The Assign class
2845         ///   might set the `Value' expression if we are in an assignment.
2846         ///
2847         ///   This is not an LValue because we need to re-write the expression, we
2848         ///   can not take data from the stack and store it.  
2849         /// </summary>
2850         public class PropertyExpr : ExpressionStatement, IAssignMethod, IMemberExpr {
2851                 public readonly PropertyInfo PropertyInfo;
2852
2853                 //
2854                 // This is set externally by the  `BaseAccess' class
2855                 //
2856                 public bool IsBase;
2857                 MethodInfo getter, setter;
2858                 bool is_static;
2859                 bool must_do_cs1540_check;
2860                 
2861                 Expression instance_expr;
2862
2863                 public PropertyExpr (EmitContext ec, PropertyInfo pi, Location l)
2864                 {
2865                         PropertyInfo = pi;
2866                         eclass = ExprClass.PropertyAccess;
2867                         is_static = false;
2868                         loc = l;
2869
2870                         type = TypeManager.TypeToCoreType (pi.PropertyType);
2871
2872                         ResolveAccessors (ec);
2873                 }
2874
2875                 public string Name {
2876                         get {
2877                                 return PropertyInfo.Name;
2878                         }
2879                 }
2880
2881                 public bool IsInstance {
2882                         get {
2883                                 return !is_static;
2884                         }
2885                 }
2886
2887                 public bool IsStatic {
2888                         get {
2889                                 return is_static;
2890                         }
2891                 }
2892                 
2893                 public Type DeclaringType {
2894                         get {
2895                                 return PropertyInfo.DeclaringType;
2896                         }
2897                 }
2898
2899                 //
2900                 // The instance expression associated with this expression
2901                 //
2902                 public Expression InstanceExpression {
2903                         set {
2904                                 instance_expr = value;
2905                         }
2906
2907                         get {
2908                                 return instance_expr;
2909                         }
2910                 }
2911
2912                 public bool VerifyAssignable ()
2913                 {
2914                         if (setter == null) {
2915                                 Report.Error (200, loc, 
2916                                               "The property `" + PropertyInfo.Name +
2917                                               "' can not be assigned to, as it has not set accessor");
2918                                 return false;
2919                         }
2920
2921                         return true;
2922                 }
2923
2924                 MethodInfo GetAccessor (Type invocation_type, string accessor_name)
2925                 {
2926                         BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic |
2927                                 BindingFlags.Static | BindingFlags.Instance;
2928                         MemberInfo[] group;
2929
2930                         group = TypeManager.MemberLookup (
2931                                 invocation_type, invocation_type, PropertyInfo.DeclaringType,
2932                                 MemberTypes.Method, flags, accessor_name + "_" + PropertyInfo.Name);
2933
2934                         //
2935                         // The first method is the closest to us
2936                         //
2937                         if (group == null)
2938                                 return null;
2939
2940                         foreach (MethodInfo mi in group) {
2941                                 MethodAttributes ma = mi.Attributes & MethodAttributes.MemberAccessMask;
2942
2943                                 //
2944                                 // If only accessible to the current class or children
2945                                 //
2946                                 if (ma == MethodAttributes.Private) {
2947                                         Type declaring_type = mi.DeclaringType;
2948                                         
2949                                         if (invocation_type != declaring_type){
2950                                                 if (TypeManager.IsSubclassOrNestedChildOf (invocation_type, mi.DeclaringType))
2951                                                         return mi;
2952                                                 else
2953                                                         continue;
2954                                         } else
2955                                                 return mi;
2956                                 }
2957                                 //
2958                                 // FamAndAssem requires that we not only derivate, but we are on the
2959                                 // same assembly.  
2960                                 //
2961                                 if (ma == MethodAttributes.FamANDAssem){
2962                                         if (mi.DeclaringType.Assembly != invocation_type.Assembly)
2963                                                 continue;
2964                                         else
2965                                                 return mi;
2966                                 }
2967
2968                                 // Assembly and FamORAssem succeed if we're in the same assembly.
2969                                 if ((ma == MethodAttributes.Assembly) || (ma == MethodAttributes.FamORAssem)){
2970                                         if (mi.DeclaringType.Assembly == invocation_type.Assembly)
2971                                                 return mi;
2972                                 }
2973
2974                                 // We already know that we aren't in the same assembly.
2975                                 if (ma == MethodAttributes.Assembly)
2976                                         continue;
2977
2978                                 // Family and FamANDAssem require that we derive.
2979                                 if ((ma == MethodAttributes.Family) || (ma == MethodAttributes.FamANDAssem) || (ma == MethodAttributes.FamORAssem)){
2980                                         if (!TypeManager.IsSubclassOrNestedChildOf (invocation_type, mi.DeclaringType))
2981                                                 continue;
2982                                         else {
2983                                                 must_do_cs1540_check = true;
2984
2985                                                 return mi;
2986                                         }
2987                                 }
2988
2989                                 return mi;
2990                         }
2991
2992                         return null;
2993                 }
2994
2995                 //
2996                 // We also perform the permission checking here, as the PropertyInfo does not
2997                 // hold the information for the accessibility of its setter/getter
2998                 //
2999                 void ResolveAccessors (EmitContext ec)
3000                 {
3001                         getter = GetAccessor (ec.ContainerType, "get");
3002                         if ((getter != null) && getter.IsStatic)
3003                                 is_static = true;
3004
3005                         setter = GetAccessor (ec.ContainerType, "set");
3006                         if ((setter != null) && setter.IsStatic)
3007                                 is_static = true;
3008
3009                         if (setter == null && getter == null){
3010                                 Error (122, "`" + PropertyInfo.Name + "' " +
3011                                        "is inaccessible because of its protection level");
3012                                 
3013                         }
3014                 }
3015
3016                 bool InstanceResolve (EmitContext ec)
3017                 {
3018                         if ((instance_expr == null) && ec.IsStatic && !is_static) {
3019                                 SimpleName.Error_ObjectRefRequired (ec, loc, PropertyInfo.Name);
3020                                 return false;
3021                         }
3022
3023                         if (instance_expr != null) {
3024                                 instance_expr = instance_expr.DoResolve (ec);
3025                                 if (instance_expr == null)
3026                                         return false;
3027                         }
3028
3029                         if (must_do_cs1540_check && (instance_expr != null)) {
3030                                 if ((instance_expr.Type != ec.ContainerType) &&
3031                                     ec.ContainerType.IsSubclassOf (instance_expr.Type)) {
3032                                         Report.Error (1540, loc, "Cannot access protected member `" +
3033                                                       PropertyInfo.DeclaringType + "." + PropertyInfo.Name + 
3034                                                       "' via a qualifier of type `" +
3035                                                       TypeManager.CSharpName (instance_expr.Type) +
3036                                                       "'; the qualifier must be of type `" +
3037                                                       TypeManager.CSharpName (ec.ContainerType) +
3038                                                       "' (or derived from it)");
3039                                         return false;
3040                                 }
3041                         }
3042
3043                         return true;
3044                 }
3045                 
3046                 override public Expression DoResolve (EmitContext ec)
3047                 {
3048                         if (getter == null){
3049                                 //
3050                                 // The following condition happens if the PropertyExpr was
3051                                 // created, but is invalid (ie, the property is inaccessible),
3052                                 // and we did not want to embed the knowledge about this in
3053                                 // the caller routine.  This only avoids double error reporting.
3054                                 //
3055                                 if (setter == null)
3056                                         return null;
3057                                 
3058                                 Report.Error (154, loc, 
3059                                               "The property `" + PropertyInfo.Name +
3060                                               "' can not be used in " +
3061                                               "this context because it lacks a get accessor");
3062                                 return null;
3063                         } 
3064
3065                         if (!InstanceResolve (ec))
3066                                 return null;
3067
3068                         //
3069                         // Only base will allow this invocation to happen.
3070                         //
3071                         if (IsBase && getter.IsAbstract){
3072                                 Report.Error (205, loc, "Cannot call an abstract base property: " +
3073                                               PropertyInfo.DeclaringType + "." +PropertyInfo.Name);
3074                                 return null;
3075                         }
3076
3077                         return this;
3078                 }
3079
3080                 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
3081                 {
3082                         if (setter == null){
3083                                 //
3084                                 // The following condition happens if the PropertyExpr was
3085                                 // created, but is invalid (ie, the property is inaccessible),
3086                                 // and we did not want to embed the knowledge about this in
3087                                 // the caller routine.  This only avoids double error reporting.
3088                                 //
3089                                 if (getter == null)
3090                                         return null;
3091                                 
3092                                 Report.Error (154, loc, 
3093                                               "The property `" + PropertyInfo.Name +
3094                                               "' can not be used in " +
3095                                               "this context because it lacks a set accessor");
3096                                 return null;
3097                         }
3098
3099                         if (!InstanceResolve (ec))
3100                                 return null;
3101                         
3102                         //
3103                         // Only base will allow this invocation to happen.
3104                         //
3105                         if (IsBase && setter.IsAbstract){
3106                                 Report.Error (205, loc, "Cannot call an abstract base property: " +
3107                                               PropertyInfo.DeclaringType + "." +PropertyInfo.Name);
3108                                 return null;
3109                         }
3110                         return this;
3111                 }
3112
3113                 override public void Emit (EmitContext ec)
3114                 {
3115                         //
3116                         // Special case: length of single dimension array property is turned into ldlen
3117                         //
3118                         if ((getter == TypeManager.system_int_array_get_length) ||
3119                             (getter == TypeManager.int_array_get_length)){
3120                                 Type iet = instance_expr.Type;
3121
3122                                 //
3123                                 // System.Array.Length can be called, but the Type does not
3124                                 // support invoking GetArrayRank, so test for that case first
3125                                 //
3126                                 if (iet != TypeManager.array_type && (iet.GetArrayRank () == 1)){
3127                                         instance_expr.Emit (ec);
3128                                         ec.ig.Emit (OpCodes.Ldlen);
3129                                         ec.ig.Emit (OpCodes.Conv_I4);
3130                                         return;
3131                                 }
3132                         }
3133
3134                         Invocation.EmitCall (ec, IsBase, IsStatic, instance_expr, getter, null, loc);
3135                         
3136                 }
3137
3138                 //
3139                 // Implements the IAssignMethod interface for assignments
3140                 //
3141                 public void EmitAssign (EmitContext ec, Expression source)
3142                 {
3143                         Argument arg = new Argument (source, Argument.AType.Expression);
3144                         ArrayList args = new ArrayList ();
3145
3146                         args.Add (arg);
3147                         Invocation.EmitCall (ec, IsBase, IsStatic, instance_expr, setter, args, loc);
3148                 }
3149
3150                 override public void EmitStatement (EmitContext ec)
3151                 {
3152                         Emit (ec);
3153                         ec.ig.Emit (OpCodes.Pop);
3154                 }
3155         }
3156
3157         /// <summary>
3158         ///   Fully resolved expression that evaluates to an Event
3159         /// </summary>
3160         public class EventExpr : Expression, IMemberExpr {
3161                 public readonly EventInfo EventInfo;
3162                 public Expression instance_expr;
3163
3164                 bool is_static;
3165                 MethodInfo add_accessor, remove_accessor;
3166                 
3167                 public EventExpr (EventInfo ei, Location loc)
3168                 {
3169                         EventInfo = ei;
3170                         this.loc = loc;
3171                         eclass = ExprClass.EventAccess;
3172
3173                         add_accessor = TypeManager.GetAddMethod (ei);
3174                         remove_accessor = TypeManager.GetRemoveMethod (ei);
3175                         
3176                         if (add_accessor.IsStatic || remove_accessor.IsStatic)
3177                                 is_static = true;
3178
3179                         if (EventInfo is MyEventBuilder){
3180                                 MyEventBuilder eb = (MyEventBuilder) EventInfo;
3181                                 type = eb.EventType;
3182                                 eb.SetUsed ();
3183                         } else
3184                                 type = EventInfo.EventHandlerType;
3185                 }
3186
3187                 public string Name {
3188                         get {
3189                                 return EventInfo.Name;
3190                         }
3191                 }
3192
3193                 public bool IsInstance {
3194                         get {
3195                                 return !is_static;
3196                         }
3197                 }
3198
3199                 public bool IsStatic {
3200                         get {
3201                                 return is_static;
3202                         }
3203                 }
3204
3205                 public Type DeclaringType {
3206                         get {
3207                                 return EventInfo.DeclaringType;
3208                         }
3209                 }
3210
3211                 public Expression InstanceExpression {
3212                         get {
3213                                 return instance_expr;
3214                         }
3215
3216                         set {
3217                                 instance_expr = value;
3218                         }
3219                 }
3220
3221                 public override Expression DoResolve (EmitContext ec)
3222                 {
3223                         if (instance_expr != null) {
3224                                 instance_expr = instance_expr.DoResolve (ec);
3225                                 if (instance_expr == null)
3226                                         return null;
3227                         }
3228
3229                         
3230                         return this;
3231                 }
3232
3233                 public override void Emit (EmitContext ec)
3234                 {
3235                         Report.Error (70, loc, "The event `" + Name + "' can only appear on the left hand side of += or -= (except on the defining type)");
3236                 }
3237
3238                 public void EmitAddOrRemove (EmitContext ec, Expression source)
3239                 {
3240                         BinaryDelegate source_del = (BinaryDelegate) source;
3241                         Expression handler = source_del.Right;
3242                         
3243                         Argument arg = new Argument (handler, Argument.AType.Expression);
3244                         ArrayList args = new ArrayList ();
3245                                 
3246                         args.Add (arg);
3247                         
3248                         if (source_del.IsAddition)
3249                                 Invocation.EmitCall (
3250                                         ec, false, IsStatic, instance_expr, add_accessor, args, loc);
3251                         else
3252                                 Invocation.EmitCall (
3253                                         ec, false, IsStatic, instance_expr, remove_accessor, args, loc);
3254                 }
3255         }
3256 }