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