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