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