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