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