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