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