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