* convert.cs (ObjectTypeToPrimitiveTypes): Added. Converts an
[mono.git] / mcs / bmcs / 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.WideningConversion (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.WideningStandardConversionExists (Convert.ConstantEC, c, target_type)){
980                                 Convert.Error_CannotWideningConversion (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                 /// <summary>
1344                 /// Converts a String to an equivalent SimpleName or a
1345                 /// MemberAccess expression
1346                 /// </summary>
1347
1348                 public static Expression StringToExpression (string name, Location loc)
1349                 {
1350                         int pos;
1351                         string left;
1352                         string right;
1353                         
1354                         Expression expr = null;
1355
1356                         pos = name.IndexOf('.');
1357                         while (pos != -1)
1358                         {
1359                                 left = name.Substring (0, pos);
1360                                 right = name.Substring (pos + 1);
1361
1362                                 if (expr == null)
1363                                         expr = new SimpleName (left, loc);
1364                                 else
1365                                         expr = new MemberAccess (expr, left, loc);
1366
1367                                 name = right;
1368                                 pos = name.IndexOf('.');
1369                         }
1370
1371                         if (expr == null)
1372                                 return new SimpleName (name, loc);
1373                         else
1374                                 return new MemberAccess (expr, name, loc);
1375
1376                 }
1377                 
1378                 //
1379                 // Converts `source' to an int, uint, long or ulong.
1380                 //
1381                 public Expression ExpressionToArrayArgument (EmitContext ec, Expression source, Location loc)
1382                 {
1383                         Expression target;
1384                         
1385                         bool old_checked = ec.CheckState;
1386                         ec.CheckState = true;
1387                         
1388                         target = Convert.WideningConversion (ec, source, TypeManager.int32_type, loc);
1389                         if (target == null){
1390                                 target = Convert.WideningConversion (ec, source, TypeManager.uint32_type, loc);
1391                                 if (target == null){
1392                                         target = Convert.WideningConversion (ec, source, TypeManager.int64_type, loc);
1393                                         if (target == null){
1394                                                 target = Convert.WideningConversion (ec, source, TypeManager.uint64_type, loc);
1395                                                 if (target == null)
1396                                                         Convert.Error_CannotWideningConversion (loc, source.Type, TypeManager.int32_type);
1397                                         }
1398                                 }
1399                         } 
1400                         ec.CheckState = old_checked;
1401
1402                         //
1403                         // Only positive constants are allowed at compile time
1404                         //
1405                         if (target is Constant){
1406                                 if (target is IntConstant){
1407                                         if (((IntConstant) target).Value < 0){
1408                                                 Error_NegativeArrayIndex (loc);
1409                                                 return null;
1410                                         }
1411                                 }
1412
1413                                 if (target is LongConstant){
1414                                         if (((LongConstant) target).Value < 0){
1415                                                 Error_NegativeArrayIndex (loc);
1416                                                 return null;
1417                                         }
1418                                 }
1419                                 
1420                         }
1421
1422                         return target;
1423                 }
1424                 
1425         }
1426
1427         /// <summary>
1428         ///   This is just a base class for expressions that can
1429         ///   appear on statements (invocations, object creation,
1430         ///   assignments, post/pre increment and decrement).  The idea
1431         ///   being that they would support an extra Emition interface that
1432         ///   does not leave a result on the stack.
1433         /// </summary>
1434         public abstract class ExpressionStatement : Expression {
1435
1436                 public virtual ExpressionStatement ResolveStatement (EmitContext ec)
1437                 {
1438                         Expression e = Resolve (ec);
1439                         if (e == null)
1440                                 return null;
1441
1442                         ExpressionStatement es = e as ExpressionStatement;
1443                         if (es == null)
1444                                 Error (201, "Only assignment, call, increment, decrement and new object " +
1445                                        "expressions can be used as a statement");
1446
1447                         return es;
1448                 }
1449
1450                 /// <summary>
1451                 ///   Requests the expression to be emitted in a `statement'
1452                 ///   context.  This means that no new value is left on the
1453                 ///   stack after invoking this method (constrasted with
1454                 ///   Emit that will always leave a value on the stack).
1455                 /// </summary>
1456                 public abstract void EmitStatement (EmitContext ec);
1457         }
1458
1459         /// <summary>
1460         ///   This kind of cast is used to encapsulate the child
1461         ///   whose type is child.Type into an expression that is
1462         ///   reported to return "return_type".  This is used to encapsulate
1463         ///   expressions which have compatible types, but need to be dealt
1464         ///   at higher levels with.
1465         ///
1466         ///   For example, a "byte" expression could be encapsulated in one
1467         ///   of these as an "unsigned int".  The type for the expression
1468         ///   would be "unsigned int".
1469         ///
1470         /// </summary>
1471         public class EmptyCast : Expression {
1472                 protected Expression child;
1473                 
1474                 public Expression Child {
1475                         get {
1476                                 return child;
1477                         }
1478                 }               
1479
1480                 public EmptyCast (Expression child, Type return_type)
1481                 {
1482                         eclass = child.eclass;
1483                         type = return_type;
1484                         this.child = child;
1485                 }
1486
1487                 public override Expression DoResolve (EmitContext ec)
1488                 {
1489                         // This should never be invoked, we are born in fully
1490                         // initialized state.
1491
1492                         return this;
1493                 }
1494
1495                 public override void Emit (EmitContext ec)
1496                 {
1497                         child.Emit (ec);
1498                 }
1499         }
1500
1501         
1502         /// <summary> 
1503         /// HelperMethodInvocation of methods or delegates. Used by the
1504         /// VB.NET compiler specifically to emit calls to the
1505         /// Microsoft.VisualBasic.CompilerServices helper routines
1506         /// </summary>
1507
1508         public class HelperMethodInvocation : Expression
1509         {
1510                 ArrayList args;
1511                 MethodInfo method;
1512                 
1513                 public HelperMethodInvocation (EmitContext ec,  Location l, Type return_type, MethodInfo method, params Expression [] exprs)
1514                 {
1515                         args = new ArrayList ();
1516                         foreach (Expression expr in exprs)
1517                                 args.Add (new Argument (expr, Argument.AType.Expression));
1518
1519
1520                         this.loc = l;
1521                         this.method = method;
1522                         type = return_type;
1523                         eclass = ExprClass.Value;
1524                 }
1525
1526                 public override Expression DoResolve (EmitContext ec)
1527                 {
1528                         return this;
1529                 }
1530
1531                 public override void Emit (EmitContext ec)
1532                 {
1533                         Invocation.EmitArguments (ec, method, args, false, null);
1534                         ec.ig.Emit (OpCodes.Call, method);
1535                 }
1536         }
1537
1538         /// <summary> 
1539         /// Implicit Creation of types. Used by the VB.NET compiler
1540         /// (in the context of Type Conversions) to emit calls to the
1541         /// appropriate constructors available in the core libraries.
1542         /// </summary>
1543
1544         public class ImplicitNew : Expression
1545         {
1546                 Expression child;
1547                 
1548                 public ImplicitNew (EmitContext ec, string ns, string name, Location l, params Expression [] exprs)
1549                 {
1550                         name = ns + "." + name;
1551                         ArrayList args = new ArrayList ();
1552                 
1553                         foreach (Expression expr in exprs)
1554                                 args.Add (new Argument (expr, Argument.AType.Expression));
1555
1556                         child = new New (StringToExpression (name, l), args, l).Resolve (ec);
1557                 }
1558
1559                 public override Expression DoResolve (EmitContext ec)
1560                 {
1561                         // This should never be invoked, we are born in fully
1562                         // initialized state.
1563
1564                         return this;
1565                 }
1566
1567                 public override void Emit (EmitContext ec)
1568                 {
1569                         child.Emit (ec);
1570                 }
1571         }
1572
1573         //
1574         // We need to special case this since an empty cast of
1575         // a NullLiteral is still a Constant
1576         //
1577         public class NullCast : Constant {
1578                 protected Expression child;
1579                                 
1580                 public NullCast (Expression child, Type return_type)
1581                 {
1582                         eclass = child.eclass;
1583                         type = return_type;
1584                         this.child = child;
1585                 }
1586
1587                 override public string AsString ()
1588                 {
1589                         return "null";
1590                 }
1591
1592                 public override object GetValue ()
1593                 {
1594                         return null;
1595                 }
1596
1597                 public override Expression DoResolve (EmitContext ec)
1598                 {
1599                         // This should never be invoked, we are born in fully
1600                         // initialized state.
1601
1602                         return this;
1603                 }
1604
1605                 public override void Emit (EmitContext ec)
1606                 {
1607                                 if (!type.IsValueType)
1608                                         child.Emit (ec);
1609                                 else {
1610                                         // VB.NET allows Nothing to be converted to any value type
1611
1612                                         ILGenerator ig = ec.ig;
1613
1614                                         ig.Emit (OpCodes.Ldtoken, type);
1615                                         ig.Emit (OpCodes.Call, TypeManager.system_type_get_type_from_handle);
1616                                         ig.Emit (OpCodes.Call, TypeManager.activator_create_instance);
1617                                         ig.Emit (OpCodes.Unbox, type);
1618                                         ig.Emit (OpCodes.Ldobj, type);
1619                                 }
1620                 }
1621
1622                 public override bool IsNegative {
1623                         get {
1624                                 return false;
1625                         }
1626                 }
1627         }
1628
1629
1630         /// <summary>
1631         ///  This class is used to wrap literals which belong inside Enums
1632         /// </summary>
1633         public class EnumConstant : Constant {
1634                 public Constant Child;
1635
1636                 public EnumConstant (Constant child, Type enum_type)
1637                 {
1638                         eclass = child.eclass;
1639                         this.Child = child;
1640                         type = enum_type;
1641                 }
1642                 
1643                 public override Expression DoResolve (EmitContext ec)
1644                 {
1645                         // This should never be invoked, we are born in fully
1646                         // initialized state.
1647
1648                         return this;
1649                 }
1650
1651                 public override void Emit (EmitContext ec)
1652                 {
1653                         Child.Emit (ec);
1654                 }
1655
1656                 public override object GetValue ()
1657                 {
1658                         return Child.GetValue ();
1659                 }
1660
1661                 public object GetValueAsEnumType ()
1662                 {
1663                         return System.Enum.ToObject (type, Child.GetValue ());
1664                 }
1665
1666                 //
1667                 // Converts from one of the valid underlying types for an enumeration
1668                 // (int32, uint32, int64, uint64, short, ushort, byte, sbyte) to
1669                 // one of the internal compiler literals: Int/UInt/Long/ULong Literals.
1670                 //
1671                 public Constant WidenToCompilerConstant ()
1672                 {
1673                         Type t = TypeManager.EnumToUnderlying (Child.Type);
1674                         object v = ((Constant) Child).GetValue ();;
1675                         
1676                         if (t == TypeManager.int32_type)
1677                                 return new IntConstant ((int) v);
1678                         if (t == TypeManager.uint32_type)
1679                                 return new UIntConstant ((uint) v);
1680                         if (t == TypeManager.int64_type)
1681                                 return new LongConstant ((long) v);
1682                         if (t == TypeManager.uint64_type)
1683                                 return new ULongConstant ((ulong) v);
1684                         if (t == TypeManager.short_type)
1685                                 return new ShortConstant ((short) v);
1686                         if (t == TypeManager.ushort_type)
1687                                 return new UShortConstant ((ushort) v);
1688                         if (t == TypeManager.byte_type)
1689                                 return new ByteConstant ((byte) v);
1690                         if (t == TypeManager.sbyte_type)
1691                                 return new SByteConstant ((sbyte) v);
1692
1693                         throw new Exception ("Invalid enumeration underlying type: " + t);
1694                 }
1695
1696                 //
1697                 // Extracts the value in the enumeration on its native representation
1698                 //
1699                 public object GetPlainValue ()
1700                 {
1701                         Type t = TypeManager.EnumToUnderlying (Child.Type);
1702                         object v = ((Constant) Child).GetValue ();;
1703                         
1704                         if (t == TypeManager.int32_type)
1705                                 return (int) v;
1706                         if (t == TypeManager.uint32_type)
1707                                 return (uint) v;
1708                         if (t == TypeManager.int64_type)
1709                                 return (long) v;
1710                         if (t == TypeManager.uint64_type)
1711                                 return (ulong) v;
1712                         if (t == TypeManager.short_type)
1713                                 return (short) v;
1714                         if (t == TypeManager.ushort_type)
1715                                 return (ushort) v;
1716                         if (t == TypeManager.byte_type)
1717                                 return (byte) v;
1718                         if (t == TypeManager.sbyte_type)
1719                                 return (sbyte) v;
1720
1721                         return null;
1722                 }
1723                 
1724                 public override string AsString ()
1725                 {
1726                         return Child.AsString ();
1727                 }
1728
1729                 public override DoubleConstant ConvertToDouble ()
1730                 {
1731                         return Child.ConvertToDouble ();
1732                 }
1733
1734                 public override FloatConstant ConvertToFloat ()
1735                 {
1736                         return Child.ConvertToFloat ();
1737                 }
1738
1739                 public override ULongConstant ConvertToULong ()
1740                 {
1741                         return Child.ConvertToULong ();
1742                 }
1743
1744                 public override LongConstant ConvertToLong ()
1745                 {
1746                         return Child.ConvertToLong ();
1747                 }
1748
1749                 public override UIntConstant ConvertToUInt ()
1750                 {
1751                         return Child.ConvertToUInt ();
1752                 }
1753
1754                 public override IntConstant ConvertToInt ()
1755                 {
1756                         return Child.ConvertToInt ();
1757                 }
1758                 
1759                 public override bool IsZeroInteger {
1760                         get { return Child.IsZeroInteger; }
1761                 }
1762
1763                 public override bool IsNegative {
1764                         get {
1765                                 return Child.IsNegative;
1766                         }
1767                 }
1768         }
1769
1770         /// <summary>
1771         ///   This kind of cast is used to encapsulate Value Types in objects.
1772         ///
1773         ///   The effect of it is to box the value type emitted by the previous
1774         ///   operation.
1775         /// </summary>
1776         public class BoxedCast : EmptyCast {
1777
1778                 public BoxedCast (Expression expr)
1779                         : base (expr, TypeManager.object_type) 
1780                 {
1781                         eclass = ExprClass.Value;
1782                 }
1783
1784                 public BoxedCast (Expression expr, Type target_type)
1785                         : base (expr, target_type)
1786                 {
1787                         eclass = ExprClass.Value;
1788                 }
1789                 
1790                 public override Expression DoResolve (EmitContext ec)
1791                 {
1792                         // This should never be invoked, we are born in fully
1793                         // initialized state.
1794
1795                         return this;
1796                 }
1797
1798                 public override void Emit (EmitContext ec)
1799                 {
1800                         base.Emit (ec);
1801                         
1802                         ec.ig.Emit (OpCodes.Box, child.Type);
1803                 }
1804         }
1805
1806         public class UnboxCast : EmptyCast {
1807                 public UnboxCast (Expression expr, Type return_type)
1808                         : base (expr, return_type)
1809                 {
1810                 }
1811
1812                 public override Expression DoResolve (EmitContext ec)
1813                 {
1814                         // This should never be invoked, we are born in fully
1815                         // initialized state.
1816
1817                         return this;
1818                 }
1819
1820                 public override void Emit (EmitContext ec)
1821                 {
1822                         Type t = type;
1823                         ILGenerator ig = ec.ig;
1824                         
1825                         base.Emit (ec);
1826                         if (t.IsGenericParameter)
1827                                 ig.Emit (OpCodes.Unbox_Any, t);
1828                         else {
1829                                 ig.Emit (OpCodes.Unbox, t);
1830
1831                                 LoadFromPtr (ig, t);
1832                         }
1833                 }
1834         }
1835         
1836         /// <summary>
1837         ///   This is used to perform explicit numeric conversions.
1838         ///
1839         ///   Explicit numeric conversions might trigger exceptions in a checked
1840         ///   context, so they should generate the conv.ovf opcodes instead of
1841         ///   conv opcodes.
1842         /// </summary>
1843         public class ConvCast : EmptyCast {
1844                 public enum Mode : byte {
1845                         I1_U1, I1_U2, I1_U4, I1_U8, I1_CH,
1846                         U1_I1, U1_CH,
1847                         I2_I1, I2_U1, I2_U2, I2_U4, I2_U8, I2_CH,
1848                         U2_I1, U2_U1, U2_I2, U2_CH,
1849                         I4_I1, I4_U1, I4_I2, I4_U2, I4_U4, I4_U8, I4_CH,
1850                         U4_I1, U4_U1, U4_I2, U4_U2, U4_I4, U4_CH,
1851                         I8_I1, I8_U1, I8_I2, I8_U2, I8_I4, I8_U4, I8_U8, I8_CH,
1852                         U8_I1, U8_U1, U8_I2, U8_U2, U8_I4, U8_U4, U8_I8, U8_CH,
1853                         CH_I1, CH_U1, CH_I2,
1854                         R4_I1, R4_U1, R4_I2, R4_U2, R4_I4, R4_U4, R4_I8, R4_U8, R4_CH,
1855                         R8_I1, R8_U1, R8_I2, R8_U2, R8_I4, R8_U4, R8_I8, R8_U8, R8_CH, R8_R4
1856                 }
1857
1858                 Mode mode;
1859                 bool checked_state;
1860                 
1861                 public ConvCast (EmitContext ec, Expression child, Type return_type, Mode m)
1862                         : base (child, return_type)
1863                 {
1864                         checked_state = ec.CheckState;
1865                         mode = m;
1866                 }
1867
1868                 public override Expression DoResolve (EmitContext ec)
1869                 {
1870                         // This should never be invoked, we are born in fully
1871                         // initialized state.
1872
1873                         return this;
1874                 }
1875
1876                 public override string ToString ()
1877                 {
1878                         return String.Format ("ConvCast ({0}, {1})", mode, child);
1879                 }
1880                 
1881                 public override void Emit (EmitContext ec)
1882                 {
1883                         ILGenerator ig = ec.ig;
1884                         
1885                         base.Emit (ec);
1886
1887                         if (checked_state){
1888                                 switch (mode){
1889                                 case Mode.I1_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1890                                 case Mode.I1_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1891                                 case Mode.I1_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1892                                 case Mode.I1_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1893                                 case Mode.I1_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1894
1895                                 case Mode.U1_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1896                                 case Mode.U1_CH: /* nothing */ break;
1897
1898                                 case Mode.I2_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1899                                 case Mode.I2_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1900                                 case Mode.I2_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1901                                 case Mode.I2_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1902                                 case Mode.I2_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1903                                 case Mode.I2_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1904
1905                                 case Mode.U2_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1906                                 case Mode.U2_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1907                                 case Mode.U2_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1908                                 case Mode.U2_CH: /* nothing */ break;
1909
1910                                 case Mode.I4_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1911                                 case Mode.I4_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1912                                 case Mode.I4_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1913                                 case Mode.I4_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1914                                 case Mode.I4_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1915                                 case Mode.I4_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1916                                 case Mode.I4_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1917
1918                                 case Mode.U4_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1919                                 case Mode.U4_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1920                                 case Mode.U4_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1921                                 case Mode.U4_U2: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1922                                 case Mode.U4_I4: ig.Emit (OpCodes.Conv_Ovf_I4_Un); break;
1923                                 case Mode.U4_CH: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1924
1925                                 case Mode.I8_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1926                                 case Mode.I8_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1927                                 case Mode.I8_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1928                                 case Mode.I8_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1929                                 case Mode.I8_I4: ig.Emit (OpCodes.Conv_Ovf_I4); break;
1930                                 case Mode.I8_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1931                                 case Mode.I8_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1932                                 case Mode.I8_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1933
1934                                 case Mode.U8_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1935                                 case Mode.U8_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1936                                 case Mode.U8_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1937                                 case Mode.U8_U2: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1938                                 case Mode.U8_I4: ig.Emit (OpCodes.Conv_Ovf_I4_Un); break;
1939                                 case Mode.U8_U4: ig.Emit (OpCodes.Conv_Ovf_U4_Un); break;
1940                                 case Mode.U8_I8: ig.Emit (OpCodes.Conv_Ovf_I8_Un); break;
1941                                 case Mode.U8_CH: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1942
1943                                 case Mode.CH_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1944                                 case Mode.CH_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1945                                 case Mode.CH_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1946
1947                                 case Mode.R4_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1948                                 case Mode.R4_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1949                                 case Mode.R4_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1950                                 case Mode.R4_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1951                                 case Mode.R4_I4: ig.Emit (OpCodes.Conv_Ovf_I4); break;
1952                                 case Mode.R4_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1953                                 case Mode.R4_I8: ig.Emit (OpCodes.Conv_Ovf_I8); break;
1954                                 case Mode.R4_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1955                                 case Mode.R4_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1956
1957                                 case Mode.R8_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1958                                 case Mode.R8_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1959                                 case Mode.R8_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1960                                 case Mode.R8_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1961                                 case Mode.R8_I4: ig.Emit (OpCodes.Conv_Ovf_I4); break;
1962                                 case Mode.R8_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1963                                 case Mode.R8_I8: ig.Emit (OpCodes.Conv_Ovf_I8); break;
1964                                 case Mode.R8_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1965                                 case Mode.R8_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1966                                 case Mode.R8_R4: ig.Emit (OpCodes.Conv_R4); break;
1967                                 }
1968                         } else {
1969                                 switch (mode){
1970                                 case Mode.I1_U1: ig.Emit (OpCodes.Conv_U1); break;
1971                                 case Mode.I1_U2: ig.Emit (OpCodes.Conv_U2); break;
1972                                 case Mode.I1_U4: ig.Emit (OpCodes.Conv_U4); break;
1973                                 case Mode.I1_U8: ig.Emit (OpCodes.Conv_I8); break;
1974                                 case Mode.I1_CH: ig.Emit (OpCodes.Conv_U2); break;
1975
1976                                 case Mode.U1_I1: ig.Emit (OpCodes.Conv_I1); break;
1977                                 case Mode.U1_CH: ig.Emit (OpCodes.Conv_U2); break;
1978
1979                                 case Mode.I2_I1: ig.Emit (OpCodes.Conv_I1); break;
1980                                 case Mode.I2_U1: ig.Emit (OpCodes.Conv_U1); break;
1981                                 case Mode.I2_U2: ig.Emit (OpCodes.Conv_U2); break;
1982                                 case Mode.I2_U4: ig.Emit (OpCodes.Conv_U4); break;
1983                                 case Mode.I2_U8: ig.Emit (OpCodes.Conv_I8); break;
1984                                 case Mode.I2_CH: ig.Emit (OpCodes.Conv_U2); break;
1985
1986                                 case Mode.U2_I1: ig.Emit (OpCodes.Conv_I1); break;
1987                                 case Mode.U2_U1: ig.Emit (OpCodes.Conv_U1); break;
1988                                 case Mode.U2_I2: ig.Emit (OpCodes.Conv_I2); break;
1989                                 case Mode.U2_CH: /* nothing */ break;
1990
1991                                 case Mode.I4_I1: ig.Emit (OpCodes.Conv_I1); break;
1992                                 case Mode.I4_U1: ig.Emit (OpCodes.Conv_U1); break;
1993                                 case Mode.I4_I2: ig.Emit (OpCodes.Conv_I2); break;
1994                                 case Mode.I4_U4: /* nothing */ break;
1995                                 case Mode.I4_U2: ig.Emit (OpCodes.Conv_U2); break;
1996                                 case Mode.I4_U8: ig.Emit (OpCodes.Conv_I8); break;
1997                                 case Mode.I4_CH: ig.Emit (OpCodes.Conv_U2); break;
1998
1999                                 case Mode.U4_I1: ig.Emit (OpCodes.Conv_I1); break;
2000                                 case Mode.U4_U1: ig.Emit (OpCodes.Conv_U1); break;
2001                                 case Mode.U4_I2: ig.Emit (OpCodes.Conv_I2); break;
2002                                 case Mode.U4_U2: ig.Emit (OpCodes.Conv_U2); break;
2003                                 case Mode.U4_I4: /* nothing */ break;
2004                                 case Mode.U4_CH: ig.Emit (OpCodes.Conv_U2); break;
2005
2006                                 case Mode.I8_I1: ig.Emit (OpCodes.Conv_I1); break;
2007                                 case Mode.I8_U1: ig.Emit (OpCodes.Conv_U1); break;
2008                                 case Mode.I8_I2: ig.Emit (OpCodes.Conv_I2); break;
2009                                 case Mode.I8_U2: ig.Emit (OpCodes.Conv_U2); break;
2010                                 case Mode.I8_I4: ig.Emit (OpCodes.Conv_I4); break;
2011                                 case Mode.I8_U4: ig.Emit (OpCodes.Conv_U4); break;
2012                                 case Mode.I8_U8: /* nothing */ break;
2013                                 case Mode.I8_CH: ig.Emit (OpCodes.Conv_U2); break;
2014
2015                                 case Mode.U8_I1: ig.Emit (OpCodes.Conv_I1); break;
2016                                 case Mode.U8_U1: ig.Emit (OpCodes.Conv_U1); break;
2017                                 case Mode.U8_I2: ig.Emit (OpCodes.Conv_I2); break;
2018                                 case Mode.U8_U2: ig.Emit (OpCodes.Conv_U2); break;
2019                                 case Mode.U8_I4: ig.Emit (OpCodes.Conv_I4); break;
2020                                 case Mode.U8_U4: ig.Emit (OpCodes.Conv_U4); break;
2021                                 case Mode.U8_I8: /* nothing */ break;
2022                                 case Mode.U8_CH: ig.Emit (OpCodes.Conv_U2); break;
2023
2024                                 case Mode.CH_I1: ig.Emit (OpCodes.Conv_I1); break;
2025                                 case Mode.CH_U1: ig.Emit (OpCodes.Conv_U1); break;
2026                                 case Mode.CH_I2: ig.Emit (OpCodes.Conv_I2); break;
2027
2028                                 case Mode.R4_I1: ig.Emit (OpCodes.Conv_I1); break;
2029                                 case Mode.R4_U1: ig.Emit (OpCodes.Conv_U1); break;
2030                                 case Mode.R4_I2: ig.Emit (OpCodes.Conv_I2); break;
2031                                 case Mode.R4_U2: ig.Emit (OpCodes.Conv_U2); break;
2032                                 case Mode.R4_I4: ig.Emit (OpCodes.Conv_I4); break;
2033                                 case Mode.R4_U4: ig.Emit (OpCodes.Conv_U4); break;
2034                                 case Mode.R4_I8: ig.Emit (OpCodes.Conv_I8); break;
2035                                 case Mode.R4_U8: ig.Emit (OpCodes.Conv_U8); break;
2036                                 case Mode.R4_CH: ig.Emit (OpCodes.Conv_U2); break;
2037
2038                                 case Mode.R8_I1: ig.Emit (OpCodes.Conv_I1); break;
2039                                 case Mode.R8_U1: ig.Emit (OpCodes.Conv_U1); break;
2040                                 case Mode.R8_I2: ig.Emit (OpCodes.Conv_I2); break;
2041                                 case Mode.R8_U2: ig.Emit (OpCodes.Conv_U2); break;
2042                                 case Mode.R8_I4: ig.Emit (OpCodes.Conv_I4); break;
2043                                 case Mode.R8_U4: ig.Emit (OpCodes.Conv_U4); break;
2044                                 case Mode.R8_I8: ig.Emit (OpCodes.Conv_I8); break;
2045                                 case Mode.R8_U8: ig.Emit (OpCodes.Conv_U8); break;
2046                                 case Mode.R8_CH: ig.Emit (OpCodes.Conv_U2); break;
2047                                 case Mode.R8_R4: ig.Emit (OpCodes.Conv_R4); break;
2048                                 }
2049                         }
2050                 }
2051         }
2052         
2053         public class OpcodeCast : EmptyCast {
2054                 OpCode op, op2;
2055                 bool second_valid;
2056                 
2057                 public OpcodeCast (Expression child, Type return_type, OpCode op)
2058                         : base (child, return_type)
2059                         
2060                 {
2061                         this.op = op;
2062                         second_valid = false;
2063                 }
2064
2065                 public OpcodeCast (Expression child, Type return_type, OpCode op, OpCode op2)
2066                         : base (child, return_type)
2067                         
2068                 {
2069                         this.op = op;
2070                         this.op2 = op2;
2071                         second_valid = true;
2072                 }
2073
2074                 public override Expression DoResolve (EmitContext ec)
2075                 {
2076                         // This should never be invoked, we are born in fully
2077                         // initialized state.
2078
2079                         return this;
2080                 }
2081
2082                 public override void Emit (EmitContext ec)
2083                 {
2084                         base.Emit (ec);
2085                         ec.ig.Emit (op);
2086
2087                         if (second_valid)
2088                                 ec.ig.Emit (op2);
2089                 }                       
2090         }
2091
2092         /// <summary>
2093         ///   This kind of cast is used to encapsulate a child and cast it
2094         ///   to the class requested
2095         /// </summary>
2096         public class ClassCast : EmptyCast {
2097                 public ClassCast (Expression child, Type return_type)
2098                         : base (child, return_type)
2099                         
2100                 {
2101                 }
2102
2103                 public override Expression DoResolve (EmitContext ec)
2104                 {
2105                         // This should never be invoked, we are born in fully
2106                         // initialized state.
2107
2108                         return this;
2109                 }
2110
2111                 public override void Emit (EmitContext ec)
2112                 {
2113                         base.Emit (ec);
2114
2115                         if (child.Type.IsGenericParameter)
2116                                 ec.ig.Emit (OpCodes.Box, child.Type);
2117
2118                         if (type.IsGenericParameter)
2119                                 ec.ig.Emit (OpCodes.Unbox_Any, type);
2120                         else
2121                                 ec.ig.Emit (OpCodes.Castclass, type);
2122                 }
2123         }
2124
2125         //
2126         // VB.NET specific
2127         //
2128         public class BooleanToNumericCast : EmptyCast {
2129                 OpCode op, op2;
2130                 
2131                 public BooleanToNumericCast (Expression child, Type return_type, OpCode op)
2132                         : base (child, return_type)
2133                         
2134                 {
2135                         this.op = op;
2136                 }
2137
2138                 public override Expression DoResolve (EmitContext ec)
2139                 {
2140                         // This should never be invoked, we are born in fully
2141                         // initialized state.
2142
2143                         return this;
2144                 }
2145
2146                 public override void Emit (EmitContext ec)
2147                 {
2148                         base.Emit (ec);
2149                         ec.ig.Emit (OpCodes.Ldc_I4_0);
2150                         ec.ig.Emit (OpCodes.Cgt_Un);
2151                         ec.ig.Emit (OpCodes.Neg);
2152                         ec.ig.Emit (op);
2153                 }                       
2154         }
2155
2156         //
2157         // VB.NET specific
2158         //
2159         public class NumericToBooleanCast : EmptyCast {
2160
2161                 Type expr_type; 
2162
2163                 public NumericToBooleanCast (Expression child, Type src_type)
2164                         : base (child, TypeManager.bool_type)
2165                         
2166                 {
2167                         expr_type = src_type;
2168                 }
2169
2170                 public override Expression DoResolve (EmitContext ec)
2171                 {
2172                         // This should never be invoked, we are born in fully
2173                         // initialized state.
2174
2175                         return this;
2176                 }
2177
2178                 public override void Emit (EmitContext ec)
2179                 {
2180                         base.Emit (ec);
2181
2182                         if (expr_type == TypeManager.byte_type ||
2183                                 expr_type == TypeManager.short_type ||
2184                                 expr_type == TypeManager.int32_type) {
2185                                 ec.ig.Emit (OpCodes.Ldc_I4_0);
2186                                 ec.ig.Emit (OpCodes.Cgt_Un);
2187                                 return;
2188                         }
2189
2190                         if (expr_type == TypeManager.int64_type) {
2191                                 ec.ig.Emit (OpCodes.Ldc_I8, (long) 0);
2192                                 ec.ig.Emit (OpCodes.Cgt_Un);
2193                                 return;
2194                         }
2195
2196                         if (expr_type == TypeManager.float_type)
2197                                 ec.ig.Emit (OpCodes.Ldc_R4, (float) 0);
2198                         else if (expr_type == TypeManager.double_type) 
2199                                 ec.ig.Emit (OpCodes.Ldc_R8, (double) 0);
2200                 
2201                         ec.ig.Emit (OpCodes.Ceq);
2202                         ec.ig.Emit (OpCodes.Ldc_I4_0);
2203                         ec.ig.Emit (OpCodes.Ceq);
2204                 }                       
2205         }
2206
2207         //
2208         // VB.NET specific
2209         //
2210         public class FloatingToFixedCast : ConvCast {
2211                 public FloatingToFixedCast (EmitContext ec, Expression child, Type return_type, Mode mode)
2212                         : base (ec, new HelperMethodInvocation (ec, child.Location, TypeManager.double_type, TypeManager.math_round_double,
2213                                                             (child.Type == TypeManager.float_type) ? 
2214                                                             new OpcodeCast (child, TypeManager.double_type, OpCodes.Conv_R8) : child), 
2215                                 return_type, mode)
2216                 {
2217                 }
2218         }
2219         
2220         
2221         /// <summary>
2222         ///   SimpleName expressions are formed of a single word and only happen at the beginning 
2223         ///   of a dotted-name.
2224         /// </summary>
2225         public class SimpleName : Expression {
2226                 public string Name;
2227                 public readonly TypeArguments Arguments;
2228
2229                 public SimpleName (string name, Location l)
2230                 {
2231                         Name = name;
2232                         loc = l;
2233                 }
2234
2235                 public SimpleName (string name, TypeArguments args, Location l)
2236                 {
2237                         Name = name;
2238                         Arguments = args;
2239                         loc = l;
2240                 }
2241
2242                 public static void Error_ObjectRefRequired (EmitContext ec, Location l, string name)
2243                 {
2244                         if (ec.IsFieldInitializer)
2245                                 Report.Error (
2246                                         236, l,
2247                                         "A field initializer cannot reference the non-static field, " +
2248                                         "method or property `"+name+"'");
2249                         else
2250                                 Report.Error (
2251                                         120, l,
2252                                         "An object reference is required " +
2253                                         "for the non-static field `"+name+"'");
2254                 }
2255                 
2256                 //
2257                 // Checks whether we are trying to access an instance
2258                 // property, method or field from a static body.
2259                 //
2260                 Expression MemberStaticCheck (EmitContext ec, Expression e)
2261                 {
2262                         if (e is IMemberExpr){
2263                                 IMemberExpr member = (IMemberExpr) e;
2264                                 
2265                                 if (!member.IsStatic){
2266                                         Error_ObjectRefRequired (ec, loc, Name);
2267                                         return null;
2268                                 }
2269                         }
2270
2271                         return e;
2272                 }
2273                 
2274                 public override Expression DoResolve (EmitContext ec)
2275                 {
2276                         return SimpleNameResolve (ec, null, false, false);
2277                 }
2278
2279                 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
2280                 {
2281                         return SimpleNameResolve (ec, right_side, false, false);
2282                 }
2283                 
2284
2285                 public Expression DoResolveAllowStatic (EmitContext ec, bool intermediate)
2286                 {
2287                         return SimpleNameResolve (ec, null, true, intermediate);
2288                 }
2289
2290                 public override FullNamedExpression ResolveAsTypeStep (EmitContext ec)
2291                 {
2292                         DeclSpace ds = ec.DeclSpace;
2293                         FullNamedExpression dt;
2294
2295                         dt = ds.LookupGeneric (Name, loc);
2296                         if (dt != null)
2297                                 return dt.ResolveAsTypeStep (ec);
2298
2299                         int errors = Report.Errors;
2300                         dt = ec.ResolvingTypeTree 
2301                                 ? ds.FindType (loc, Name)
2302                                 : ds.LookupType (Name, true, loc);
2303                         if (Report.Errors != errors)
2304                                 return null;
2305
2306                         return dt;
2307                 }
2308
2309                 Expression SimpleNameResolve (EmitContext ec, Expression right_side,
2310                                               bool allow_static, bool intermediate)
2311                 {
2312                         Expression e = DoSimpleNameResolve (ec, right_side, allow_static, intermediate);
2313                         if (e == null)
2314                                 return null;
2315
2316                         Block current_block = ec.CurrentBlock;
2317                         if (current_block != null){
2318                                 if (current_block.IsVariableNameUsedInChildBlock (Name)) {
2319                                         Report.Error (135, Location,
2320                                                       "'{0}' has a different meaning in a child block", Name);
2321                                         return null;
2322                                 }
2323                         }
2324
2325                         if (e.Type != null && e.Type.IsPointer && !ec.InUnsafe) {
2326                                 UnsafeError (loc);
2327                                 return null;
2328                         }
2329
2330                         return e;
2331                 }
2332
2333                 /// <remarks>
2334                 ///   7.5.2: Simple Names. 
2335                 ///
2336                 ///   Local Variables and Parameters are handled at
2337                 ///   parse time, so they never occur as SimpleNames.
2338                 ///
2339                 ///   The `allow_static' flag is used by MemberAccess only
2340                 ///   and it is used to inform us that it is ok for us to 
2341                 ///   avoid the static check, because MemberAccess might end
2342                 ///   up resolving the Name as a Type name and the access as
2343                 ///   a static type access.
2344                 ///
2345                 ///   ie: Type Type; .... { Type.GetType (""); }
2346                 ///
2347                 ///   Type is both an instance variable and a Type;  Type.GetType
2348                 ///   is the static method not an instance method of type.
2349                 /// </remarks>
2350                 Expression DoSimpleNameResolve (EmitContext ec, Expression right_side, bool allow_static, bool intermediate)
2351                 {
2352                         Expression e = null;
2353
2354                         //
2355                         // Stage 1: Performed by the parser (binding to locals or parameters).
2356                         //
2357                         Block current_block = ec.CurrentBlock;
2358                         if (current_block != null){
2359                                 LocalInfo vi = current_block.GetLocalInfo (Name);
2360                                 if (vi != null){
2361                                         Expression var;
2362                                         
2363                                         var = new LocalVariableReference (ec.CurrentBlock, Name, loc);
2364                                         
2365                                         if (right_side != null)
2366                                                 return var.ResolveLValue (ec, right_side);
2367                                         else
2368                                                 return var.Resolve (ec);
2369                                 }
2370
2371                                 ParameterReference pref = current_block.GetParameterReference (Name, loc);
2372                                 if (pref != null) {
2373                                         if (right_side != null)
2374                                                 return pref.ResolveLValue (ec, right_side);
2375                                         else
2376                                                 return pref.Resolve (ec);
2377                                 }
2378                         }
2379                         
2380                         //
2381                         // Stage 2: Lookup members 
2382                         //
2383
2384                         DeclSpace lookup_ds = ec.DeclSpace;
2385                         Type almost_matched_type = null;
2386                         ArrayList almost_matched = null;
2387                         do {
2388                                 if (lookup_ds.TypeBuilder == null)
2389                                         break;
2390
2391                                 e = MemberLookup (ec, lookup_ds.TypeBuilder, Name, loc);
2392                                 if (e != null)
2393                                         break;
2394
2395                                 if (almost_matched == null && almostMatchedMembers.Count > 0) {
2396                                         almost_matched_type = lookup_ds.TypeBuilder;
2397                                         almost_matched = (ArrayList) almostMatchedMembers.Clone ();
2398                                 }
2399
2400                                 lookup_ds =lookup_ds.Parent;
2401                         } while (lookup_ds != null);
2402
2403                         if (e == null && ec.ContainerType != null)
2404                                 e = MemberLookup (ec, ec.ContainerType, Name, loc);
2405
2406                         if (e == null) {
2407                                 if (almost_matched == null && almostMatchedMembers.Count > 0) {
2408                                         almost_matched_type = ec.ContainerType;
2409                                         almost_matched = (ArrayList) almostMatchedMembers.Clone ();
2410                                 }
2411                                 e = ResolveAsTypeStep (ec);
2412                         }
2413
2414                         if (e == null) {
2415                                 if (almost_matched != null)
2416                                         almostMatchedMembers = almost_matched;
2417                                 if (almost_matched_type == null)
2418                                         almost_matched_type = ec.ContainerType;
2419                                 MemberLookupFailed (ec, null, almost_matched_type, ((SimpleName) this).Name, ec.DeclSpace.Name, loc);
2420                                 return null;
2421                         }
2422
2423                         if (e is TypeExpr)
2424                                 return e;
2425
2426                         if (e is IMemberExpr) {
2427                                 e = MemberAccess.ResolveMemberAccess (ec, e, null, loc, this);
2428                                 if (e == null)
2429                                         return null;
2430
2431                                 IMemberExpr me = e as IMemberExpr;
2432                                 if (me == null)
2433                                         return e;
2434
2435                                 if (Arguments != null) {
2436                                         MethodGroupExpr mg = me as MethodGroupExpr;
2437                                         if (mg == null)
2438                                                 return null;
2439
2440                                         return mg.ResolveGeneric (ec, Arguments);
2441                                 }
2442
2443                                 // This fails if ResolveMemberAccess() was unable to decide whether
2444                                 // it's a field or a type of the same name.
2445                                 
2446                                 if (!me.IsStatic && (me.InstanceExpression == null))
2447                                         return e;
2448
2449                                 if (!me.IsStatic &&
2450                                     TypeManager.IsNestedFamilyAccessible (me.InstanceExpression.Type, me.DeclaringType) &&
2451                                     me.InstanceExpression.Type != me.DeclaringType &&
2452                                     !TypeManager.IsFamilyAccessible (me.InstanceExpression.Type, me.DeclaringType) &&
2453                                     (!intermediate || !MemberAccess.IdenticalNameAndTypeName (ec, this, e, loc))) {
2454                                         Error (38, "Cannot access nonstatic member `" + me.Name + "' of " +
2455                                                "outer type `" + me.DeclaringType + "' via nested type `" +
2456                                                me.InstanceExpression.Type + "'");
2457                                         return null;
2458                                 }
2459
2460                                 return (right_side != null)
2461                                         ? e.DoResolveLValue (ec, right_side)
2462                                         : e.DoResolve (ec);
2463                         }
2464
2465                         if (ec.IsStatic || ec.IsFieldInitializer){
2466                                 if (allow_static)
2467                                         return e;
2468
2469                                 return MemberStaticCheck (ec, e);
2470                         } else
2471                                 return e;
2472                 }
2473                 
2474                 public override void Emit (EmitContext ec)
2475                 {
2476                         //
2477                         // If this is ever reached, then we failed to
2478                         // find the name as a namespace
2479                         //
2480
2481                         Error (103, "The name `" + Name +
2482                                "' does not exist in the class `" +
2483                                ec.DeclSpace.Name + "'");
2484                 }
2485
2486                 public override string ToString ()
2487                 {
2488                         return Name;
2489                 }
2490         }
2491
2492         /// <summary>
2493         ///   Represents a namespace or a type.  The name of the class was inspired by
2494         ///   section 10.8.1 (Fully Qualified Names).
2495         /// </summary>
2496         public abstract class FullNamedExpression : Expression {
2497                 public override FullNamedExpression ResolveAsTypeStep (EmitContext ec)
2498                 {
2499                         return this;
2500                 }
2501
2502                 public abstract string FullName {
2503                         get;
2504                 }
2505         }
2506         
2507         /// <summary>
2508         ///   Fully resolved expression that evaluates to a type
2509         /// </summary>
2510         public abstract class TypeExpr : FullNamedExpression {
2511                 override public FullNamedExpression ResolveAsTypeStep (EmitContext ec)
2512                 {
2513                         TypeExpr t = DoResolveAsTypeStep (ec);
2514                         if (t == null)
2515                                 return null;
2516
2517                         eclass = ExprClass.Type;
2518                         return t;
2519                 }
2520
2521                 override public Expression DoResolve (EmitContext ec)
2522                 {
2523                         return ResolveAsTypeTerminal (ec);
2524                 }
2525
2526                 override public void Emit (EmitContext ec)
2527                 {
2528                         throw new Exception ("Should never be called");
2529                 }
2530
2531                 public virtual bool CheckAccessLevel (DeclSpace ds)
2532                 {
2533                         return ds.CheckAccessLevel (Type);
2534                 }
2535
2536                 public virtual bool AsAccessible (DeclSpace ds, int flags)
2537                 {
2538                         return ds.AsAccessible (Type, flags);
2539                 }
2540
2541                 public virtual bool IsClass {
2542                         get { return Type.IsClass; }
2543                 }
2544
2545                 public virtual bool IsValueType {
2546                         get { return Type.IsValueType; }
2547                 }
2548
2549                 public virtual bool IsInterface {
2550                         get { return Type.IsInterface; }
2551                 }
2552
2553                 public virtual bool IsSealed {
2554                         get { return Type.IsSealed; }
2555                 }
2556
2557                 public virtual bool CanInheritFrom ()
2558                 {
2559                         if (Type == TypeManager.enum_type ||
2560                             (Type == TypeManager.value_type && RootContext.StdLib) ||
2561                             Type == TypeManager.multicast_delegate_type ||
2562                             Type == TypeManager.delegate_type ||
2563                             Type == TypeManager.array_type)
2564                                 return false;
2565
2566                         return true;
2567                 }
2568
2569                 public virtual bool IsAttribute {
2570                         get {
2571                                 return Type == TypeManager.attribute_type ||
2572                                         Type.IsSubclassOf (TypeManager.attribute_type);
2573                         }
2574                 }
2575
2576                 protected abstract TypeExpr DoResolveAsTypeStep (EmitContext ec);
2577
2578                 public virtual Type ResolveType (EmitContext ec)
2579                 {
2580                         TypeExpr t = ResolveAsTypeTerminal (ec);
2581                         if (t == null)
2582                                 return null;
2583
2584                         return t.Type;
2585                 }
2586
2587                 public abstract string Name {
2588                         get;
2589                 }
2590
2591                 public override bool Equals (object obj)
2592                 {
2593                         TypeExpr tobj = obj as TypeExpr;
2594                         if (tobj == null)
2595                                 return false;
2596
2597                         return Type == tobj.Type;
2598                 }
2599
2600                 public override int GetHashCode ()
2601                 {
2602                         return Type.GetHashCode ();
2603                 }
2604                 
2605                 public override string ToString ()
2606                 {
2607                         return Name;
2608                 }
2609         }
2610
2611         public class TypeExpression : TypeExpr {
2612                 public TypeExpression (Type t, Location l)
2613                 {
2614                         Type = t;
2615                         eclass = ExprClass.Type;
2616                         loc = l;
2617                 }
2618
2619                 protected override TypeExpr DoResolveAsTypeStep (EmitContext ec)
2620                 {
2621                         return this;
2622                 }
2623
2624                 public override string Name {
2625                         get {
2626                                 return Type.ToString ();
2627                         }
2628                 }
2629
2630                 public override string FullName {
2631                         get {
2632                                 return Type.FullName != null ? Type.FullName : Type.Name;
2633                         }
2634                 }
2635         }
2636
2637         /// <summary>
2638         ///   Used to create types from a fully qualified name.  These are just used
2639         ///   by the parser to setup the core types.  A TypeLookupExpression is always
2640         ///   classified as a type.
2641         /// </summary>
2642         public class TypeLookupExpression : TypeExpr {
2643                 string name;
2644                 
2645                 public TypeLookupExpression (string name)
2646                 {
2647                         this.name = name;
2648                 }
2649
2650                 protected override TypeExpr DoResolveAsTypeStep (EmitContext ec)
2651                 {
2652                         if (type == null) {
2653                                 FullNamedExpression t = ec.DeclSpace.LookupType (name, false, Location.Null);
2654                                 if (t == null)
2655                                         return null;
2656                                 if (!(t is TypeExpr))
2657                                         return null;
2658                                 type = ((TypeExpr) t).ResolveType (ec);
2659                         }
2660
2661                         return this;
2662                 }
2663
2664                 public override string Name {
2665                         get {
2666                                 return name;
2667                         }
2668                 }
2669
2670                 public override string FullName {
2671                         get {
2672                                 return name;
2673                         }
2674                 }
2675         }
2676
2677         /// <summary>
2678         ///   Represents an "unbound generic type", ie. typeof (Foo<>).
2679         ///   See 14.5.11.
2680         /// </summary>
2681         public class UnboundTypeExpression : TypeLookupExpression {
2682                 public UnboundTypeExpression (string name)
2683                         : base (name)
2684                 { }
2685         }
2686
2687         public class TypeAliasExpression : TypeExpr {
2688                 FullNamedExpression alias;
2689                 TypeExpr texpr;
2690                 TypeArguments args;
2691                 string name;
2692
2693                 public TypeAliasExpression (FullNamedExpression alias, TypeArguments args, Location l)
2694                 {
2695                         this.alias = alias;
2696                         this.args = args;
2697                         loc = l;
2698
2699                         eclass = ExprClass.Type;
2700                         if (args != null)
2701                                 name = alias.FullName + "<" + args.ToString () + ">";
2702                         else
2703                                 name = alias.FullName;
2704                 }
2705
2706                 public override string Name {
2707                         get { return alias.FullName; }
2708                 }
2709
2710                 public override string FullName {
2711                         get { return name; }
2712                 }
2713
2714                 protected override TypeExpr DoResolveAsTypeStep (EmitContext ec)
2715                 {
2716                         texpr = alias.ResolveAsTypeTerminal (ec);
2717                         if (texpr == null)
2718                                 return null;
2719
2720                         Type type = texpr.Type;
2721                         int num_args = TypeManager.GetNumberOfTypeArguments (type);
2722
2723                         if (args != null) {
2724                                 if (num_args == 0) {
2725                                         Report.Error (308, loc,
2726                                                       "The non-generic type `{0}' cannot " +
2727                                                       "be used with type arguments.",
2728                                                       TypeManager.CSharpName (type));
2729                                         return null;
2730                                 }
2731
2732                                 ConstructedType ctype = new ConstructedType (type, args, loc);
2733                                 return ctype.ResolveAsTypeTerminal (ec);
2734                         } else if (num_args > 0) {
2735                                 Report.Error (305, loc,
2736                                               "Using the generic type `{0}' " +
2737                                               "requires {1} type arguments",
2738                                               TypeManager.GetFullName (type), num_args);
2739                                 return null;
2740                         }
2741
2742                         return new TypeExpression (type, loc);
2743                 }
2744
2745                 public override bool CheckAccessLevel (DeclSpace ds)
2746                 {
2747                         return texpr.CheckAccessLevel (ds);
2748                 }
2749
2750                 public override bool AsAccessible (DeclSpace ds, int flags)
2751                 {
2752                         return texpr.AsAccessible (ds, flags);
2753                 }
2754
2755                 public override bool IsClass {
2756                         get { return texpr.IsClass; }
2757                 }
2758
2759                 public override bool IsValueType {
2760                         get { return texpr.IsValueType; }
2761                 }
2762
2763                 public override bool IsInterface {
2764                         get { return texpr.IsInterface; }
2765                 }
2766
2767                 public override bool IsSealed {
2768                         get { return texpr.IsSealed; }
2769                 }
2770
2771                 public override bool IsAttribute {
2772                         get { return texpr.IsAttribute; }
2773                 }
2774         }
2775
2776         /// <summary>
2777         ///   MethodGroup Expression.
2778         ///  
2779         ///   This is a fully resolved expression that evaluates to a type
2780         /// </summary>
2781         public class MethodGroupExpr : Expression, IMemberExpr {
2782                 public MethodBase [] Methods;
2783                 Expression instance_expression = null;
2784                 bool is_explicit_impl = false;
2785                 bool has_type_arguments = false;
2786                 bool identical_type_name = false;
2787                 bool is_base;
2788                 
2789                 public MethodGroupExpr (MemberInfo [] mi, Location l)
2790                 {
2791                         Methods = new MethodBase [mi.Length];
2792                         mi.CopyTo (Methods, 0);
2793                         eclass = ExprClass.MethodGroup;
2794                         type = TypeManager.object_type;
2795                         loc = l;
2796                 }
2797
2798                 public MethodGroupExpr (ArrayList list, Location l)
2799                 {
2800                         Methods = new MethodBase [list.Count];
2801
2802                         try {
2803                                 list.CopyTo (Methods, 0);
2804                         } catch {
2805                                 foreach (MemberInfo m in list){
2806                                         if (!(m is MethodBase)){
2807                                                 Console.WriteLine ("Name " + m.Name);
2808                                                 Console.WriteLine ("Found a: " + m.GetType ().FullName);
2809                                         }
2810                                 }
2811                                 throw;
2812                         }
2813
2814                         loc = l;
2815                         eclass = ExprClass.MethodGroup;
2816                         type = TypeManager.object_type;
2817                 }
2818
2819                 public Type DeclaringType {
2820                         get {
2821                                 //
2822                                 // We assume that the top-level type is in the end
2823                                 //
2824                                 return Methods [Methods.Length - 1].DeclaringType;
2825                                 //return Methods [0].DeclaringType;
2826                         }
2827                 }
2828                 
2829                 //
2830                 // `A method group may have associated an instance expression' 
2831                 // 
2832                 public Expression InstanceExpression {
2833                         get {
2834                                 return instance_expression;
2835                         }
2836
2837                         set {
2838                                 instance_expression = value;
2839                         }
2840                 }
2841
2842                 public bool IsExplicitImpl {
2843                         get {
2844                                 return is_explicit_impl;
2845                         }
2846
2847                         set {
2848                                 is_explicit_impl = value;
2849                         }
2850                 }
2851
2852                 public bool HasTypeArguments {
2853                         get {
2854                                 return has_type_arguments;
2855                         }
2856
2857                         set {
2858                                 has_type_arguments = value;
2859                         }
2860                 }
2861
2862                 public bool IdenticalTypeName {
2863                         get {
2864                                 return identical_type_name;
2865                         }
2866
2867                         set {
2868                                 identical_type_name = value;
2869                         }
2870                 }
2871
2872                 public bool IsBase {
2873                         get {
2874                                 return is_base;
2875                         }
2876                         set {
2877                                 is_base = value;
2878                         }
2879                 }
2880
2881                 public string Name {
2882                         get {
2883                                 //return Methods [0].Name;
2884                                 return Methods [Methods.Length - 1].Name;
2885                         }
2886                 }
2887
2888                 public bool IsInstance {
2889                         get {
2890                                 foreach (MethodBase mb in Methods)
2891                                         if (!mb.IsStatic)
2892                                                 return true;
2893
2894                                 return false;
2895                         }
2896                 }
2897
2898                 public bool IsStatic {
2899                         get {
2900                                 foreach (MethodBase mb in Methods)
2901                                         if (mb.IsStatic)
2902                                                 return true;
2903
2904                                 return false;
2905                         }
2906                 }
2907                 
2908                 override public Expression DoResolve (EmitContext ec)
2909                 {
2910                         if (!IsInstance)
2911                                 instance_expression = null;
2912
2913                         if (instance_expression != null) {
2914                                 instance_expression = instance_expression.DoResolve (ec);
2915                                 if (instance_expression == null)
2916                                         return null;
2917                         }
2918
2919                         return this;
2920                 }
2921
2922                 public void ReportUsageError ()
2923                 {
2924                         Report.Error (654, loc, "Method `" + DeclaringType + "." +
2925                                       Name + "()' is referenced without parentheses");
2926                 }
2927
2928                 override public void Emit (EmitContext ec)
2929                 {
2930                         ReportUsageError ();
2931                 }
2932
2933                 bool RemoveMethods (bool keep_static)
2934                 {
2935                         ArrayList smethods = new ArrayList ();
2936
2937                         foreach (MethodBase mb in Methods){
2938                                 if (mb.IsStatic == keep_static)
2939                                         smethods.Add (mb);
2940                         }
2941
2942                         if (smethods.Count == 0)
2943                                 return false;
2944
2945                         Methods = new MethodBase [smethods.Count];
2946                         smethods.CopyTo (Methods, 0);
2947
2948                         return true;
2949                 }
2950                 
2951                 /// <summary>
2952                 ///   Removes any instance methods from the MethodGroup, returns
2953                 ///   false if the resulting set is empty.
2954                 /// </summary>
2955                 public bool RemoveInstanceMethods ()
2956                 {
2957                         return RemoveMethods (true);
2958                 }
2959
2960                 /// <summary>
2961                 ///   Removes any static methods from the MethodGroup, returns
2962                 ///   false if the resulting set is empty.
2963                 /// </summary>
2964                 public bool RemoveStaticMethods ()
2965                 {
2966                         return RemoveMethods (false);
2967                 }
2968
2969                 public Expression ResolveGeneric (EmitContext ec, TypeArguments args)
2970                 {
2971                         if (args.Resolve (ec) == false)
2972                                 return null;
2973
2974                         Type[] atypes = args.Arguments;
2975
2976                         int first_count = 0;
2977                         MethodInfo first = null;
2978
2979                         ArrayList list = new ArrayList ();
2980                         foreach (MethodBase mb in Methods) {
2981                                 MethodInfo mi = mb as MethodInfo;
2982                                 if ((mi == null) || !mi.HasGenericParameters)
2983                                         continue;
2984
2985                                 Type[] gen_params = mi.GetGenericArguments ();
2986
2987                                 if (first == null) {
2988                                         first = mi;
2989                                         first_count = gen_params.Length;
2990                                 }
2991
2992                                 if (gen_params.Length != atypes.Length)
2993                                         continue;
2994
2995                                 list.Add (mi.BindGenericParameters (atypes));
2996                         }
2997
2998                         if (list.Count > 0) {
2999                                 MethodGroupExpr new_mg = new MethodGroupExpr (list, Location);
3000                                 new_mg.InstanceExpression = InstanceExpression;
3001                                 new_mg.HasTypeArguments = true;
3002                                 return new_mg;
3003                         }
3004
3005                         if (first != null)
3006                                 Report.Error (
3007                                         305, loc, "Using the generic method `{0}' " +
3008                                         "requires {1} type arguments", Name,
3009                                         first_count);
3010                         else
3011                                 Report.Error (
3012                                         308, loc, "The non-generic method `{0}' " +
3013                                         "cannot be used with type arguments", Name);
3014
3015                         return null;
3016                 }
3017         }
3018
3019         /// <summary>
3020         ///   Fully resolved expression that evaluates to a Field
3021         /// </summary>
3022         public class FieldExpr : Expression, IAssignMethod, IMemoryLocation, IMemberExpr, IVariable {
3023                 public readonly FieldInfo FieldInfo;
3024                 Expression instance_expr;
3025                 VariableInfo variable_info;
3026                 
3027                 LocalTemporary temp;
3028                 bool prepared;
3029                 bool is_field_initializer;
3030                 
3031                 public FieldExpr (FieldInfo fi, Location l)
3032                 {
3033                         FieldInfo = fi;
3034                         eclass = ExprClass.Variable;
3035                         type = TypeManager.TypeToCoreType (fi.FieldType);
3036                         loc = l;
3037                 }
3038
3039                 public string Name {
3040                         get {
3041                                 return FieldInfo.Name;
3042                         }
3043                 }
3044
3045                 public bool IsInstance {
3046                         get {
3047                                 return !FieldInfo.IsStatic;
3048                         }
3049                 }
3050
3051                 public bool IsStatic {
3052                         get {
3053                                 return FieldInfo.IsStatic;
3054                         }
3055                 }
3056
3057                 public Type DeclaringType {
3058                         get {
3059                                 return FieldInfo.DeclaringType;
3060                         }
3061                 }
3062
3063                 public Expression InstanceExpression {
3064                         get {
3065                                 return instance_expr;
3066                         }
3067
3068                         set {
3069                                 instance_expr = value;
3070                         }
3071                 }
3072
3073                 public bool IsFieldInitializer {
3074                         get {
3075                                 return is_field_initializer;
3076                         }
3077
3078                         set {
3079                                 is_field_initializer = value;
3080                         }
3081                 }
3082
3083                 public VariableInfo VariableInfo {
3084                         get {
3085                                 return variable_info;
3086                         }
3087                 }
3088
3089                 override public Expression DoResolve (EmitContext ec)
3090                 {
3091                         if (!FieldInfo.IsStatic){
3092                                 if (instance_expr == null){
3093                                         //
3094                                         // This can happen when referencing an instance field using
3095                                         // a fully qualified type expression: TypeName.InstanceField = xxx
3096                                         // 
3097                                         SimpleName.Error_ObjectRefRequired (ec, loc, FieldInfo.Name);
3098                                         return null;
3099                                 }
3100
3101                                 // Resolve the field's instance expression while flow analysis is turned
3102                                 // off: when accessing a field "a.b", we must check whether the field
3103                                 // "a.b" is initialized, not whether the whole struct "a" is initialized.
3104                                 instance_expr = instance_expr.Resolve (ec, ResolveFlags.VariableOrValue |
3105                                                                        ResolveFlags.DisableFlowAnalysis);
3106                                 if (instance_expr == null)
3107                                         return null;
3108                         }
3109
3110                         ObsoleteAttribute oa;
3111                         FieldBase f = TypeManager.GetField (FieldInfo);
3112                         if (f != null) {
3113                                 oa = f.GetObsoleteAttribute (f.Parent);
3114                                 if (oa != null)
3115                                         AttributeTester.Report_ObsoleteMessage (oa, f.GetSignatureForError (), loc);
3116                                 // To be sure that type is external because we do not register generated fields
3117                         } else if (!(FieldInfo.DeclaringType is TypeBuilder)) {                                
3118                                 oa = AttributeTester.GetMemberObsoleteAttribute (FieldInfo);
3119                                 if (oa != null)
3120                                         AttributeTester.Report_ObsoleteMessage (oa, TypeManager.GetFullNameSignature (FieldInfo), loc);
3121                         }
3122
3123                         if (ec.CurrentAnonymousMethod != null){
3124                                 if (!FieldInfo.IsStatic){
3125                                         if (ec.TypeContainer is Struct){
3126                                                 Report.Error (1673, loc, "Can not reference instance variables in anonymous methods hosted in structs");
3127                                                 return null;
3128                                         }
3129                                         ec.CaptureField (this);
3130                                 } 
3131                         }
3132                         
3133                         // If the instance expression is a local variable or parameter.
3134                         IVariable var = instance_expr as IVariable;
3135                         if ((var == null) || (var.VariableInfo == null))
3136                                 return this;
3137
3138                         VariableInfo vi = var.VariableInfo;
3139                         if (!vi.IsFieldAssigned (ec, FieldInfo.Name, loc))
3140                                 return null;
3141
3142                         variable_info = vi.GetSubStruct (FieldInfo.Name);
3143                         return this;
3144                 }
3145
3146                 void Report_AssignToReadonly (bool is_instance)
3147                 {
3148                         string msg;
3149                         
3150                         if (is_instance)
3151                                 msg = "Readonly field can not be assigned outside " +
3152                                 "of constructor or variable initializer";
3153                         else
3154                                 msg = "A static readonly field can only be assigned in " +
3155                                 "a static constructor";
3156
3157                         Report.Error (is_instance ? 191 : 198, loc, msg);
3158                 }
3159                 
3160                 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
3161                 {
3162                         IVariable var = instance_expr as IVariable;
3163                         if ((var != null) && (var.VariableInfo != null))
3164                                 var.VariableInfo.SetFieldAssigned (ec, FieldInfo.Name);
3165
3166                         Expression e = DoResolve (ec);
3167
3168                         if (e == null)
3169                                 return null;
3170
3171                         if (!FieldInfo.IsStatic && (instance_expr.Type.IsValueType && !(instance_expr is IMemoryLocation))) {
3172                                 // FIXME: Provide better error reporting.
3173                                 Error (1612, "Cannot modify expression because it is not a variable.");
3174                                 return null;
3175                         }
3176
3177                         if (!FieldInfo.IsInitOnly)
3178                                 return this;
3179
3180                         FieldBase fb = TypeManager.GetField (FieldInfo);
3181                         if (fb != null)
3182                                 fb.SetAssigned ();
3183
3184                         //
3185                         // InitOnly fields can only be assigned in constructors
3186                         //
3187
3188                         if (ec.IsConstructor){
3189                                 if (IsStatic && !ec.IsStatic)
3190                                         Report_AssignToReadonly (false);
3191
3192                                 Type ctype;
3193                                 if (!is_field_initializer &&
3194                                     (ec.TypeContainer.CurrentType != null))
3195                                         ctype = ec.TypeContainer.CurrentType;
3196                                 else
3197                                         ctype = ec.ContainerType;
3198
3199                                 if (TypeManager.IsEqual (ctype, FieldInfo.DeclaringType))
3200                                         return this;
3201                         }
3202
3203                         Report_AssignToReadonly (!IsStatic);
3204                         
3205                         return null;
3206                 }
3207
3208                 public override void CheckMarshallByRefAccess (Type container)
3209                 {
3210                         if (!IsStatic && Type.IsValueType && !container.IsSubclassOf (TypeManager.mbr_type) && DeclaringType.IsSubclassOf (TypeManager.mbr_type)) {
3211                                 Report.SymbolRelatedToPreviousError (DeclaringType);
3212                                 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);
3213                         }
3214                 }
3215
3216                 public bool VerifyFixed (bool is_expression)
3217                 {
3218                         IVariable variable = instance_expr as IVariable;
3219                         if ((variable == null) || !variable.VerifyFixed (true))
3220                                 return false;
3221
3222                         return true;
3223                 }
3224                 
3225                 public void Emit (EmitContext ec, bool leave_copy)
3226                 {
3227                         ILGenerator ig = ec.ig;
3228                         bool is_volatile = false;
3229
3230                         if (FieldInfo is FieldBuilder){
3231                                 FieldBase f = TypeManager.GetField (FieldInfo);
3232                                 if (f != null){
3233                                         if ((f.ModFlags & Modifiers.VOLATILE) != 0)
3234                                                 is_volatile = true;
3235                                         
3236                                         f.status |= Field.Status.USED;
3237                                 }
3238                         } 
3239                         
3240                         if (FieldInfo.IsStatic){
3241                                 if (is_volatile)
3242                                         ig.Emit (OpCodes.Volatile);
3243                                 
3244                                 ig.Emit (OpCodes.Ldsfld, FieldInfo);
3245                         } else {
3246                                 if (!prepared)
3247                                         EmitInstance (ec);
3248
3249                                 if (is_volatile)
3250                                         ig.Emit (OpCodes.Volatile);
3251
3252                                 ig.Emit (OpCodes.Ldfld, FieldInfo);
3253                         }
3254
3255                         if (leave_copy) {
3256                                 ec.ig.Emit (OpCodes.Dup);
3257                                 if (!FieldInfo.IsStatic) {
3258                                         temp = new LocalTemporary (ec, this.Type);
3259                                         temp.Store (ec);
3260                                 }
3261                         }
3262                 }
3263
3264                 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
3265                 {
3266                         FieldAttributes fa = FieldInfo.Attributes;
3267                         bool is_static = (fa & FieldAttributes.Static) != 0;
3268                         bool is_readonly = (fa & FieldAttributes.InitOnly) != 0;
3269                         ILGenerator ig = ec.ig;
3270                         prepared = prepare_for_load;
3271
3272                         if (is_readonly && !ec.IsConstructor){
3273                                 Report_AssignToReadonly (!is_static);
3274                                 return;
3275                         }
3276
3277                         if (!is_static) {
3278                                 EmitInstance (ec);
3279                                 if (prepare_for_load)
3280                                         ig.Emit (OpCodes.Dup);
3281                         }
3282
3283                         source.Emit (ec);
3284                         if (leave_copy) {
3285                                 ec.ig.Emit (OpCodes.Dup);
3286                                 if (!FieldInfo.IsStatic) {
3287                                         temp = new LocalTemporary (ec, this.Type);
3288                                         temp.Store (ec);
3289                                 }
3290                         }
3291
3292                         if (FieldInfo is FieldBuilder){
3293                                 FieldBase f = TypeManager.GetField (FieldInfo);
3294                                 if (f != null){
3295                                         if ((f.ModFlags & Modifiers.VOLATILE) != 0)
3296                                                 ig.Emit (OpCodes.Volatile);
3297                                         
3298                                         f.status |= Field.Status.ASSIGNED;
3299                                 }
3300                         } 
3301
3302                         if (is_static)
3303                                 ig.Emit (OpCodes.Stsfld, FieldInfo);
3304                         else 
3305                                 ig.Emit (OpCodes.Stfld, FieldInfo);
3306                         
3307                         if (temp != null)
3308                                 temp.Emit (ec);
3309                 }
3310
3311                 void EmitInstance (EmitContext ec)
3312                 {
3313                         if (instance_expr.Type.IsValueType) {
3314                                 if (instance_expr is IMemoryLocation) {
3315                                         ((IMemoryLocation) instance_expr).AddressOf (ec, AddressOp.LoadStore);
3316                                 } else {
3317                                         LocalTemporary t = new LocalTemporary (ec, instance_expr.Type);
3318                                         instance_expr.Emit (ec);
3319                                         t.Store (ec);
3320                                         t.AddressOf (ec, AddressOp.Store);
3321                                 }
3322                         } else
3323                                 instance_expr.Emit (ec);
3324                 }
3325
3326                 public override void Emit (EmitContext ec)
3327                 {
3328                         Emit (ec, false);
3329                 }
3330
3331                 public void AddressOf (EmitContext ec, AddressOp mode)
3332                 {
3333                         ILGenerator ig = ec.ig;
3334                         
3335                         if (FieldInfo is FieldBuilder){
3336                                 FieldBase f = TypeManager.GetField (FieldInfo);
3337                                 if (f != null){
3338                                         if ((f.ModFlags & Modifiers.VOLATILE) != 0){
3339                                                 Error (676, "volatile variable: can not take its address, or pass as ref/out parameter");
3340                                                 return;
3341                                         }
3342                                         
3343                                         if ((mode & AddressOp.Store) != 0)
3344                                                 f.status |= Field.Status.ASSIGNED;
3345                                         if ((mode & AddressOp.Load) != 0)
3346                                                 f.status |= Field.Status.USED;
3347                                 }
3348                         } 
3349
3350                         //
3351                         // Handle initonly fields specially: make a copy and then
3352                         // get the address of the copy.
3353                         //
3354                         bool need_copy;
3355                         if (FieldInfo.IsInitOnly){
3356                                 need_copy = true;
3357                                 if (ec.IsConstructor){
3358                                         if (FieldInfo.IsStatic){
3359                                                 if (ec.IsStatic)
3360                                                         need_copy = false;
3361                                         } else
3362                                                 need_copy = false;
3363                                 }
3364                         } else
3365                                 need_copy = false;
3366                         
3367                         if (need_copy){
3368                                 LocalBuilder local;
3369                                 Emit (ec);
3370                                 local = ig.DeclareLocal (type);
3371                                 ig.Emit (OpCodes.Stloc, local);
3372                                 ig.Emit (OpCodes.Ldloca, local);
3373                                 return;
3374                         }
3375
3376
3377                         if (FieldInfo.IsStatic){
3378                                 ig.Emit (OpCodes.Ldsflda, FieldInfo);
3379                         } else {
3380                                 EmitInstance (ec);
3381                                 ig.Emit (OpCodes.Ldflda, FieldInfo);
3382                         }
3383                 }
3384         }
3385
3386         //
3387         // A FieldExpr whose address can not be taken
3388         //
3389         public class FieldExprNoAddress : FieldExpr, IMemoryLocation {
3390                 public FieldExprNoAddress (FieldInfo fi, Location loc) : base (fi, loc)
3391                 {
3392                 }
3393                 
3394                 public new void AddressOf (EmitContext ec, AddressOp mode)
3395                 {
3396                         Report.Error (-215, "Report this: Taking the address of a remapped parameter not supported");
3397                 }
3398         }
3399         
3400         /// <summary>
3401         ///   Expression that evaluates to a Property.  The Assign class
3402         ///   might set the `Value' expression if we are in an assignment.
3403         ///
3404         ///   This is not an LValue because we need to re-write the expression, we
3405         ///   can not take data from the stack and store it.  
3406         /// </summary>
3407         public class PropertyExpr : ExpressionStatement, IAssignMethod, IMemberExpr {
3408                 public readonly PropertyInfo PropertyInfo;
3409
3410                 //
3411                 // This is set externally by the  `BaseAccess' class
3412                 //
3413                 public bool IsBase;
3414                 MethodInfo getter, setter;
3415                 bool is_static;
3416                 
3417                 Expression instance_expr;
3418                 LocalTemporary temp;
3419                 bool prepared;
3420
3421                 internal static PtrHashtable AccessorTable = new PtrHashtable (); 
3422
3423                 public PropertyExpr (EmitContext ec, PropertyInfo pi, Location l)
3424                 {
3425                         PropertyInfo = pi;
3426                         eclass = ExprClass.PropertyAccess;
3427                         is_static = false;
3428                         loc = l;
3429
3430                         type = TypeManager.TypeToCoreType (pi.PropertyType);
3431
3432                         ResolveAccessors (ec);
3433                 }
3434
3435                 public string Name {
3436                         get {
3437                                 return PropertyInfo.Name;
3438                         }
3439                 }
3440
3441                 public bool IsInstance {
3442                         get {
3443                                 return !is_static;
3444                         }
3445                 }
3446
3447                 public bool IsStatic {
3448                         get {
3449                                 return is_static;
3450                         }
3451                 }
3452                 
3453                 public Type DeclaringType {
3454                         get {
3455                                 return PropertyInfo.DeclaringType;
3456                         }
3457                 }
3458
3459                 //
3460                 // The instance expression associated with this expression
3461                 //
3462                 public Expression InstanceExpression {
3463                         set {
3464                                 instance_expr = value;
3465                         }
3466
3467                         get {
3468                                 return instance_expr;
3469                         }
3470                 }
3471
3472                 public bool VerifyAssignable ()
3473                 {
3474                         if (setter == null) {
3475                                 Report.Error (200, loc, 
3476                                               "The property `" + PropertyInfo.Name +
3477                                               "' can not be assigned to, as it has not set accessor");
3478                                 return false;
3479                         }
3480
3481                         return true;
3482                 }
3483
3484                 void FindAccessors (Type invocation_type)
3485                 {
3486                         BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic |
3487                                 BindingFlags.Static | BindingFlags.Instance |
3488                                 BindingFlags.DeclaredOnly;
3489
3490                         Type current = PropertyInfo.DeclaringType;
3491                         for (; current != null; current = current.BaseType) {
3492                                 MemberInfo[] group = TypeManager.MemberLookup (
3493                                         invocation_type, invocation_type, current,
3494                                         MemberTypes.Property, flags, PropertyInfo.Name, null);
3495
3496                                 if (group == null)
3497                                         continue;
3498
3499                                 if (group.Length != 1)
3500                                         // Oooops, can this ever happen ?
3501                                         return;
3502
3503                                 PropertyInfo pi = (PropertyInfo) group [0];
3504
3505                                 if (getter == null)
3506                                         getter = pi.GetGetMethod (true);
3507
3508                                 if (setter == null)
3509                                         setter = pi.GetSetMethod (true);
3510
3511                                 MethodInfo accessor = getter != null ? getter : setter;
3512
3513                                 if (!accessor.IsVirtual)
3514                                         return;
3515                         }
3516                 }
3517
3518                 //
3519                 // We also perform the permission checking here, as the PropertyInfo does not
3520                 // hold the information for the accessibility of its setter/getter
3521                 //
3522                 void ResolveAccessors (EmitContext ec)
3523                 {
3524                         FindAccessors (ec.ContainerType);
3525
3526                         if (getter != null) {
3527                                 AccessorTable [getter] = PropertyInfo;
3528                                 is_static = getter.IsStatic;
3529                         }
3530
3531                         if (setter != null) {
3532                                 AccessorTable [setter] = PropertyInfo;
3533                                 is_static = setter.IsStatic;
3534                         }
3535                 }
3536
3537                 bool InstanceResolve (EmitContext ec, bool must_do_cs1540_check)
3538                 {
3539                         if ((instance_expr == null) && ec.IsStatic && !is_static) {
3540                                 SimpleName.Error_ObjectRefRequired (ec, loc, PropertyInfo.Name);
3541                                 return false;
3542                         }
3543
3544                         if (instance_expr != null) {
3545                                 instance_expr = instance_expr.DoResolve (ec);
3546                                 if (instance_expr == null)
3547                                         return false;
3548
3549                                 instance_expr.CheckMarshallByRefAccess (ec.ContainerType);
3550                         }
3551
3552                         if (must_do_cs1540_check && (instance_expr != null)) {
3553                                 if ((instance_expr.Type != ec.ContainerType) &&
3554                                     ec.ContainerType.IsSubclassOf (instance_expr.Type)) {
3555                                         Report.Error (1540, loc, "Cannot access protected member `" +
3556                                                       PropertyInfo.DeclaringType + "." + PropertyInfo.Name + 
3557                                                       "' via a qualifier of type `" +
3558                                                       TypeManager.CSharpName (instance_expr.Type) +
3559                                                       "'; the qualifier must be of type `" +
3560                                                       TypeManager.CSharpName (ec.ContainerType) +
3561                                                       "' (or derived from it)");
3562                                         return false;
3563                                 }
3564                         }
3565
3566                         return true;
3567                 }
3568                 
3569                 override public Expression DoResolve (EmitContext ec)
3570                 {
3571                         if (getter != null){
3572                                 if (TypeManager.GetArgumentTypes (getter).Length != 0){
3573                                         Report.Error (
3574                                                 117, loc, "`{0}' does not contain a " +
3575                                                 "definition for `{1}'.", getter.DeclaringType,
3576                                                 Name);
3577                                         return null;
3578                                 }
3579                         }
3580
3581                         if (getter == null){
3582                                 //
3583                                 // The following condition happens if the PropertyExpr was
3584                                 // created, but is invalid (ie, the property is inaccessible),
3585                                 // and we did not want to embed the knowledge about this in
3586                                 // the caller routine.  This only avoids double error reporting.
3587                                 //
3588                                 if (setter == null)
3589                                         return null;
3590                                 
3591                                 Report.Error (154, loc, 
3592                                               "The property `" + PropertyInfo.Name +
3593                                               "' can not be used in " +
3594                                               "this context because it lacks a get accessor");
3595                                 return null;
3596                         } 
3597
3598                         bool must_do_cs1540_check;
3599                         if (!IsAccessorAccessible (ec.ContainerType, getter, out must_do_cs1540_check)) {
3600                                 Report.Error (122, loc, "'{0}.get' is inaccessible due to its protection level", PropertyInfo.Name);
3601                                 return null;
3602                         }
3603
3604                         if (!InstanceResolve (ec, must_do_cs1540_check))
3605                                 return null;
3606
3607                         //
3608                         // Only base will allow this invocation to happen.
3609                         //
3610                         if (IsBase && getter.IsAbstract){
3611                                 Report.Error (205, loc, "Cannot call an abstract base property: " +
3612                                               PropertyInfo.DeclaringType + "." +PropertyInfo.Name);
3613                                 return null;
3614                         }
3615
3616                         return this;
3617                 }
3618
3619                 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
3620                 {
3621                         if (setter == null){
3622                                 //
3623                                 // The following condition happens if the PropertyExpr was
3624                                 // created, but is invalid (ie, the property is inaccessible),
3625                                 // and we did not want to embed the knowledge about this in
3626                                 // the caller routine.  This only avoids double error reporting.
3627                                 //
3628                                 if (getter == null)
3629                                         return null;
3630                                 
3631                                 Report.Error (154, loc, 
3632                                               "The property `" + PropertyInfo.Name +
3633                                               "' can not be used in " +
3634                                               "this context because it lacks a set accessor");
3635                                 return null;
3636                         }
3637
3638                         if (TypeManager.GetArgumentTypes (setter).Length != 1){
3639                                 Report.Error (
3640                                         117, loc, "`{0}' does not contain a " +
3641                                         "definition for `{1}'.", getter.DeclaringType,
3642                                         Name);
3643                                 return null;
3644                         }
3645
3646                         bool must_do_cs1540_check;
3647                         if (!IsAccessorAccessible (ec.ContainerType, setter, out must_do_cs1540_check)) {
3648                                 Report.Error (122, loc, "'{0}.set' is inaccessible due to its protection level", PropertyInfo.Name);
3649                                 return null;
3650                         }
3651
3652                         if (!InstanceResolve (ec, must_do_cs1540_check))
3653                                 return null;
3654                         
3655                         //
3656                         // Only base will allow this invocation to happen.
3657                         //
3658                         if (IsBase && setter.IsAbstract){
3659                                 Report.Error (205, loc, "Cannot call an abstract base property: " +
3660                                               PropertyInfo.DeclaringType + "." +PropertyInfo.Name);
3661                                 return null;
3662                         }
3663
3664                         //
3665                         // Check that we are not making changes to a temporary memory location
3666                         //
3667                         if (instance_expr != null && instance_expr.Type.IsValueType && !(instance_expr is IMemoryLocation)) {
3668                                 // FIXME: Provide better error reporting.
3669                                 Error (1612, "Cannot modify expression because it is not a variable.");
3670                                 return null;
3671                         }
3672
3673                         return this;
3674                 }
3675
3676
3677                 
3678                 public override void Emit (EmitContext ec)
3679                 {
3680                         Emit (ec, false);
3681                 }
3682                 
3683                 void EmitInstance (EmitContext ec)
3684                 {
3685                         if (is_static)
3686                                 return;
3687
3688                         if (instance_expr.Type.IsValueType) {
3689                                 if (instance_expr is IMemoryLocation) {
3690                                         ((IMemoryLocation) instance_expr).AddressOf (ec, AddressOp.LoadStore);
3691                                 } else {
3692                                         LocalTemporary t = new LocalTemporary (ec, instance_expr.Type);
3693                                         instance_expr.Emit (ec);
3694                                         t.Store (ec);
3695                                         t.AddressOf (ec, AddressOp.Store);
3696                                 }
3697                         } else
3698                                 instance_expr.Emit (ec);
3699                         
3700                         if (prepared)
3701                                 ec.ig.Emit (OpCodes.Dup);
3702                 }
3703
3704                 
3705                 public void Emit (EmitContext ec, bool leave_copy)
3706                 {
3707                         if (!prepared)
3708                                 EmitInstance (ec);
3709                         
3710                         //
3711                         // Special case: length of single dimension array property is turned into ldlen
3712                         //
3713                         if ((getter == TypeManager.system_int_array_get_length) ||
3714                             (getter == TypeManager.int_array_get_length)){
3715                                 Type iet = instance_expr.Type;
3716
3717                                 //
3718                                 // System.Array.Length can be called, but the Type does not
3719                                 // support invoking GetArrayRank, so test for that case first
3720                                 //
3721                                 if (iet != TypeManager.array_type && (iet.GetArrayRank () == 1)) {
3722                                         ec.ig.Emit (OpCodes.Ldlen);
3723                                         ec.ig.Emit (OpCodes.Conv_I4);
3724                                         return;
3725                                 }
3726                         }
3727
3728                         Invocation.EmitCall (ec, IsBase, IsStatic, new EmptyAddressOf (), getter, null, loc);
3729                         
3730                         if (!leave_copy)
3731                                 return;
3732                         
3733                         ec.ig.Emit (OpCodes.Dup);
3734                         if (!is_static) {
3735                                 temp = new LocalTemporary (ec, this.Type);
3736                                 temp.Store (ec);
3737                         }
3738                 }
3739
3740                 //
3741                 // Implements the IAssignMethod interface for assignments
3742                 //
3743                 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
3744                 {
3745                         prepared = prepare_for_load;
3746                         
3747                         EmitInstance (ec);
3748
3749                         source.Emit (ec);
3750                         if (leave_copy) {
3751                                 ec.ig.Emit (OpCodes.Dup);
3752                                 if (!is_static) {
3753                                         temp = new LocalTemporary (ec, this.Type);
3754                                         temp.Store (ec);
3755                                 }
3756                         }
3757                         
3758                         ArrayList args = new ArrayList (1);
3759                         args.Add (new Argument (new EmptyAddressOf (), Argument.AType.Expression));
3760                         
3761                         Invocation.EmitCall (ec, IsBase, IsStatic, new EmptyAddressOf (), setter, args, loc);
3762                         
3763                         if (temp != null)
3764                                 temp.Emit (ec);
3765                 }
3766
3767                 override public void EmitStatement (EmitContext ec)
3768                 {
3769                         Emit (ec);
3770                         ec.ig.Emit (OpCodes.Pop);
3771                 }
3772         }
3773
3774         /// <summary>
3775         ///   Fully resolved expression that evaluates to an Event
3776         /// </summary>
3777         public class EventExpr : Expression, IMemberExpr {
3778                 public readonly EventInfo EventInfo;
3779                 Expression instance_expr;
3780
3781                 bool is_static;
3782                 MethodInfo add_accessor, remove_accessor;
3783                 
3784                 public EventExpr (EventInfo ei, Location loc)
3785                 {
3786                         EventInfo = ei;
3787                         this.loc = loc;
3788                         eclass = ExprClass.EventAccess;
3789
3790                         add_accessor = TypeManager.GetAddMethod (ei);
3791                         remove_accessor = TypeManager.GetRemoveMethod (ei);
3792                         
3793                         if (add_accessor.IsStatic || remove_accessor.IsStatic)
3794                                 is_static = true;
3795
3796                         if (EventInfo is MyEventBuilder){
3797                                 MyEventBuilder eb = (MyEventBuilder) EventInfo;
3798                                 type = eb.EventType;
3799                                 eb.SetUsed ();
3800                         } else
3801                                 type = EventInfo.EventHandlerType;
3802                 }
3803
3804                 public string Name {
3805                         get {
3806                                 return EventInfo.Name;
3807                         }
3808                 }
3809
3810                 public bool IsInstance {
3811                         get {
3812                                 return !is_static;
3813                         }
3814                 }
3815
3816                 public bool IsStatic {
3817                         get {
3818                                 return is_static;
3819                         }
3820                 }
3821
3822                 public Type DeclaringType {
3823                         get {
3824                                 return EventInfo.DeclaringType;
3825                         }
3826                 }
3827
3828                 public Expression InstanceExpression {
3829                         get {
3830                                 return instance_expr;
3831                         }
3832
3833                         set {
3834                                 instance_expr = value;
3835                         }
3836                 }
3837
3838                 bool InstanceResolve (EmitContext ec, bool must_do_cs1540_check)
3839                 {
3840                         if ((instance_expr == null) && ec.IsStatic && !is_static) {
3841                                 SimpleName.Error_ObjectRefRequired (ec, loc, EventInfo.Name);
3842                                 return false;
3843                         }
3844
3845                         if (instance_expr != null) {
3846                                 instance_expr = instance_expr.DoResolve (ec);
3847                                 if (instance_expr == null)
3848                                         return false;
3849                         }
3850
3851                         //
3852                         // This is using the same mechanism as the CS1540 check in PropertyExpr.
3853                         // However, in the Event case, we reported a CS0122 instead.
3854                         //
3855                         if (must_do_cs1540_check && (instance_expr != null)) {
3856                                 if ((instance_expr.Type != ec.ContainerType) &&
3857                                         ec.ContainerType.IsSubclassOf (instance_expr.Type)) {
3858                                         Report.Error (122, loc, "'{0}' is inaccessible due to its protection level",
3859                                                 DeclaringType.Name + "." + EventInfo.Name);
3860
3861                                         return false;
3862                                 }
3863                         }
3864
3865                         return true;
3866                 }
3867
3868                 public override Expression DoResolve (EmitContext ec)
3869                 {
3870                         if (instance_expr != null) {
3871                                 instance_expr = instance_expr.DoResolve (ec);
3872                                 if (instance_expr == null)
3873                                         return null;
3874                         }
3875
3876                         bool must_do_cs1540_check;
3877                         if (!(IsAccessorAccessible (ec.ContainerType, add_accessor, out must_do_cs1540_check)
3878                                     && IsAccessorAccessible (ec.ContainerType, remove_accessor, out must_do_cs1540_check))) {
3879                                 
3880                                Report.Error (122, loc, "'{0}' is inaccessible due to its protection level",
3881                                                DeclaringType.Name + "." + EventInfo.Name);
3882                                return null;
3883                         }
3884
3885                         if (!InstanceResolve (ec, must_do_cs1540_check))
3886                                 return null;
3887                         
3888                         return this;
3889                 }               
3890
3891                 public override void Emit (EmitContext ec)
3892                 {
3893                         if (instance_expr is This)
3894                                 Report.Error (79, loc, "The event `{0}' can only appear on the left hand side of += or -=, try calling the actual delegate", Name);
3895                         else
3896                                 Report.Error (70, loc, "The event `{0}' can only appear on the left hand side of += or -= "+
3897                                               "(except on the defining type)", Name);
3898                 }
3899
3900                 public void EmitAddOrRemove (EmitContext ec, Expression source)
3901                 {
3902                         BinaryDelegate source_del = (BinaryDelegate) source;
3903                         Expression handler = source_del.Right;
3904                         
3905                         Argument arg = new Argument (handler, Argument.AType.Expression);
3906                         ArrayList args = new ArrayList ();
3907                                 
3908                         args.Add (arg);
3909                         
3910                         if (source_del.IsAddition)
3911                                 Invocation.EmitCall (
3912                                         ec, false, IsStatic, instance_expr, add_accessor, args, loc);
3913                         else
3914                                 Invocation.EmitCall (
3915                                         ec, false, IsStatic, instance_expr, remove_accessor, args, loc);
3916                 }
3917         }
3918 }