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