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