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