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