**** Merged from HEAD ****
[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
1895                 //
1896                 // If true, then we are a simple name, not composed with a ".
1897                 //
1898                 bool is_base;
1899
1900                 public SimpleName (string a, string b, Location l)
1901                 {
1902                         Name = String.Concat (a, ".", b);
1903                         loc = l;
1904                         is_base = false;
1905                 }
1906                 
1907                 public SimpleName (string name, Location l)
1908                 {
1909                         Name = name;
1910                         loc = l;
1911                         is_base = true;
1912                 }
1913
1914                 public static void Error_ObjectRefRequired (EmitContext ec, Location l, string name)
1915                 {
1916                         if (ec.IsFieldInitializer)
1917                                 Report.Error (
1918                                         236, l,
1919                                         "A field initializer cannot reference the non-static field, " +
1920                                         "method or property `"+name+"'");
1921                         else
1922                                 Report.Error (
1923                                         120, l,
1924                                         "An object reference is required " +
1925                                         "for the non-static field `"+name+"'");
1926                 }
1927                 
1928                 //
1929                 // Checks whether we are trying to access an instance
1930                 // property, method or field from a static body.
1931                 //
1932                 Expression MemberStaticCheck (EmitContext ec, Expression e)
1933                 {
1934                         if (e is IMemberExpr){
1935                                 IMemberExpr member = (IMemberExpr) e;
1936                                 
1937                                 if (!member.IsStatic){
1938                                         Error_ObjectRefRequired (ec, loc, Name);
1939                                         return null;
1940                                 }
1941                         }
1942
1943                         return e;
1944                 }
1945                 
1946                 public override Expression DoResolve (EmitContext ec)
1947                 {
1948                         return SimpleNameResolve (ec, null, false);
1949                 }
1950
1951                 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
1952                 {
1953                         return SimpleNameResolve (ec, right_side, false);
1954                 }
1955                 
1956
1957                 public Expression DoResolveAllowStatic (EmitContext ec)
1958                 {
1959                         return SimpleNameResolve (ec, null, true);
1960                 }
1961
1962                 public override Expression ResolveAsTypeStep (EmitContext ec)
1963                 {
1964                         DeclSpace ds = ec.DeclSpace;
1965                         NamespaceEntry ns = ds.NamespaceEntry;
1966                         Type t;
1967                         string alias_value;
1968
1969                         //
1970                         // Since we are cheating: we only do the Alias lookup for
1971                         // namespaces if the name does not include any dots in it
1972                         //
1973                         if (ns != null && is_base)
1974                                 alias_value = ns.LookupAlias (Name);
1975                         else
1976                                 alias_value = null;
1977
1978                         if (ec.ResolvingTypeTree){
1979                                 int errors = Report.Errors;
1980                                 Type dt = ds.FindType (loc, Name);
1981                                 
1982                                 if (Report.Errors != errors)
1983                                         return null;
1984                                 
1985                                 if (dt != null)
1986                                         return new TypeExpression (dt, loc);
1987
1988                                 if (alias_value != null){
1989                                         if ((t = RootContext.LookupType (ds, alias_value, true, loc)) != null)
1990                                                 return new TypeExpression (t, loc);
1991                                 }
1992                         }
1993
1994                         //
1995                         // First, the using aliases
1996                         //
1997                         if (alias_value != null){
1998                                 if ((t = RootContext.LookupType (ds, alias_value, true, loc)) != null)
1999                                         return new TypeExpression (t, loc);
2000                                 
2001                                 // we have alias value, but it isn't Type, so try if it's namespace
2002                                 return new SimpleName (alias_value, loc);
2003                         }
2004
2005                         TypeParameterExpr generic_type = ds.LookupGeneric (Name, loc);
2006                         if (generic_type != null)
2007                                 return generic_type.ResolveAsTypeTerminal (ec);
2008
2009                         //
2010                         // Stage 2: Lookup up if we are an alias to a type
2011                         // or a namespace.
2012                         //
2013
2014                         if ((t = RootContext.LookupType (ds, Name, true, loc)) != null)
2015                                 return new TypeExpression (t, loc);
2016                                 
2017                         // No match, maybe our parent can compose us
2018                         // into something meaningful.
2019                         return this;
2020                 }
2021
2022                 /// <remarks>
2023                 ///   7.5.2: Simple Names. 
2024                 ///
2025                 ///   Local Variables and Parameters are handled at
2026                 ///   parse time, so they never occur as SimpleNames.
2027                 ///
2028                 ///   The `allow_static' flag is used by MemberAccess only
2029                 ///   and it is used to inform us that it is ok for us to 
2030                 ///   avoid the static check, because MemberAccess might end
2031                 ///   up resolving the Name as a Type name and the access as
2032                 ///   a static type access.
2033                 ///
2034                 ///   ie: Type Type; .... { Type.GetType (""); }
2035                 ///
2036                 ///   Type is both an instance variable and a Type;  Type.GetType
2037                 ///   is the static method not an instance method of type.
2038                 /// </remarks>
2039                 Expression SimpleNameResolve (EmitContext ec, Expression right_side, bool allow_static)
2040                 {
2041                         Expression e = null;
2042
2043                         //
2044                         // Stage 1: Performed by the parser (binding to locals or parameters).
2045                         //
2046                         Block current_block = ec.CurrentBlock;
2047                         if (current_block != null){
2048                                 LocalInfo vi = current_block.GetLocalInfo (Name);
2049                                 if (vi != null){
2050                                         Expression var;
2051                                         
2052                                         var = new LocalVariableReference (ec.CurrentBlock, Name, loc);
2053                                         
2054                                         if (right_side != null)
2055                                                 return var.ResolveLValue (ec, right_side);
2056                                         else
2057                                                 return var.Resolve (ec);
2058                                 }
2059
2060                                 int idx = -1;
2061                                 Parameter par = null;
2062                                 Parameters pars = current_block.Parameters;
2063                                 if (pars != null)
2064                                         par = pars.GetParameterByName (Name, out idx);
2065
2066                                 if (par != null) {
2067                                         ParameterReference param;
2068                                         
2069                                         param = new ParameterReference (pars, current_block, idx, Name, loc);
2070
2071                                         if (right_side != null)
2072                                                 return param.ResolveLValue (ec, right_side);
2073                                         else
2074                                                 return param.Resolve (ec);
2075                                 }
2076                         }
2077                         
2078                         //
2079                         // Stage 2: Lookup members 
2080                         //
2081
2082                         DeclSpace lookup_ds = ec.DeclSpace;
2083                         do {
2084                                 if (lookup_ds.TypeBuilder == null)
2085                                         break;
2086
2087                                 e = MemberLookup (ec, lookup_ds.TypeBuilder, Name, loc);
2088                                 if (e != null)
2089                                         break;
2090
2091                                 lookup_ds =lookup_ds.Parent;
2092                         } while (lookup_ds != null);
2093
2094                         if (e == null && ec.ContainerType != null)
2095                                 e = MemberLookup (ec, ec.ContainerType, Name, loc);
2096
2097                         if (e == null) {
2098                                 //
2099                                 // Since we are cheating (is_base is our hint
2100                                 // that we are the beginning of the name): we
2101                                 // only do the Alias lookup for namespaces if
2102                                 // the name does not include any dots in it
2103                                 //
2104                                 NamespaceEntry ns = ec.DeclSpace.NamespaceEntry;
2105                                 if (is_base && ns != null){
2106                                         string alias_value = ns.LookupAlias (Name);
2107                                         if (alias_value != null){
2108                                                 Name = alias_value;
2109                                                 Type t;
2110
2111                                                 if ((t = TypeManager.LookupType (Name)) != null)
2112                                                         return new TypeExpression (t, loc);
2113                                         
2114                                                 // No match, maybe our parent can compose us
2115                                                 // into something meaningful.
2116                                                 return this;
2117                                         }
2118                                 }
2119
2120                                 return ResolveAsTypeStep (ec);
2121                         }
2122
2123                         if (e is TypeExpr)
2124                                 return e;
2125
2126                         if (e is IMemberExpr) {
2127                                 e = MemberAccess.ResolveMemberAccess (ec, e, null, loc, this);
2128                                 if (e == null)
2129                                         return null;
2130
2131                                 IMemberExpr me = e as IMemberExpr;
2132                                 if (me == null)
2133                                         return e;
2134
2135                                 // This fails if ResolveMemberAccess() was unable to decide whether
2136                                 // it's a field or a type of the same name.
2137                                 if (!me.IsStatic && (me.InstanceExpression == null))
2138                                         return e;
2139
2140                                 if (!me.IsStatic &&
2141                                     TypeManager.IsNestedChildOf (me.InstanceExpression.Type, me.DeclaringType) &&
2142                                     !me.InstanceExpression.Type.IsSubclassOf (me.DeclaringType)) {
2143                                         Error (38, "Cannot access nonstatic member `" + me.Name + "' of " +
2144                                                "outer type `" + me.DeclaringType + "' via nested type `" +
2145                                                me.InstanceExpression.Type + "'");
2146                                         return null;
2147                                 }
2148
2149                                 if (right_side != null)
2150                                         e = e.DoResolveLValue (ec, right_side);
2151                                 else
2152                                         e = e.DoResolve (ec);
2153
2154                                 return e;                               
2155                         }
2156
2157                         if (ec.IsStatic || ec.IsFieldInitializer){
2158                                 if (allow_static)
2159                                         return e;
2160
2161                                 return MemberStaticCheck (ec, e);
2162                         } else
2163                                 return e;
2164                 }
2165                 
2166                 public override void Emit (EmitContext ec)
2167                 {
2168                         //
2169                         // If this is ever reached, then we failed to
2170                         // find the name as a namespace
2171                         //
2172
2173                         Error (103, "The name `" + Name +
2174                                "' does not exist in the class `" +
2175                                ec.DeclSpace.Name + "'");
2176                 }
2177
2178                 public override string ToString ()
2179                 {
2180                         return Name;
2181                 }
2182         }
2183         
2184         /// <summary>
2185         ///   Fully resolved expression that evaluates to a type
2186         /// </summary>
2187         public abstract class TypeExpr : Expression {
2188                 override public Expression ResolveAsTypeStep (EmitContext ec)
2189                 {
2190                         TypeExpr t = DoResolveAsTypeStep (ec);
2191                         if (t == null)
2192                                 return null;
2193
2194                         eclass = ExprClass.Type;
2195                         return t;
2196                 }
2197
2198                 override public Expression DoResolve (EmitContext ec)
2199                 {
2200                         return ResolveAsTypeTerminal (ec);
2201                 }
2202
2203                 override public void Emit (EmitContext ec)
2204                 {
2205                         throw new Exception ("Should never be called");
2206                 }
2207
2208                 public virtual bool CheckAccessLevel (DeclSpace ds)
2209                 {
2210                         return ds.CheckAccessLevel (Type);
2211                 }
2212
2213                 public virtual bool AsAccessible (DeclSpace ds, int flags)
2214                 {
2215                         return ds.AsAccessible (Type, flags);
2216                 }
2217
2218                 public virtual bool IsClass {
2219                         get { return Type.IsClass; }
2220                 }
2221
2222                 public virtual bool IsValueType {
2223                         get { return Type.IsValueType; }
2224                 }
2225
2226                 public virtual bool IsInterface {
2227                         get { return Type.IsInterface; }
2228                 }
2229
2230                 public virtual bool IsSealed {
2231                         get { return Type.IsSealed; }
2232                 }
2233
2234                 public virtual bool CanInheritFrom ()
2235                 {
2236                         if (Type == TypeManager.enum_type ||
2237                             (Type == TypeManager.value_type && RootContext.StdLib) ||
2238                             Type == TypeManager.delegate_type ||
2239                             Type == TypeManager.array_type)
2240                                 return false;
2241
2242                         return true;
2243                 }
2244
2245                 public virtual bool IsAttribute {
2246                         get {
2247                                 return Type == TypeManager.attribute_type ||
2248                                         Type.IsSubclassOf (TypeManager.attribute_type);
2249                         }
2250                 }
2251
2252                 public virtual TypeExpr[] GetInterfaces ()
2253                 {
2254                         return TypeManager.GetInterfaces (Type);
2255                 }
2256
2257                 public abstract TypeExpr DoResolveAsTypeStep (EmitContext ec);
2258
2259                 public virtual Type ResolveType (EmitContext ec)
2260                 {
2261                         TypeExpr t = ResolveAsTypeTerminal (ec);
2262                         if (t == null)
2263                                 return null;
2264
2265                         return t.Type;
2266                 }
2267
2268                 public abstract string Name {
2269                         get;
2270                 }
2271
2272                 public override bool Equals (object obj)
2273                 {
2274                         TypeExpr tobj = obj as TypeExpr;
2275                         if (tobj == null)
2276                                 return false;
2277
2278                         return Type == tobj.Type;
2279                 }
2280
2281                 public override string ToString ()
2282                 {
2283                         return Name;
2284                 }
2285         }
2286
2287         public class TypeExpression : TypeExpr {
2288                 public TypeExpression (Type t, Location l)
2289                 {
2290                         Type = t;
2291                         eclass = ExprClass.Type;
2292                         loc = l;
2293                 }
2294
2295                 public override TypeExpr DoResolveAsTypeStep (EmitContext ec)
2296                 {
2297                         return this;
2298                 }
2299
2300                 public override string Name {
2301                         get {
2302                                 return Type.ToString ();
2303                         }
2304                 }
2305         }
2306
2307         /// <summary>
2308         ///   Used to create types from a fully qualified name.  These are just used
2309         ///   by the parser to setup the core types.  A TypeLookupExpression is always
2310         ///   classified as a type.
2311         /// </summary>
2312         public class TypeLookupExpression : TypeExpr {
2313                 string name;
2314                 
2315                 public TypeLookupExpression (string name)
2316                 {
2317                         this.name = name;
2318                 }
2319
2320                 public override TypeExpr DoResolveAsTypeStep (EmitContext ec)
2321                 {
2322                         if (type == null)
2323                                 type = RootContext.LookupType (ec.DeclSpace, name, false, Location.Null);
2324                         return this;
2325                 }
2326
2327                 public override string Name {
2328                         get {
2329                                 return name;
2330                         }
2331                 }
2332         }
2333
2334         /// <summary>
2335         ///   MethodGroup Expression.
2336         ///  
2337         ///   This is a fully resolved expression that evaluates to a type
2338         /// </summary>
2339         public class MethodGroupExpr : Expression, IMemberExpr {
2340                 public MethodBase [] Methods;
2341                 Expression instance_expression = null;
2342                 bool is_explicit_impl = false;
2343                 
2344                 public MethodGroupExpr (MemberInfo [] mi, Location l)
2345                 {
2346                         Methods = new MethodBase [mi.Length];
2347                         mi.CopyTo (Methods, 0);
2348                         eclass = ExprClass.MethodGroup;
2349                         type = TypeManager.object_type;
2350                         loc = l;
2351                 }
2352
2353                 public MethodGroupExpr (ArrayList list, Location l)
2354                 {
2355                         Methods = new MethodBase [list.Count];
2356
2357                         try {
2358                                 list.CopyTo (Methods, 0);
2359                         } catch {
2360                                 foreach (MemberInfo m in list){
2361                                         if (!(m is MethodBase)){
2362                                                 Console.WriteLine ("Name " + m.Name);
2363                                                 Console.WriteLine ("Found a: " + m.GetType ().FullName);
2364                                         }
2365                                 }
2366                                 throw;
2367                         }
2368
2369                         loc = l;
2370                         eclass = ExprClass.MethodGroup;
2371                         type = TypeManager.object_type;
2372                 }
2373
2374                 public Type DeclaringType {
2375                         get {
2376                                 //
2377                                 // We assume that the top-level type is in the end
2378                                 //
2379                                 return Methods [Methods.Length - 1].DeclaringType;
2380                                 //return Methods [0].DeclaringType;
2381                         }
2382                 }
2383                 
2384                 //
2385                 // `A method group may have associated an instance expression' 
2386                 // 
2387                 public Expression InstanceExpression {
2388                         get {
2389                                 return instance_expression;
2390                         }
2391
2392                         set {
2393                                 instance_expression = value;
2394                         }
2395                 }
2396
2397                 public bool IsExplicitImpl {
2398                         get {
2399                                 return is_explicit_impl;
2400                         }
2401
2402                         set {
2403                                 is_explicit_impl = value;
2404                         }
2405                 }
2406
2407                 public string Name {
2408                         get {
2409                                 //return Methods [0].Name;
2410                                 return Methods [Methods.Length - 1].Name;
2411                         }
2412                 }
2413
2414                 public bool IsInstance {
2415                         get {
2416                                 foreach (MethodBase mb in Methods)
2417                                         if (!mb.IsStatic)
2418                                                 return true;
2419
2420                                 return false;
2421                         }
2422                 }
2423
2424                 public bool IsStatic {
2425                         get {
2426                                 foreach (MethodBase mb in Methods)
2427                                         if (mb.IsStatic)
2428                                                 return true;
2429
2430                                 return false;
2431                         }
2432                 }
2433                 
2434                 override public Expression DoResolve (EmitContext ec)
2435                 {
2436                         if (!IsInstance)
2437                                 instance_expression = null;
2438
2439                         if (instance_expression != null) {
2440                                 instance_expression = instance_expression.DoResolve (ec);
2441                                 if (instance_expression == null)
2442                                         return null;
2443                         }
2444
2445                         return this;
2446                 }
2447
2448                 public void ReportUsageError ()
2449                 {
2450                         Report.Error (654, loc, "Method `" + DeclaringType + "." +
2451                                       Name + "()' is referenced without parentheses");
2452                 }
2453
2454                 override public void Emit (EmitContext ec)
2455                 {
2456                         ReportUsageError ();
2457                 }
2458
2459                 bool RemoveMethods (bool keep_static)
2460                 {
2461                         ArrayList smethods = new ArrayList ();
2462
2463                         foreach (MethodBase mb in Methods){
2464                                 if (mb.IsStatic == keep_static)
2465                                         smethods.Add (mb);
2466                         }
2467
2468                         if (smethods.Count == 0)
2469                                 return false;
2470
2471                         Methods = new MethodBase [smethods.Count];
2472                         smethods.CopyTo (Methods, 0);
2473
2474                         return true;
2475                 }
2476                 
2477                 /// <summary>
2478                 ///   Removes any instance methods from the MethodGroup, returns
2479                 ///   false if the resulting set is empty.
2480                 /// </summary>
2481                 public bool RemoveInstanceMethods ()
2482                 {
2483                         return RemoveMethods (true);
2484                 }
2485
2486                 /// <summary>
2487                 ///   Removes any static methods from the MethodGroup, returns
2488                 ///   false if the resulting set is empty.
2489                 /// </summary>
2490                 public bool RemoveStaticMethods ()
2491                 {
2492                         return RemoveMethods (false);
2493                 }
2494         }
2495
2496         /// <summary>
2497         ///   Fully resolved expression that evaluates to a Field
2498         /// </summary>
2499         public class FieldExpr : Expression, IAssignMethod, IMemoryLocation, IMemberExpr, IVariable {
2500                 public readonly FieldInfo FieldInfo;
2501                 Expression instance_expr;
2502                 VariableInfo variable_info;
2503                 
2504                 public FieldExpr (FieldInfo fi, Location l)
2505                 {
2506                         FieldInfo = fi;
2507                         eclass = ExprClass.Variable;
2508                         type = fi.FieldType;
2509                         loc = l;
2510                 }
2511
2512                 public string Name {
2513                         get {
2514                                 return FieldInfo.Name;
2515                         }
2516                 }
2517
2518                 public bool IsInstance {
2519                         get {
2520                                 return !FieldInfo.IsStatic;
2521                         }
2522                 }
2523
2524                 public bool IsStatic {
2525                         get {
2526                                 return FieldInfo.IsStatic;
2527                         }
2528                 }
2529
2530                 public Type DeclaringType {
2531                         get {
2532                                 return FieldInfo.DeclaringType;
2533                         }
2534                 }
2535
2536                 public Expression InstanceExpression {
2537                         get {
2538                                 return instance_expr;
2539                         }
2540
2541                         set {
2542                                 instance_expr = value;
2543                         }
2544                 }
2545
2546                 public VariableInfo VariableInfo {
2547                         get {
2548                                 return variable_info;
2549                         }
2550                 }
2551
2552                 override public Expression DoResolve (EmitContext ec)
2553                 {
2554                         if (!FieldInfo.IsStatic){
2555                                 if (instance_expr == null){
2556                                         //
2557                                         // This can happen when referencing an instance field using
2558                                         // a fully qualified type expression: TypeName.InstanceField = xxx
2559                                         // 
2560                                         SimpleName.Error_ObjectRefRequired (ec, loc, FieldInfo.Name);
2561                                         return null;
2562                                 }
2563
2564                                 // Resolve the field's instance expression while flow analysis is turned
2565                                 // off: when accessing a field "a.b", we must check whether the field
2566                                 // "a.b" is initialized, not whether the whole struct "a" is initialized.
2567                                 instance_expr = instance_expr.Resolve (ec, ResolveFlags.VariableOrValue |
2568                                                                        ResolveFlags.DisableFlowAnalysis);
2569                                 if (instance_expr == null)
2570                                         return null;
2571                         }
2572
2573                         // If the instance expression is a local variable or parameter.
2574                         IVariable var = instance_expr as IVariable;
2575                         if ((var == null) || (var.VariableInfo == null))
2576                                 return this;
2577
2578                         VariableInfo vi = var.VariableInfo;
2579                         if (!vi.IsFieldAssigned (ec, FieldInfo.Name, loc))
2580                                 return null;
2581
2582                         variable_info = vi.GetSubStruct (FieldInfo.Name);
2583                         return this;
2584                 }
2585
2586                 void Report_AssignToReadonly (bool is_instance)
2587                 {
2588                         string msg;
2589                         
2590                         if (is_instance)
2591                                 msg = "Readonly field can not be assigned outside " +
2592                                 "of constructor or variable initializer";
2593                         else
2594                                 msg = "A static readonly field can only be assigned in " +
2595                                 "a static constructor";
2596
2597                         Report.Error (is_instance ? 191 : 198, loc, msg);
2598                 }
2599                 
2600                 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
2601                 {
2602                         IVariable var = instance_expr as IVariable;
2603                         if ((var != null) && (var.VariableInfo != null))
2604                                 var.VariableInfo.SetFieldAssigned (ec, FieldInfo.Name);
2605
2606                         Expression e = DoResolve (ec);
2607
2608                         if (e == null)
2609                                 return null;
2610
2611                         if (!FieldInfo.IsStatic && (instance_expr.Type.IsValueType && !(instance_expr is IMemoryLocation))) {
2612                                 // FIXME: Provide better error reporting.
2613                                 Error (1612, "Cannot modify expression because it is not a variable.");
2614                                 return null;
2615                         }
2616
2617                         if (!FieldInfo.IsInitOnly)
2618                                 return this;
2619
2620                         FieldBase fb = TypeManager.GetField (FieldInfo);
2621                         if (fb != null)
2622                                 fb.SetAssigned ();
2623
2624                         //
2625                         // InitOnly fields can only be assigned in constructors
2626                         //
2627
2628                         if (ec.IsConstructor){
2629                                 if (IsStatic && !ec.IsStatic)
2630                                         Report_AssignToReadonly (false);
2631
2632                                 if (ec.ContainerType == FieldInfo.DeclaringType)
2633                                         return this;
2634                         }
2635
2636                         Report_AssignToReadonly (true);
2637                         
2638                         return null;
2639                 }
2640
2641                 public bool VerifyFixed (bool is_expression)
2642                 {
2643                         IVariable variable = instance_expr as IVariable;
2644                         if ((variable == null) || !variable.VerifyFixed (true))
2645                                 return false;
2646
2647                         return true;
2648                 }
2649
2650                 override public void Emit (EmitContext ec)
2651                 {
2652                         ILGenerator ig = ec.ig;
2653                         bool is_volatile = false;
2654
2655                         if (FieldInfo is FieldBuilder){
2656                                 FieldBase f = TypeManager.GetField (FieldInfo);
2657                                 if (f != null){
2658                                         if ((f.ModFlags & Modifiers.VOLATILE) != 0)
2659                                                 is_volatile = true;
2660                                         
2661                                         f.status |= Field.Status.USED;
2662                                 }
2663                         } 
2664                         
2665                         if (FieldInfo.IsStatic){
2666                                 if (is_volatile)
2667                                         ig.Emit (OpCodes.Volatile);
2668                                 
2669                                 ig.Emit (OpCodes.Ldsfld, FieldInfo);
2670                                 return;
2671                         }
2672                         
2673                         if (instance_expr.Type.IsValueType){
2674                                 IMemoryLocation ml;
2675                                 LocalTemporary tempo = null;
2676                                 
2677                                 if (!(instance_expr is IMemoryLocation)){
2678                                         tempo = new LocalTemporary (ec, instance_expr.Type);
2679                                         
2680                                         if (ec.RemapToProxy)
2681                                                 ec.EmitThis ();
2682                         
2683                                         InstanceExpression.Emit (ec);
2684                                         tempo.Store (ec);
2685                                         ml = tempo;
2686                                 } else
2687                                         ml = (IMemoryLocation) instance_expr;
2688                                 
2689                                 ml.AddressOf (ec, AddressOp.Load);
2690                         } else {
2691                                 if (ec.RemapToProxy)
2692                                         ec.EmitThis ();
2693                                 else
2694                                         instance_expr.Emit (ec);
2695                         }
2696                         if (is_volatile)
2697                                 ig.Emit (OpCodes.Volatile);
2698                         
2699                         ig.Emit (OpCodes.Ldfld, FieldInfo);
2700                 }
2701
2702                 public void EmitAssign (EmitContext ec, Expression source)
2703                 {
2704                         FieldAttributes fa = FieldInfo.Attributes;
2705                         bool is_static = (fa & FieldAttributes.Static) != 0;
2706                         bool is_readonly = (fa & FieldAttributes.InitOnly) != 0;
2707                         ILGenerator ig = ec.ig;
2708
2709                         if (is_readonly && !ec.IsConstructor){
2710                                 Report_AssignToReadonly (!is_static);
2711                                 return;
2712                         }
2713
2714                         if (!is_static){
2715                                 Expression instance = instance_expr;
2716
2717                                 if (instance.Type.IsValueType){
2718                                         IMemoryLocation ml = (IMemoryLocation) instance;
2719
2720                                         ml.AddressOf (ec, AddressOp.Store);
2721                                 } else {
2722                                         if (ec.RemapToProxy)
2723                                                 ec.EmitThis ();
2724                                         else
2725                                                 instance.Emit (ec);
2726                                 }
2727                         }
2728
2729                         source.Emit (ec);
2730
2731                         if (FieldInfo is FieldBuilder){
2732                                 FieldBase f = TypeManager.GetField (FieldInfo);
2733                                 if (f != null){
2734                                         if ((f.ModFlags & Modifiers.VOLATILE) != 0)
2735                                                 ig.Emit (OpCodes.Volatile);
2736                                         
2737                                         f.status |= Field.Status.ASSIGNED;
2738                                 }
2739                         } 
2740
2741                         if (is_static)
2742                                 ig.Emit (OpCodes.Stsfld, FieldInfo);
2743                         else 
2744                                 ig.Emit (OpCodes.Stfld, FieldInfo);
2745                 }
2746                 
2747                 public void AddressOf (EmitContext ec, AddressOp mode)
2748                 {
2749                         ILGenerator ig = ec.ig;
2750                         
2751                         if (FieldInfo is FieldBuilder){
2752                                 FieldBase f = TypeManager.GetField (FieldInfo);
2753                                 if (f != null){
2754                                         if ((f.ModFlags & Modifiers.VOLATILE) != 0){
2755                                                 Error (676, "volatile variable: can not take its address, or pass as ref/out parameter");
2756                                                 return;
2757                                         }
2758                                         
2759                                         if ((mode & AddressOp.Store) != 0)
2760                                                 f.status |= Field.Status.ASSIGNED;
2761                                         if ((mode & AddressOp.Load) != 0)
2762                                                 f.status |= Field.Status.USED;
2763                                 }
2764                         } 
2765
2766                         //
2767                         // Handle initonly fields specially: make a copy and then
2768                         // get the address of the copy.
2769                         //
2770                         bool need_copy;
2771                         if (FieldInfo.IsInitOnly){
2772                                 need_copy = true;
2773                                 if (ec.IsConstructor){
2774                                         if (FieldInfo.IsStatic){
2775                                                 if (ec.IsStatic)
2776                                                         need_copy = false;
2777                                         } else
2778                                                 need_copy = false;
2779                                 }
2780                         } else
2781                                 need_copy = false;
2782                         
2783                         if (need_copy){
2784                                 LocalBuilder local;
2785                                 Emit (ec);
2786                                 local = ig.DeclareLocal (type);
2787                                 ig.Emit (OpCodes.Stloc, local);
2788                                 ig.Emit (OpCodes.Ldloca, local);
2789                                 return;
2790                         }
2791
2792
2793                         if (FieldInfo.IsStatic){
2794                                 ig.Emit (OpCodes.Ldsflda, FieldInfo);
2795                         } else {
2796                                 //
2797                                 // In the case of `This', we call the AddressOf method, which will
2798                                 // only load the pointer, and not perform an Ldobj immediately after
2799                                 // the value has been loaded into the stack.
2800                                 //
2801                                 if (instance_expr is This)
2802                                         ((This)instance_expr).AddressOf (ec, AddressOp.LoadStore);
2803                                 else if (instance_expr.Type.IsValueType && instance_expr is IMemoryLocation){
2804                                         IMemoryLocation ml = (IMemoryLocation) instance_expr;
2805
2806                                         ml.AddressOf (ec, AddressOp.LoadStore);
2807                                 } else
2808                                         instance_expr.Emit (ec);
2809                                 ig.Emit (OpCodes.Ldflda, FieldInfo);
2810                         }
2811                 }
2812         }
2813
2814         //
2815         // A FieldExpr whose address can not be taken
2816         //
2817         public class FieldExprNoAddress : FieldExpr, IMemoryLocation {
2818                 public FieldExprNoAddress (FieldInfo fi, Location loc) : base (fi, loc)
2819                 {
2820                 }
2821                 
2822                 public new void AddressOf (EmitContext ec, AddressOp mode)
2823                 {
2824                         Report.Error (-215, "Report this: Taking the address of a remapped parameter not supported");
2825                 }
2826         }
2827         
2828         /// <summary>
2829         ///   Expression that evaluates to a Property.  The Assign class
2830         ///   might set the `Value' expression if we are in an assignment.
2831         ///
2832         ///   This is not an LValue because we need to re-write the expression, we
2833         ///   can not take data from the stack and store it.  
2834         /// </summary>
2835         public class PropertyExpr : ExpressionStatement, IAssignMethod, IMemberExpr {
2836                 public readonly PropertyInfo PropertyInfo;
2837
2838                 //
2839                 // This is set externally by the  `BaseAccess' class
2840                 //
2841                 public bool IsBase;
2842                 MethodInfo getter, setter;
2843                 bool is_static;
2844                 bool must_do_cs1540_check;
2845                 
2846                 Expression instance_expr;
2847
2848                 public PropertyExpr (EmitContext ec, PropertyInfo pi, Location l)
2849                 {
2850                         PropertyInfo = pi;
2851                         eclass = ExprClass.PropertyAccess;
2852                         is_static = false;
2853                         loc = l;
2854
2855                         type = TypeManager.TypeToCoreType (pi.PropertyType);
2856
2857                         ResolveAccessors (ec);
2858                 }
2859
2860                 public string Name {
2861                         get {
2862                                 return PropertyInfo.Name;
2863                         }
2864                 }
2865
2866                 public bool IsInstance {
2867                         get {
2868                                 return !is_static;
2869                         }
2870                 }
2871
2872                 public bool IsStatic {
2873                         get {
2874                                 return is_static;
2875                         }
2876                 }
2877                 
2878                 public Type DeclaringType {
2879                         get {
2880                                 return PropertyInfo.DeclaringType;
2881                         }
2882                 }
2883
2884                 //
2885                 // The instance expression associated with this expression
2886                 //
2887                 public Expression InstanceExpression {
2888                         set {
2889                                 instance_expr = value;
2890                         }
2891
2892                         get {
2893                                 return instance_expr;
2894                         }
2895                 }
2896
2897                 public bool VerifyAssignable ()
2898                 {
2899                         if (setter == null) {
2900                                 Report.Error (200, loc, 
2901                                               "The property `" + PropertyInfo.Name +
2902                                               "' can not be assigned to, as it has not set accessor");
2903                                 return false;
2904                         }
2905
2906                         return true;
2907                 }
2908
2909                 MethodInfo GetAccessor (Type invocation_type, string accessor_name)
2910                 {
2911                         BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic |
2912                                 BindingFlags.Static | BindingFlags.Instance;
2913                         MemberInfo[] group;
2914
2915                         group = TypeManager.MemberLookup (
2916                                 invocation_type, invocation_type, PropertyInfo.DeclaringType,
2917                                 MemberTypes.Method, flags, accessor_name + "_" + PropertyInfo.Name);
2918
2919                         //
2920                         // The first method is the closest to us
2921                         //
2922                         if (group == null)
2923                                 return null;
2924
2925                         foreach (MethodInfo mi in group) {
2926                                 MethodAttributes ma = mi.Attributes & MethodAttributes.MemberAccessMask;
2927
2928                                 //
2929                                 // If only accessible to the current class or children
2930                                 //
2931                                 if (ma == MethodAttributes.Private) {
2932                                         Type declaring_type = mi.DeclaringType;
2933                                         
2934                                         if (invocation_type != declaring_type){
2935                                                 if (TypeManager.IsSubclassOrNestedChildOf (invocation_type, mi.DeclaringType))
2936                                                         return mi;
2937                                                 else
2938                                                         continue;
2939                                         } else
2940                                                 return mi;
2941                                 }
2942                                 //
2943                                 // FamAndAssem requires that we not only derivate, but we are on the
2944                                 // same assembly.  
2945                                 //
2946                                 if (ma == MethodAttributes.FamANDAssem){
2947                                         if (mi.DeclaringType.Assembly != invocation_type.Assembly)
2948                                                 continue;
2949                                         else
2950                                                 return mi;
2951                                 }
2952
2953                                 // Assembly and FamORAssem succeed if we're in the same assembly.
2954                                 if ((ma == MethodAttributes.Assembly) || (ma == MethodAttributes.FamORAssem)){
2955                                         if (mi.DeclaringType.Assembly == invocation_type.Assembly)
2956                                                 return mi;
2957                                 }
2958
2959                                 // We already know that we aren't in the same assembly.
2960                                 if (ma == MethodAttributes.Assembly)
2961                                         continue;
2962
2963                                 // Family and FamANDAssem require that we derive.
2964                                 if ((ma == MethodAttributes.Family) || (ma == MethodAttributes.FamANDAssem) || (ma == MethodAttributes.FamORAssem)){
2965                                         if (!TypeManager.IsSubclassOrNestedChildOf (invocation_type, mi.DeclaringType))
2966                                                 continue;
2967                                         else {
2968                                                 must_do_cs1540_check = true;
2969
2970                                                 return mi;
2971                                         }
2972                                 }
2973
2974                                 return mi;
2975                         }
2976
2977                         return null;
2978                 }
2979
2980                 //
2981                 // We also perform the permission checking here, as the PropertyInfo does not
2982                 // hold the information for the accessibility of its setter/getter
2983                 //
2984                 void ResolveAccessors (EmitContext ec)
2985                 {
2986                         getter = GetAccessor (ec.ContainerType, "get");
2987                         if ((getter != null) && getter.IsStatic)
2988                                 is_static = true;
2989
2990                         setter = GetAccessor (ec.ContainerType, "set");
2991                         if ((setter != null) && setter.IsStatic)
2992                                 is_static = true;
2993
2994                         if (setter == null && getter == null){
2995                                 Error (122, "`" + PropertyInfo.Name + "' " +
2996                                        "is inaccessible because of its protection level");
2997                                 
2998                         }
2999                 }
3000
3001                 bool InstanceResolve (EmitContext ec)
3002                 {
3003                         if ((instance_expr == null) && ec.IsStatic && !is_static) {
3004                                 SimpleName.Error_ObjectRefRequired (ec, loc, PropertyInfo.Name);
3005                                 return false;
3006                         }
3007
3008                         if (instance_expr != null) {
3009                                 instance_expr = instance_expr.DoResolve (ec);
3010                                 if (instance_expr == null)
3011                                         return false;
3012                         }
3013
3014                         if (must_do_cs1540_check && (instance_expr != null)) {
3015                                 if ((instance_expr.Type != ec.ContainerType) &&
3016                                     ec.ContainerType.IsSubclassOf (instance_expr.Type)) {
3017                                         Report.Error (1540, loc, "Cannot access protected member `" +
3018                                                       PropertyInfo.DeclaringType + "." + PropertyInfo.Name + 
3019                                                       "' via a qualifier of type `" +
3020                                                       TypeManager.CSharpName (instance_expr.Type) +
3021                                                       "'; the qualifier must be of type `" +
3022                                                       TypeManager.CSharpName (ec.ContainerType) +
3023                                                       "' (or derived from it)");
3024                                         return false;
3025                                 }
3026                         }
3027
3028                         return true;
3029                 }
3030                 
3031                 override public Expression DoResolve (EmitContext ec)
3032                 {
3033                         if (getter == null){
3034                                 //
3035                                 // The following condition happens if the PropertyExpr was
3036                                 // created, but is invalid (ie, the property is inaccessible),
3037                                 // and we did not want to embed the knowledge about this in
3038                                 // the caller routine.  This only avoids double error reporting.
3039                                 //
3040                                 if (setter == null)
3041                                         return null;
3042                                 
3043                                 Report.Error (154, loc, 
3044                                               "The property `" + PropertyInfo.Name +
3045                                               "' can not be used in " +
3046                                               "this context because it lacks a get accessor");
3047                                 return null;
3048                         } 
3049
3050                         if (!InstanceResolve (ec))
3051                                 return null;
3052
3053                         //
3054                         // Only base will allow this invocation to happen.
3055                         //
3056                         if (IsBase && getter.IsAbstract){
3057                                 Report.Error (205, loc, "Cannot call an abstract base property: " +
3058                                               PropertyInfo.DeclaringType + "." +PropertyInfo.Name);
3059                                 return null;
3060                         }
3061
3062                         return this;
3063                 }
3064
3065                 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
3066                 {
3067                         if (setter == null){
3068                                 //
3069                                 // The following condition happens if the PropertyExpr was
3070                                 // created, but is invalid (ie, the property is inaccessible),
3071                                 // and we did not want to embed the knowledge about this in
3072                                 // the caller routine.  This only avoids double error reporting.
3073                                 //
3074                                 if (getter == null)
3075                                         return null;
3076                                 
3077                                 Report.Error (154, loc, 
3078                                               "The property `" + PropertyInfo.Name +
3079                                               "' can not be used in " +
3080                                               "this context because it lacks a set accessor");
3081                                 return null;
3082                         }
3083
3084                         if (!InstanceResolve (ec))
3085                                 return null;
3086                         
3087                         //
3088                         // Only base will allow this invocation to happen.
3089                         //
3090                         if (IsBase && setter.IsAbstract){
3091                                 Report.Error (205, loc, "Cannot call an abstract base property: " +
3092                                               PropertyInfo.DeclaringType + "." +PropertyInfo.Name);
3093                                 return null;
3094                         }
3095                         return this;
3096                 }
3097
3098                 override public void Emit (EmitContext ec)
3099                 {
3100                         //
3101                         // Special case: length of single dimension array property is turned into ldlen
3102                         //
3103                         if ((getter == TypeManager.system_int_array_get_length) ||
3104                             (getter == TypeManager.int_array_get_length)){
3105                                 Type iet = instance_expr.Type;
3106
3107                                 //
3108                                 // System.Array.Length can be called, but the Type does not
3109                                 // support invoking GetArrayRank, so test for that case first
3110                                 //
3111                                 if (iet != TypeManager.array_type && (iet.GetArrayRank () == 1)){
3112                                         instance_expr.Emit (ec);
3113                                         ec.ig.Emit (OpCodes.Ldlen);
3114                                         ec.ig.Emit (OpCodes.Conv_I4);
3115                                         return;
3116                                 }
3117                         }
3118
3119                         Invocation.EmitCall (ec, IsBase, IsStatic, instance_expr, getter, null, loc);
3120                         
3121                 }
3122
3123                 //
3124                 // Implements the IAssignMethod interface for assignments
3125                 //
3126                 public void EmitAssign (EmitContext ec, Expression source)
3127                 {
3128                         Argument arg = new Argument (source, Argument.AType.Expression);
3129                         ArrayList args = new ArrayList ();
3130
3131                         args.Add (arg);
3132                         Invocation.EmitCall (ec, IsBase, IsStatic, instance_expr, setter, args, loc);
3133                 }
3134
3135                 override public void EmitStatement (EmitContext ec)
3136                 {
3137                         Emit (ec);
3138                         ec.ig.Emit (OpCodes.Pop);
3139                 }
3140         }
3141
3142         /// <summary>
3143         ///   Fully resolved expression that evaluates to an Event
3144         /// </summary>
3145         public class EventExpr : Expression, IMemberExpr {
3146                 public readonly EventInfo EventInfo;
3147                 public Expression instance_expr;
3148
3149                 bool is_static;
3150                 MethodInfo add_accessor, remove_accessor;
3151                 
3152                 public EventExpr (EventInfo ei, Location loc)
3153                 {
3154                         EventInfo = ei;
3155                         this.loc = loc;
3156                         eclass = ExprClass.EventAccess;
3157
3158                         add_accessor = TypeManager.GetAddMethod (ei);
3159                         remove_accessor = TypeManager.GetRemoveMethod (ei);
3160                         
3161                         if (add_accessor.IsStatic || remove_accessor.IsStatic)
3162                                 is_static = true;
3163
3164                         if (EventInfo is MyEventBuilder){
3165                                 MyEventBuilder eb = (MyEventBuilder) EventInfo;
3166                                 type = eb.EventType;
3167                                 eb.SetUsed ();
3168                         } else
3169                                 type = EventInfo.EventHandlerType;
3170                 }
3171
3172                 public string Name {
3173                         get {
3174                                 return EventInfo.Name;
3175                         }
3176                 }
3177
3178                 public bool IsInstance {
3179                         get {
3180                                 return !is_static;
3181                         }
3182                 }
3183
3184                 public bool IsStatic {
3185                         get {
3186                                 return is_static;
3187                         }
3188                 }
3189
3190                 public Type DeclaringType {
3191                         get {
3192                                 return EventInfo.DeclaringType;
3193                         }
3194                 }
3195
3196                 public Expression InstanceExpression {
3197                         get {
3198                                 return instance_expr;
3199                         }
3200
3201                         set {
3202                                 instance_expr = value;
3203                         }
3204                 }
3205
3206                 public override Expression DoResolve (EmitContext ec)
3207                 {
3208                         if (instance_expr != null) {
3209                                 instance_expr = instance_expr.DoResolve (ec);
3210                                 if (instance_expr == null)
3211                                         return null;
3212                         }
3213
3214                         
3215                         return this;
3216                 }
3217
3218                 public override void Emit (EmitContext ec)
3219                 {
3220                         Report.Error (70, loc, "The event `" + Name + "' can only appear on the left hand side of += or -= (except on the defining type)");
3221                 }
3222
3223                 public void EmitAddOrRemove (EmitContext ec, Expression source)
3224                 {
3225                         BinaryDelegate source_del = (BinaryDelegate) source;
3226                         Expression handler = source_del.Right;
3227                         
3228                         Argument arg = new Argument (handler, Argument.AType.Expression);
3229                         ArrayList args = new ArrayList ();
3230                                 
3231                         args.Add (arg);
3232                         
3233                         if (source_del.IsAddition)
3234                                 Invocation.EmitCall (
3235                                         ec, false, IsStatic, instance_expr, add_accessor, args, loc);
3236                         else
3237                                 Invocation.EmitCall (
3238                                         ec, false, IsStatic, instance_expr, remove_accessor, args, loc);
3239                 }
3240         }
3241 }