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