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