Standardized Mainsoft ConstraintCollection tests.
[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         /// <summary>
1386         ///     This is a numeric cast to a Decimal
1387         /// </summary>
1388         public class CastToDecimal : EmptyCast {
1389
1390                 MethodInfo conversion_operator;
1391
1392                 public CastToDecimal (EmitContext ec, Expression child)
1393                         : this (ec, child, false)
1394                 {
1395                 }
1396
1397                 public CastToDecimal (EmitContext ec, Expression child, bool find_explicit)
1398                         : base (child, TypeManager.decimal_type)
1399                 {
1400                         conversion_operator = GetConversionOperator (ec, find_explicit);
1401
1402                         if (conversion_operator == null)
1403                                 Convert.Error_CannotImplicitConversion (loc, child.Type, type);
1404                 }
1405
1406                 // Returns the implicit operator that converts from
1407                 // 'child.Type' to System.Decimal.
1408                 MethodInfo GetConversionOperator (EmitContext ec, bool find_explicit)
1409                 {
1410                         string operator_name = "op_Implicit";
1411
1412                         if (find_explicit)
1413                                 operator_name = "op_Explicit";
1414                         
1415                         MethodGroupExpr opers = Expression.MethodLookup (
1416                                 ec, type, operator_name, loc) as MethodGroupExpr;
1417
1418                         if (opers == null)
1419                                 Convert.Error_CannotImplicitConversion (loc, child.Type, type);
1420                         
1421                         foreach (MethodInfo oper in opers.Methods) {
1422                                 ParameterData pd = TypeManager.GetParameterData (oper);
1423
1424                                 if (pd.ParameterType (0) == child.Type && oper.ReturnType == type)
1425                                         return oper;
1426                         }
1427
1428                         return null;
1429                 }
1430                 public override void Emit (EmitContext ec)
1431                 {
1432                         ILGenerator ig = ec.ig;
1433                         child.Emit (ec);
1434
1435                         ig.Emit (OpCodes.Call, conversion_operator);
1436                 }
1437         }
1438         /// <summary>
1439         ///     This is an explicit numeric cast from a Decimal
1440         /// </summary>
1441         public class CastFromDecimal : EmptyCast
1442         {
1443                 MethodInfo conversion_operator;
1444                 public CastFromDecimal (EmitContext ec, Expression child, Type return_type)
1445                         : base (child, return_type)
1446                 {
1447                         if (child.Type != TypeManager.decimal_type)
1448                                 throw new InternalErrorException (
1449                                         "The expected type is Decimal, instead it is " + child.Type.FullName);
1450
1451                         conversion_operator = GetConversionOperator (ec);
1452                         if (conversion_operator == null)
1453                                 Convert.Error_CannotImplicitConversion (loc, child.Type, type);
1454                 }
1455
1456                 // Returns the explicit operator that converts from an
1457                 // express of type System.Decimal to 'type'.
1458                 MethodInfo GetConversionOperator (EmitContext ec)
1459                 {                               
1460                         MethodGroupExpr opers = Expression.MethodLookup (
1461                                 ec, child.Type, "op_Explicit", loc) as MethodGroupExpr;
1462
1463                         if (opers == null)
1464                                 Convert.Error_CannotImplicitConversion (loc, child.Type, type);
1465                         
1466                         foreach (MethodInfo oper in opers.Methods) {
1467                                 ParameterData pd = TypeManager.GetParameterData (oper);
1468
1469                                 if (pd.ParameterType (0) == child.Type && oper.ReturnType == type)
1470                                         return oper;
1471                         }
1472
1473                         return null;
1474                 }
1475                 public override void Emit (EmitContext ec)
1476                 {
1477                         ILGenerator ig = ec.ig;
1478                         child.Emit (ec);
1479
1480                         ig.Emit (OpCodes.Call, conversion_operator);
1481                 }
1482         }
1483
1484         //
1485         // We need to special case this since an empty cast of
1486         // a NullLiteral is still a Constant
1487         //
1488         public class NullCast : Constant {
1489                 protected Expression child;
1490                                 
1491                 public NullCast (Expression child, Type return_type)
1492                 {
1493                         eclass = child.eclass;
1494                         type = return_type;
1495                         this.child = child;
1496                 }
1497
1498                 override public string AsString ()
1499                 {
1500                         return "null";
1501                 }
1502
1503                 public override object GetValue ()
1504                 {
1505                         return null;
1506                 }
1507
1508                 public override Expression DoResolve (EmitContext ec)
1509                 {
1510                         // This should never be invoked, we are born in fully
1511                         // initialized state.
1512
1513                         return this;
1514                 }
1515
1516                 public override void Emit (EmitContext ec)
1517                 {
1518                         child.Emit (ec);
1519                 }
1520
1521                 public override bool IsDefaultValue {
1522                         get {
1523                                 throw new NotImplementedException ();
1524                         }
1525                 }
1526
1527                 public override bool IsNegative {
1528                         get {
1529                                 return false;
1530                         }
1531                 }
1532         }
1533
1534
1535         /// <summary>
1536         ///  This class is used to wrap literals which belong inside Enums
1537         /// </summary>
1538         public class EnumConstant : Constant {
1539                 public Constant Child;
1540
1541                 public EnumConstant (Constant child, Type enum_type)
1542                 {
1543                         eclass = child.eclass;
1544                         this.Child = child;
1545                         type = enum_type;
1546                 }
1547                 
1548                 public override Expression DoResolve (EmitContext ec)
1549                 {
1550                         // This should never be invoked, we are born in fully
1551                         // initialized state.
1552
1553                         return this;
1554                 }
1555
1556                 public override void Emit (EmitContext ec)
1557                 {
1558                         Child.Emit (ec);
1559                 }
1560
1561                 public override object GetValue ()
1562                 {
1563                         return Child.GetValue ();
1564                 }
1565
1566                 public object GetValueAsEnumType ()
1567                 {
1568                         return System.Enum.ToObject (type, Child.GetValue ());
1569                 }
1570
1571                 //
1572                 // Converts from one of the valid underlying types for an enumeration
1573                 // (int32, uint32, int64, uint64, short, ushort, byte, sbyte) to
1574                 // one of the internal compiler literals: Int/UInt/Long/ULong Literals.
1575                 //
1576                 public Constant WidenToCompilerConstant ()
1577                 {
1578                         Type t = TypeManager.EnumToUnderlying (Child.Type);
1579                         object v = ((Constant) Child).GetValue ();;
1580                         
1581                         if (t == TypeManager.int32_type)
1582                                 return new IntConstant ((int) v);
1583                         if (t == TypeManager.uint32_type)
1584                                 return new UIntConstant ((uint) v);
1585                         if (t == TypeManager.int64_type)
1586                                 return new LongConstant ((long) v);
1587                         if (t == TypeManager.uint64_type)
1588                                 return new ULongConstant ((ulong) v);
1589                         if (t == TypeManager.short_type)
1590                                 return new ShortConstant ((short) v);
1591                         if (t == TypeManager.ushort_type)
1592                                 return new UShortConstant ((ushort) v);
1593                         if (t == TypeManager.byte_type)
1594                                 return new ByteConstant ((byte) v);
1595                         if (t == TypeManager.sbyte_type)
1596                                 return new SByteConstant ((sbyte) v);
1597
1598                         throw new Exception ("Invalid enumeration underlying type: " + t);
1599                 }
1600
1601                 //
1602                 // Extracts the value in the enumeration on its native representation
1603                 //
1604                 public object GetPlainValue ()
1605                 {
1606                         Type t = TypeManager.EnumToUnderlying (Child.Type);
1607                         object v = ((Constant) Child).GetValue ();;
1608                         
1609                         if (t == TypeManager.int32_type)
1610                                 return (int) v;
1611                         if (t == TypeManager.uint32_type)
1612                                 return (uint) v;
1613                         if (t == TypeManager.int64_type)
1614                                 return (long) v;
1615                         if (t == TypeManager.uint64_type)
1616                                 return (ulong) v;
1617                         if (t == TypeManager.short_type)
1618                                 return (short) v;
1619                         if (t == TypeManager.ushort_type)
1620                                 return (ushort) v;
1621                         if (t == TypeManager.byte_type)
1622                                 return (byte) v;
1623                         if (t == TypeManager.sbyte_type)
1624                                 return (sbyte) v;
1625
1626                         return null;
1627                 }
1628                 
1629                 public override string AsString ()
1630                 {
1631                         return Child.AsString ();
1632                 }
1633
1634                 public override DoubleConstant ConvertToDouble ()
1635                 {
1636                         return Child.ConvertToDouble ();
1637                 }
1638
1639                 public override FloatConstant ConvertToFloat ()
1640                 {
1641                         return Child.ConvertToFloat ();
1642                 }
1643
1644                 public override ULongConstant ConvertToULong ()
1645                 {
1646                         return Child.ConvertToULong ();
1647                 }
1648
1649                 public override LongConstant ConvertToLong ()
1650                 {
1651                         return Child.ConvertToLong ();
1652                 }
1653
1654                 public override UIntConstant ConvertToUInt ()
1655                 {
1656                         return Child.ConvertToUInt ();
1657                 }
1658
1659                 public override IntConstant ConvertToInt ()
1660                 {
1661                         return Child.ConvertToInt ();
1662                 }
1663
1664                 public override bool IsDefaultValue {
1665                         get {
1666                                 return Child.IsDefaultValue;
1667                         }
1668                 }
1669
1670                 public override bool IsZeroInteger {
1671                         get { return Child.IsZeroInteger; }
1672                 }
1673
1674                 public override bool IsNegative {
1675                         get {
1676                                 return Child.IsNegative;
1677                         }
1678                 }
1679         }
1680
1681         /// <summary>
1682         ///   This kind of cast is used to encapsulate Value Types in objects.
1683         ///
1684         ///   The effect of it is to box the value type emitted by the previous
1685         ///   operation.
1686         /// </summary>
1687         public class BoxedCast : EmptyCast {
1688
1689                 public BoxedCast (Expression expr)
1690                         : base (expr, TypeManager.object_type) 
1691                 {
1692                         eclass = ExprClass.Value;
1693                 }
1694
1695                 public BoxedCast (Expression expr, Type target_type)
1696                         : base (expr, target_type)
1697                 {
1698                         eclass = ExprClass.Value;
1699                 }
1700                 
1701                 public override Expression DoResolve (EmitContext ec)
1702                 {
1703                         // This should never be invoked, we are born in fully
1704                         // initialized state.
1705
1706                         return this;
1707                 }
1708
1709                 public override void Emit (EmitContext ec)
1710                 {
1711                         base.Emit (ec);
1712                         
1713                         ec.ig.Emit (OpCodes.Box, child.Type);
1714                 }
1715         }
1716
1717         public class UnboxCast : EmptyCast {
1718                 public UnboxCast (Expression expr, Type return_type)
1719                         : base (expr, return_type)
1720                 {
1721                 }
1722
1723                 public override Expression DoResolve (EmitContext ec)
1724                 {
1725                         // This should never be invoked, we are born in fully
1726                         // initialized state.
1727
1728                         return this;
1729                 }
1730
1731                 public override void Emit (EmitContext ec)
1732                 {
1733                         Type t = type;
1734                         ILGenerator ig = ec.ig;
1735                         
1736                         base.Emit (ec);
1737                         ig.Emit (OpCodes.Unbox, t);
1738
1739                         LoadFromPtr (ig, t);
1740                 }
1741         }
1742         
1743         /// <summary>
1744         ///   This is used to perform explicit numeric conversions.
1745         ///
1746         ///   Explicit numeric conversions might trigger exceptions in a checked
1747         ///   context, so they should generate the conv.ovf opcodes instead of
1748         ///   conv opcodes.
1749         /// </summary>
1750         public class ConvCast : EmptyCast {
1751                 public enum Mode : byte {
1752                         I1_U1, I1_U2, I1_U4, I1_U8, I1_CH,
1753                         U1_I1, U1_CH,
1754                         I2_I1, I2_U1, I2_U2, I2_U4, I2_U8, I2_CH,
1755                         U2_I1, U2_U1, U2_I2, U2_CH,
1756                         I4_I1, I4_U1, I4_I2, I4_U2, I4_U4, I4_U8, I4_CH,
1757                         U4_I1, U4_U1, U4_I2, U4_U2, U4_I4, U4_CH,
1758                         I8_I1, I8_U1, I8_I2, I8_U2, I8_I4, I8_U4, I8_U8, I8_CH,
1759                         U8_I1, U8_U1, U8_I2, U8_U2, U8_I4, U8_U4, U8_I8, U8_CH,
1760                         CH_I1, CH_U1, CH_I2,
1761                         R4_I1, R4_U1, R4_I2, R4_U2, R4_I4, R4_U4, R4_I8, R4_U8, R4_CH,
1762                         R8_I1, R8_U1, R8_I2, R8_U2, R8_I4, R8_U4, R8_I8, R8_U8, R8_CH, R8_R4
1763                 }
1764
1765                 Mode mode;
1766                 bool checked_state;
1767                 
1768                 public ConvCast (EmitContext ec, Expression child, Type return_type, Mode m)
1769                         : base (child, return_type)
1770                 {
1771                         checked_state = ec.CheckState;
1772                         mode = m;
1773                 }
1774
1775                 public override Expression DoResolve (EmitContext ec)
1776                 {
1777                         // This should never be invoked, we are born in fully
1778                         // initialized state.
1779
1780                         return this;
1781                 }
1782
1783                 public override string ToString ()
1784                 {
1785                         return String.Format ("ConvCast ({0}, {1})", mode, child);
1786                 }
1787                 
1788                 public override void Emit (EmitContext ec)
1789                 {
1790                         ILGenerator ig = ec.ig;
1791                         
1792                         base.Emit (ec);
1793
1794                         if (checked_state){
1795                                 switch (mode){
1796                                 case Mode.I1_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1797                                 case Mode.I1_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1798                                 case Mode.I1_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1799                                 case Mode.I1_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1800                                 case Mode.I1_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1801
1802                                 case Mode.U1_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1803                                 case Mode.U1_CH: /* nothing */ break;
1804
1805                                 case Mode.I2_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1806                                 case Mode.I2_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1807                                 case Mode.I2_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1808                                 case Mode.I2_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1809                                 case Mode.I2_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1810                                 case Mode.I2_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1811
1812                                 case Mode.U2_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1813                                 case Mode.U2_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1814                                 case Mode.U2_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1815                                 case Mode.U2_CH: /* nothing */ break;
1816
1817                                 case Mode.I4_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1818                                 case Mode.I4_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1819                                 case Mode.I4_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1820                                 case Mode.I4_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1821                                 case Mode.I4_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1822                                 case Mode.I4_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1823                                 case Mode.I4_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1824
1825                                 case Mode.U4_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1826                                 case Mode.U4_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1827                                 case Mode.U4_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1828                                 case Mode.U4_U2: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1829                                 case Mode.U4_I4: ig.Emit (OpCodes.Conv_Ovf_I4_Un); break;
1830                                 case Mode.U4_CH: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1831
1832                                 case Mode.I8_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1833                                 case Mode.I8_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1834                                 case Mode.I8_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1835                                 case Mode.I8_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1836                                 case Mode.I8_I4: ig.Emit (OpCodes.Conv_Ovf_I4); break;
1837                                 case Mode.I8_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1838                                 case Mode.I8_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1839                                 case Mode.I8_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1840
1841                                 case Mode.U8_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1842                                 case Mode.U8_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1843                                 case Mode.U8_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1844                                 case Mode.U8_U2: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1845                                 case Mode.U8_I4: ig.Emit (OpCodes.Conv_Ovf_I4_Un); break;
1846                                 case Mode.U8_U4: ig.Emit (OpCodes.Conv_Ovf_U4_Un); break;
1847                                 case Mode.U8_I8: ig.Emit (OpCodes.Conv_Ovf_I8_Un); break;
1848                                 case Mode.U8_CH: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1849
1850                                 case Mode.CH_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1851                                 case Mode.CH_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1852                                 case Mode.CH_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1853
1854                                 case Mode.R4_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1855                                 case Mode.R4_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1856                                 case Mode.R4_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1857                                 case Mode.R4_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1858                                 case Mode.R4_I4: ig.Emit (OpCodes.Conv_Ovf_I4); break;
1859                                 case Mode.R4_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1860                                 case Mode.R4_I8: ig.Emit (OpCodes.Conv_Ovf_I8); break;
1861                                 case Mode.R4_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1862                                 case Mode.R4_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1863
1864                                 case Mode.R8_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1865                                 case Mode.R8_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1866                                 case Mode.R8_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1867                                 case Mode.R8_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1868                                 case Mode.R8_I4: ig.Emit (OpCodes.Conv_Ovf_I4); break;
1869                                 case Mode.R8_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1870                                 case Mode.R8_I8: ig.Emit (OpCodes.Conv_Ovf_I8); break;
1871                                 case Mode.R8_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1872                                 case Mode.R8_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1873                                 case Mode.R8_R4: ig.Emit (OpCodes.Conv_R4); break;
1874                                 }
1875                         } else {
1876                                 switch (mode){
1877                                 case Mode.I1_U1: ig.Emit (OpCodes.Conv_U1); break;
1878                                 case Mode.I1_U2: ig.Emit (OpCodes.Conv_U2); break;
1879                                 case Mode.I1_U4: ig.Emit (OpCodes.Conv_U4); break;
1880                                 case Mode.I1_U8: ig.Emit (OpCodes.Conv_I8); break;
1881                                 case Mode.I1_CH: ig.Emit (OpCodes.Conv_U2); break;
1882
1883                                 case Mode.U1_I1: ig.Emit (OpCodes.Conv_I1); break;
1884                                 case Mode.U1_CH: ig.Emit (OpCodes.Conv_U2); break;
1885
1886                                 case Mode.I2_I1: ig.Emit (OpCodes.Conv_I1); break;
1887                                 case Mode.I2_U1: ig.Emit (OpCodes.Conv_U1); break;
1888                                 case Mode.I2_U2: ig.Emit (OpCodes.Conv_U2); break;
1889                                 case Mode.I2_U4: ig.Emit (OpCodes.Conv_U4); break;
1890                                 case Mode.I2_U8: ig.Emit (OpCodes.Conv_I8); break;
1891                                 case Mode.I2_CH: ig.Emit (OpCodes.Conv_U2); break;
1892
1893                                 case Mode.U2_I1: ig.Emit (OpCodes.Conv_I1); break;
1894                                 case Mode.U2_U1: ig.Emit (OpCodes.Conv_U1); break;
1895                                 case Mode.U2_I2: ig.Emit (OpCodes.Conv_I2); break;
1896                                 case Mode.U2_CH: /* nothing */ break;
1897
1898                                 case Mode.I4_I1: ig.Emit (OpCodes.Conv_I1); break;
1899                                 case Mode.I4_U1: ig.Emit (OpCodes.Conv_U1); break;
1900                                 case Mode.I4_I2: ig.Emit (OpCodes.Conv_I2); break;
1901                                 case Mode.I4_U4: /* nothing */ break;
1902                                 case Mode.I4_U2: ig.Emit (OpCodes.Conv_U2); break;
1903                                 case Mode.I4_U8: ig.Emit (OpCodes.Conv_I8); break;
1904                                 case Mode.I4_CH: ig.Emit (OpCodes.Conv_U2); break;
1905
1906                                 case Mode.U4_I1: ig.Emit (OpCodes.Conv_I1); break;
1907                                 case Mode.U4_U1: ig.Emit (OpCodes.Conv_U1); break;
1908                                 case Mode.U4_I2: ig.Emit (OpCodes.Conv_I2); break;
1909                                 case Mode.U4_U2: ig.Emit (OpCodes.Conv_U2); break;
1910                                 case Mode.U4_I4: /* nothing */ break;
1911                                 case Mode.U4_CH: ig.Emit (OpCodes.Conv_U2); break;
1912
1913                                 case Mode.I8_I1: ig.Emit (OpCodes.Conv_I1); break;
1914                                 case Mode.I8_U1: ig.Emit (OpCodes.Conv_U1); break;
1915                                 case Mode.I8_I2: ig.Emit (OpCodes.Conv_I2); break;
1916                                 case Mode.I8_U2: ig.Emit (OpCodes.Conv_U2); break;
1917                                 case Mode.I8_I4: ig.Emit (OpCodes.Conv_I4); break;
1918                                 case Mode.I8_U4: ig.Emit (OpCodes.Conv_U4); break;
1919                                 case Mode.I8_U8: /* nothing */ break;
1920                                 case Mode.I8_CH: ig.Emit (OpCodes.Conv_U2); break;
1921
1922                                 case Mode.U8_I1: ig.Emit (OpCodes.Conv_I1); break;
1923                                 case Mode.U8_U1: ig.Emit (OpCodes.Conv_U1); break;
1924                                 case Mode.U8_I2: ig.Emit (OpCodes.Conv_I2); break;
1925                                 case Mode.U8_U2: ig.Emit (OpCodes.Conv_U2); break;
1926                                 case Mode.U8_I4: ig.Emit (OpCodes.Conv_I4); break;
1927                                 case Mode.U8_U4: ig.Emit (OpCodes.Conv_U4); break;
1928                                 case Mode.U8_I8: /* nothing */ break;
1929                                 case Mode.U8_CH: ig.Emit (OpCodes.Conv_U2); break;
1930
1931                                 case Mode.CH_I1: ig.Emit (OpCodes.Conv_I1); break;
1932                                 case Mode.CH_U1: ig.Emit (OpCodes.Conv_U1); break;
1933                                 case Mode.CH_I2: ig.Emit (OpCodes.Conv_I2); break;
1934
1935                                 case Mode.R4_I1: ig.Emit (OpCodes.Conv_I1); break;
1936                                 case Mode.R4_U1: ig.Emit (OpCodes.Conv_U1); break;
1937                                 case Mode.R4_I2: ig.Emit (OpCodes.Conv_I2); break;
1938                                 case Mode.R4_U2: ig.Emit (OpCodes.Conv_U2); break;
1939                                 case Mode.R4_I4: ig.Emit (OpCodes.Conv_I4); break;
1940                                 case Mode.R4_U4: ig.Emit (OpCodes.Conv_U4); break;
1941                                 case Mode.R4_I8: ig.Emit (OpCodes.Conv_I8); break;
1942                                 case Mode.R4_U8: ig.Emit (OpCodes.Conv_U8); break;
1943                                 case Mode.R4_CH: ig.Emit (OpCodes.Conv_U2); break;
1944
1945                                 case Mode.R8_I1: ig.Emit (OpCodes.Conv_I1); break;
1946                                 case Mode.R8_U1: ig.Emit (OpCodes.Conv_U1); break;
1947                                 case Mode.R8_I2: ig.Emit (OpCodes.Conv_I2); break;
1948                                 case Mode.R8_U2: ig.Emit (OpCodes.Conv_U2); break;
1949                                 case Mode.R8_I4: ig.Emit (OpCodes.Conv_I4); break;
1950                                 case Mode.R8_U4: ig.Emit (OpCodes.Conv_U4); break;
1951                                 case Mode.R8_I8: ig.Emit (OpCodes.Conv_I8); break;
1952                                 case Mode.R8_U8: ig.Emit (OpCodes.Conv_U8); break;
1953                                 case Mode.R8_CH: ig.Emit (OpCodes.Conv_U2); break;
1954                                 case Mode.R8_R4: ig.Emit (OpCodes.Conv_R4); break;
1955                                 }
1956                         }
1957                 }
1958         }
1959         
1960         public class OpcodeCast : EmptyCast {
1961                 OpCode op, op2;
1962                 bool second_valid;
1963                 
1964                 public OpcodeCast (Expression child, Type return_type, OpCode op)
1965                         : base (child, return_type)
1966                         
1967                 {
1968                         this.op = op;
1969                         second_valid = false;
1970                 }
1971
1972                 public OpcodeCast (Expression child, Type return_type, OpCode op, OpCode op2)
1973                         : base (child, return_type)
1974                         
1975                 {
1976                         this.op = op;
1977                         this.op2 = op2;
1978                         second_valid = true;
1979                 }
1980
1981                 public override Expression DoResolve (EmitContext ec)
1982                 {
1983                         // This should never be invoked, we are born in fully
1984                         // initialized state.
1985
1986                         return this;
1987                 }
1988
1989                 public override void Emit (EmitContext ec)
1990                 {
1991                         base.Emit (ec);
1992                         ec.ig.Emit (op);
1993
1994                         if (second_valid)
1995                                 ec.ig.Emit (op2);
1996                 }                       
1997         }
1998
1999         /// <summary>
2000         ///   This kind of cast is used to encapsulate a child and cast it
2001         ///   to the class requested
2002         /// </summary>
2003         public class ClassCast : EmptyCast {
2004                 public ClassCast (Expression child, Type return_type)
2005                         : base (child, return_type)
2006                         
2007                 {
2008                 }
2009
2010                 public override Expression DoResolve (EmitContext ec)
2011                 {
2012                         // This should never be invoked, we are born in fully
2013                         // initialized state.
2014
2015                         return this;
2016                 }
2017
2018                 public override void Emit (EmitContext ec)
2019                 {
2020                         base.Emit (ec);
2021
2022                         ec.ig.Emit (OpCodes.Castclass, type);
2023                 }                       
2024                 
2025         }
2026         
2027         /// <summary>
2028         ///   SimpleName expressions are formed of a single word and only happen at the beginning 
2029         ///   of a dotted-name.
2030         /// </summary>
2031         public class SimpleName : Expression {
2032                 public string Name;
2033                 bool in_transit;
2034
2035                 public SimpleName (string name, Location l)
2036                 {
2037                         Name = name;
2038                         loc = l;
2039                 }
2040
2041                 public static void Error_ObjectRefRequired (EmitContext ec, Location l, string name)
2042                 {
2043                         if (ec.IsFieldInitializer)
2044                                 Report.Error (
2045                                         236, l,
2046                                         "A field initializer cannot reference the non-static field, " +
2047                                         "method or property `"+name+"'");
2048                         else
2049                                 Report.Error (
2050                                         120, l,
2051                                         "An object reference is required " +
2052                                         "for the non-static field `"+name+"'");
2053                 }
2054
2055                 public bool IdenticalNameAndTypeName (EmitContext ec, Expression resolved_to, Location loc)
2056                 {
2057                         return resolved_to != null && resolved_to.Type != null && 
2058                                 resolved_to.Type.Name == Name &&
2059                                 (ec.DeclSpace.LookupType (Name, loc, /* ignore_cs0104 = */ true) != null);
2060                 }
2061
2062                 public override Expression DoResolve (EmitContext ec)
2063                 {
2064                         return SimpleNameResolve (ec, null, false);
2065                 }
2066
2067                 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
2068                 {
2069                         return SimpleNameResolve (ec, right_side, false);
2070                 }
2071                 
2072
2073                 public Expression DoResolve (EmitContext ec, bool intermediate)
2074                 {
2075                         return SimpleNameResolve (ec, null, intermediate);
2076                 }
2077
2078                 public override FullNamedExpression ResolveAsTypeStep (EmitContext ec)
2079                 {
2080                         int errors = Report.Errors;
2081                         FullNamedExpression dt = ec.DeclSpace.LookupType (Name, loc, /*ignore_cs0104=*/ false);
2082                         if (Report.Errors != errors)
2083                                 return null;
2084
2085                         return dt;
2086                 }
2087
2088                 Expression SimpleNameResolve (EmitContext ec, Expression right_side, bool intermediate)
2089                 {
2090                         if (in_transit)
2091                                 return null;
2092                         in_transit = true;
2093
2094                         Expression e = DoSimpleNameResolve (ec, right_side, intermediate);
2095                         if (e == null)
2096                                 return null;
2097
2098                         if (ec.CurrentBlock == null || ec.CurrentBlock.CheckInvariantMeaningInBlock (Name, e, Location))
2099                                 return e;
2100
2101                         return null;
2102                 }
2103
2104                 /// <remarks>
2105                 ///   7.5.2: Simple Names. 
2106                 ///
2107                 ///   Local Variables and Parameters are handled at
2108                 ///   parse time, so they never occur as SimpleNames.
2109                 ///
2110                 ///   The `intermediate' flag is used by MemberAccess only
2111                 ///   and it is used to inform us that it is ok for us to 
2112                 ///   avoid the static check, because MemberAccess might end
2113                 ///   up resolving the Name as a Type name and the access as
2114                 ///   a static type access.
2115                 ///
2116                 ///   ie: Type Type; .... { Type.GetType (""); }
2117                 ///
2118                 ///   Type is both an instance variable and a Type;  Type.GetType
2119                 ///   is the static method not an instance method of type.
2120                 /// </remarks>
2121                 Expression DoSimpleNameResolve (EmitContext ec, Expression right_side, bool intermediate)
2122                 {
2123                         Expression e = null;
2124
2125                         //
2126                         // Stage 1: Performed by the parser (binding to locals or parameters).
2127                         //
2128                         Block current_block = ec.CurrentBlock;
2129                         if (current_block != null){
2130                                 LocalInfo vi = current_block.GetLocalInfo (Name);
2131                                 if (vi != null){
2132                                         Expression var;
2133                                         
2134                                         var = new LocalVariableReference (ec.CurrentBlock, Name, loc);
2135                                         
2136                                         if (right_side != null)
2137                                                 return var.ResolveLValue (ec, right_side);
2138                                         else
2139                                                 return var.Resolve (ec);
2140                                 }
2141
2142                                 ParameterReference pref = current_block.Toplevel.GetParameterReference (Name, loc);
2143                                 if (pref != null) {
2144                                         if (right_side != null)
2145                                                 return pref.ResolveLValue (ec, right_side);
2146                                         else
2147                                                 return pref.Resolve (ec);
2148                                 }
2149                         }
2150                         
2151                         //
2152                         // Stage 2: Lookup members 
2153                         //
2154
2155                         DeclSpace lookup_ds = ec.DeclSpace;
2156                         Type almost_matched_type = null;
2157                         ArrayList almost_matched = null;
2158                         do {
2159                                 if (lookup_ds.TypeBuilder == null)
2160                                         break;
2161
2162                                 e = MemberLookup (ec, lookup_ds.TypeBuilder, Name, loc);
2163                                 if (e != null)
2164                                         break;
2165
2166                                 if (almost_matched == null && almostMatchedMembers.Count > 0) {
2167                                         almost_matched_type = lookup_ds.TypeBuilder;
2168                                         almost_matched = (ArrayList) almostMatchedMembers.Clone ();
2169                                 }
2170
2171                                 lookup_ds =lookup_ds.Parent;
2172                         } while (lookup_ds != null);
2173                                 
2174                         if (e == null && ec.ContainerType != null)
2175                                 e = MemberLookup (ec, ec.ContainerType, Name, loc);
2176
2177                         if (e == null) {
2178                                 if (almost_matched == null && almostMatchedMembers.Count > 0) {
2179                                         almost_matched_type = ec.ContainerType;
2180                                         almost_matched = (ArrayList) almostMatchedMembers.Clone ();
2181                                 }
2182                                 e = ResolveAsTypeStep (ec);
2183                         }
2184
2185                         if (e == null) {
2186                                 if (almost_matched != null)
2187                                         almostMatchedMembers = almost_matched;
2188                                 if (almost_matched_type == null)
2189                                         almost_matched_type = ec.ContainerType;
2190                                 MemberLookupFailed (ec, null, almost_matched_type, ((SimpleName) this).Name, ec.DeclSpace.Name, true, loc);
2191                                 return null;
2192                         }
2193
2194                         if (e is TypeExpr)
2195                                 return e;
2196
2197                         if (e is MemberExpr) {
2198                                 MemberExpr me = (MemberExpr) e;
2199
2200                                 Expression left;
2201                                 if (me.IsInstance) {
2202                                         if (ec.IsStatic || ec.IsFieldInitializer) {
2203                                                 //
2204                                                 // Note that an MemberExpr can be both IsInstance and IsStatic.
2205                                                 // An unresolved MethodGroupExpr can contain both kinds of methods
2206                                                 // and each predicate is true if the MethodGroupExpr contains
2207                                                 // at least one of that kind of method.
2208                                                 //
2209
2210                                                 if (!me.IsStatic &&
2211                                                     (!intermediate || !IdenticalNameAndTypeName (ec, me, loc))) {
2212                                                         Error_ObjectRefRequired (ec, loc, Name);
2213                                                         return null;
2214                                                 }
2215
2216                                                 //
2217                                                 // Pass the buck to MemberAccess and Invocation.
2218                                                 //
2219                                                 left = EmptyExpression.Null;
2220                                         } else {
2221                                                 left = ec.GetThis (loc);
2222                                         }
2223                                 } else {
2224                                         left = new TypeExpression (ec.ContainerType, loc);
2225                                 }
2226
2227                                 e = me.ResolveMemberAccess (ec, left, loc, null);
2228                                 if (e == null)
2229                                         return null;
2230
2231                                 me = e as MemberExpr;
2232                                 if (me == null)
2233                                         return e;
2234
2235                                 if (!me.IsStatic &&
2236                                     TypeManager.IsNestedFamilyAccessible (me.InstanceExpression.Type, me.DeclaringType) &&
2237                                     me.InstanceExpression.Type != me.DeclaringType &&
2238                                     !me.InstanceExpression.Type.IsSubclassOf (me.DeclaringType) &&
2239                                     (!intermediate || !IdenticalNameAndTypeName (ec, e, loc))) {
2240                                         Error (38, "Cannot access nonstatic member `" + me.Name + "' of " +
2241                                                "outer type `" + me.DeclaringType + "' via nested type `" +
2242                                                me.InstanceExpression.Type + "'");
2243                                         return null;
2244                                 }
2245
2246                                 return (right_side != null)
2247                                         ? me.DoResolveLValue (ec, right_side)
2248                                         : me.DoResolve (ec);
2249                         }
2250
2251                         return e;
2252                 }
2253                 
2254                 public override void Emit (EmitContext ec)
2255                 {
2256                         //
2257                         // If this is ever reached, then we failed to
2258                         // find the name as a namespace
2259                         //
2260
2261                         Error (103, "The name `" + Name +
2262                                "' does not exist in the class `" +
2263                                ec.DeclSpace.Name + "'");
2264                 }
2265
2266                 public override string ToString ()
2267                 {
2268                         return Name;
2269                 }
2270         }
2271
2272         /// <summary>
2273         ///   Represents a namespace or a type.  The name of the class was inspired by
2274         ///   section 10.8.1 (Fully Qualified Names).
2275         /// </summary>
2276         public abstract class FullNamedExpression : Expression {
2277                 public override FullNamedExpression ResolveAsTypeStep (EmitContext ec)
2278                 {
2279                         return this;
2280                 }
2281
2282                 public abstract string FullName {
2283                         get;
2284                 }
2285         }
2286         
2287         /// <summary>
2288         ///   Fully resolved expression that evaluates to a type
2289         /// </summary>
2290         public abstract class TypeExpr : FullNamedExpression {
2291                 override public FullNamedExpression ResolveAsTypeStep (EmitContext ec)
2292                 {
2293                         TypeExpr t = DoResolveAsTypeStep (ec);
2294                         if (t == null)
2295                                 return null;
2296
2297                         eclass = ExprClass.Type;
2298                         return t;
2299                 }
2300
2301                 override public Expression DoResolve (EmitContext ec)
2302                 {
2303                         return ResolveAsTypeTerminal (ec, false);
2304                 }
2305
2306                 override public void Emit (EmitContext ec)
2307                 {
2308                         throw new Exception ("Should never be called");
2309                 }
2310
2311                 public virtual bool CheckAccessLevel (DeclSpace ds)
2312                 {
2313                         return ds.CheckAccessLevel (Type);
2314                 }
2315
2316                 public virtual bool AsAccessible (DeclSpace ds, int flags)
2317                 {
2318                         return ds.AsAccessible (Type, flags);
2319                 }
2320
2321                 public virtual bool IsClass {
2322                         get { return Type.IsClass; }
2323                 }
2324
2325                 public virtual bool IsValueType {
2326                         get { return Type.IsValueType; }
2327                 }
2328
2329                 public virtual bool IsInterface {
2330                         get { return Type.IsInterface; }
2331                 }
2332
2333                 public virtual bool IsSealed {
2334                         get { return Type.IsSealed; }
2335                 }
2336
2337                 public virtual bool CanInheritFrom ()
2338                 {
2339                         if (Type == TypeManager.enum_type ||
2340                             (Type == TypeManager.value_type && RootContext.StdLib) ||
2341                             Type == TypeManager.multicast_delegate_type ||
2342                             Type == TypeManager.delegate_type ||
2343                             Type == TypeManager.array_type)
2344                                 return false;
2345
2346                         return true;
2347                 }
2348
2349                 public abstract TypeExpr DoResolveAsTypeStep (EmitContext ec);
2350
2351                 public virtual Type ResolveType (EmitContext ec)
2352                 {
2353                         TypeExpr t = ResolveAsTypeTerminal (ec, false);
2354                         if (t == null)
2355                                 return null;
2356
2357                         return t.Type;
2358                 }
2359
2360                 public abstract string Name {
2361                         get;
2362                 }
2363
2364                 public override bool Equals (object obj)
2365                 {
2366                         TypeExpr tobj = obj as TypeExpr;
2367                         if (tobj == null)
2368                                 return false;
2369
2370                         return Type == tobj.Type;
2371                 }
2372
2373                 public override int GetHashCode ()
2374                 {
2375                         return Type.GetHashCode ();
2376                 }
2377                 
2378                 public override string ToString ()
2379                 {
2380                         return Name;
2381                 }
2382         }
2383
2384         public class TypeExpression : TypeExpr {
2385                 public TypeExpression (Type t, Location l)
2386                 {
2387                         Type = t;
2388                         eclass = ExprClass.Type;
2389                         loc = l;
2390                 }
2391
2392                 public override TypeExpr DoResolveAsTypeStep (EmitContext ec)
2393                 {
2394                         return this;
2395                 }
2396
2397                 public override string Name {
2398                         get {
2399                                 return Type.ToString ();
2400                         }
2401                 }
2402
2403                 public override string FullName {
2404                         get {
2405                                 return Type.FullName;
2406                         }
2407                 }
2408         }
2409
2410         /// <summary>
2411         ///   Used to create types from a fully qualified name.  These are just used
2412         ///   by the parser to setup the core types.  A TypeLookupExpression is always
2413         ///   classified as a type.
2414         /// </summary>
2415         public class TypeLookupExpression : TypeExpr {
2416                 string name;
2417                 
2418                 public TypeLookupExpression (string name)
2419                 {
2420                         this.name = name;
2421                 }
2422
2423                 public override TypeExpr DoResolveAsTypeStep (EmitContext ec)
2424                 {
2425                         if (type == null) {
2426                                 FullNamedExpression t = ec.DeclSpace.LookupType (name, Location.Null, /*ignore_cs0104=*/ false);
2427                                 if (t == null) {
2428                                         Report.Error (246, loc, "Cannot find type `" + name + "'");
2429                                         return null;
2430                                 }
2431                                 if (!(t is TypeExpr)) {
2432                                         Report.Error (118, Location, "'{0}' denotes a '{1}', where a type was expected",
2433                                                       t.FullName, t.ExprClassName ());
2434
2435                                         return null;
2436                                 }
2437                                 type = ((TypeExpr) t).ResolveType (ec);
2438                         }
2439
2440                         return this;
2441                 }
2442
2443                 public override string Name {
2444                         get {
2445                                 return name;
2446                         }
2447                 }
2448
2449                 public override string FullName {
2450                         get {
2451                                 return name;
2452                         }
2453                 }
2454         }
2455
2456         public class TypeAliasExpression : TypeExpr {
2457                 TypeExpr texpr;
2458
2459                 public TypeAliasExpression (TypeExpr texpr, Location l)
2460                 {
2461                         this.texpr = texpr;
2462                         loc = texpr.Location;
2463
2464                         eclass = ExprClass.Type;
2465                 }
2466
2467                 public override string Name {
2468                         get { return texpr.Name; }
2469                 }
2470
2471                 public override string FullName {
2472                         get { return texpr.FullName; }
2473                 }
2474
2475                 public override TypeExpr DoResolveAsTypeStep (EmitContext ec)
2476                 {
2477                         Type type = texpr.ResolveType (ec);
2478                         if (type == null)
2479                                 return null;
2480
2481                         return new TypeExpression (type, loc);
2482                 }
2483
2484                 public override bool CheckAccessLevel (DeclSpace ds)
2485                 {
2486                         return texpr.CheckAccessLevel (ds);
2487                 }
2488
2489                 public override bool AsAccessible (DeclSpace ds, int flags)
2490                 {
2491                         return texpr.AsAccessible (ds, flags);
2492                 }
2493
2494                 public override bool IsClass {
2495                         get { return texpr.IsClass; }
2496                 }
2497
2498                 public override bool IsValueType {
2499                         get { return texpr.IsValueType; }
2500                 }
2501
2502                 public override bool IsInterface {
2503                         get { return texpr.IsInterface; }
2504                 }
2505
2506                 public override bool IsSealed {
2507                         get { return texpr.IsSealed; }
2508                 }
2509         }
2510
2511         /// <summary>
2512         ///   This class denotes an expression which evaluates to a member
2513         ///   of a struct or a class.
2514         /// </summary>
2515         public abstract class MemberExpr : Expression
2516         {
2517                 /// <summary>
2518                 ///   The name of this member.
2519                 /// </summary>
2520                 public abstract string Name {
2521                         get;
2522                 }
2523
2524                 /// <summary>
2525                 ///   Whether this is an instance member.
2526                 /// </summary>
2527                 public abstract bool IsInstance {
2528                         get;
2529                 }
2530
2531                 /// <summary>
2532                 ///   Whether this is a static member.
2533                 /// </summary>
2534                 public abstract bool IsStatic {
2535                         get;
2536                 }
2537
2538                 /// <summary>
2539                 ///   The type which declares this member.
2540                 /// </summary>
2541                 public abstract Type DeclaringType {
2542                         get;
2543                 }
2544
2545                 /// <summary>
2546                 ///   The instance expression associated with this member, if it's a
2547                 ///   non-static member.
2548                 /// </summary>
2549                 public Expression InstanceExpression;
2550
2551                 public static void error176 (Location loc, string name)
2552                 {
2553                         Report.Error (176, loc, "Static member `" + name + "' cannot be accessed " +
2554                                       "with an instance reference, qualify with a type name instead");
2555                 }
2556
2557
2558                 // TODO: possible optimalization
2559                 // Cache resolved constant result in FieldBuilder <-> expression map
2560                 public virtual Expression ResolveMemberAccess (EmitContext ec, Expression left, Location loc,
2561                                                                SimpleName original)
2562                 {
2563                         //
2564                         // Precondition:
2565                         //   original == null || original.Resolve (...) ==> left
2566                         //
2567
2568                         if (left is TypeExpr) {
2569                                 if (!IsStatic) {
2570                                         SimpleName.Error_ObjectRefRequired (ec, loc, Name);
2571                                         return null;
2572                                 }
2573
2574                                 return this;
2575                         }
2576                                 
2577                         if (!IsInstance) {
2578                                 if (original != null && original.IdenticalNameAndTypeName (ec, left, loc))
2579                                         return this;
2580
2581                                 error176 (loc, Name);
2582                                 return null;
2583                         }
2584
2585                         InstanceExpression = left;
2586
2587                         return this;
2588                 }
2589         }
2590
2591         /// <summary>
2592         ///   MethodGroup Expression.
2593         ///  
2594         ///   This is a fully resolved expression that evaluates to a type
2595         /// </summary>
2596         public class MethodGroupExpr : MemberExpr {
2597                 public MethodBase [] Methods;
2598                 bool identical_type_name = false;
2599                 bool is_base;
2600                 
2601                 public MethodGroupExpr (MemberInfo [] mi, Location l)
2602                 {
2603                         Methods = new MethodBase [mi.Length];
2604                         mi.CopyTo (Methods, 0);
2605                         eclass = ExprClass.MethodGroup;
2606                         type = TypeManager.object_type;
2607                         loc = l;
2608                 }
2609
2610                 public MethodGroupExpr (ArrayList list, Location l)
2611                 {
2612                         Methods = new MethodBase [list.Count];
2613
2614                         try {
2615                                 list.CopyTo (Methods, 0);
2616                         } catch {
2617                                 foreach (MemberInfo m in list){
2618                                         if (!(m is MethodBase)){
2619                                                 Console.WriteLine ("Name " + m.Name);
2620                                                 Console.WriteLine ("Found a: " + m.GetType ().FullName);
2621                                         }
2622                                 }
2623                                 throw;
2624                         }
2625
2626                         loc = l;
2627                         eclass = ExprClass.MethodGroup;
2628                         type = TypeManager.object_type;
2629                 }
2630
2631                 public override Type DeclaringType {
2632                         get {
2633                                 //
2634                                 // The methods are arranged in this order:
2635                                 // derived type -> base type
2636                                 //
2637                                 return Methods [0].DeclaringType;
2638                         }
2639                 }
2640
2641                 public bool IdenticalTypeName {
2642                         get {
2643                                 return identical_type_name;
2644                         }
2645
2646                         set {
2647                                 identical_type_name = value;
2648                         }
2649                 }
2650                 
2651                 public bool IsBase {
2652                         get {
2653                                 return is_base;
2654                         }
2655                         set {
2656                                 is_base = value;
2657                         }
2658                 }
2659
2660                 public override string Name {
2661                         get {
2662                                 return Methods [0].Name;
2663                         }
2664                 }
2665
2666                 public override bool IsInstance {
2667                         get {
2668                                 foreach (MethodBase mb in Methods)
2669                                         if (!mb.IsStatic)
2670                                                 return true;
2671
2672                                 return false;
2673                         }
2674                 }
2675
2676                 public override bool IsStatic {
2677                         get {
2678                                 foreach (MethodBase mb in Methods)
2679                                         if (mb.IsStatic)
2680                                                 return true;
2681
2682                                 return false;
2683                         }
2684                 }
2685
2686                 public override Expression ResolveMemberAccess (EmitContext ec, Expression left, Location loc,
2687                                                                 SimpleName original)
2688                 {
2689                         if (!(left is TypeExpr) &&
2690                             original != null && original.IdenticalNameAndTypeName (ec, left, loc))
2691                                 IdenticalTypeName = true;
2692
2693                         return base.ResolveMemberAccess (ec, left, loc, original);
2694                 }
2695                 
2696                 override public Expression DoResolve (EmitContext ec)
2697                 {
2698                         if (!IsInstance)
2699                                 InstanceExpression = null;
2700
2701                         if (InstanceExpression != null) {
2702                                 InstanceExpression = InstanceExpression.DoResolve (ec);
2703                                 if (InstanceExpression == null)
2704                                         return null;
2705                         }
2706
2707                         return this;
2708                 }
2709
2710                 public void ReportUsageError ()
2711                 {
2712                         Report.Error (654, loc, "Method `" + DeclaringType + "." +
2713                                       Name + "()' is referenced without parentheses");
2714                 }
2715
2716                 override public void Emit (EmitContext ec)
2717                 {
2718                         ReportUsageError ();
2719                 }
2720
2721                 bool RemoveMethods (bool keep_static)
2722                 {
2723                         ArrayList smethods = new ArrayList ();
2724
2725                         foreach (MethodBase mb in Methods){
2726                                 if (mb.IsStatic == keep_static)
2727                                         smethods.Add (mb);
2728                         }
2729
2730                         if (smethods.Count == 0)
2731                                 return false;
2732
2733                         Methods = new MethodBase [smethods.Count];
2734                         smethods.CopyTo (Methods, 0);
2735
2736                         return true;
2737                 }
2738                 
2739                 /// <summary>
2740                 ///   Removes any instance methods from the MethodGroup, returns
2741                 ///   false if the resulting set is empty.
2742                 /// </summary>
2743                 public bool RemoveInstanceMethods ()
2744                 {
2745                         return RemoveMethods (true);
2746                 }
2747
2748                 /// <summary>
2749                 ///   Removes any static methods from the MethodGroup, returns
2750                 ///   false if the resulting set is empty.
2751                 /// </summary>
2752                 public bool RemoveStaticMethods ()
2753                 {
2754                         return RemoveMethods (false);
2755                 }
2756         }
2757
2758         /// <summary>
2759         ///   Fully resolved expression that evaluates to a Field
2760         /// </summary>
2761         public class FieldExpr : MemberExpr, IAssignMethod, IMemoryLocation, IVariable {
2762                 public readonly FieldInfo FieldInfo;
2763                 VariableInfo variable_info;
2764
2765                 LocalTemporary temp;
2766                 bool prepared;
2767                 bool in_initializer;
2768
2769                 public FieldExpr (FieldInfo fi, Location l, bool in_initializer):
2770                         this (fi, l)
2771                 {
2772                         this.in_initializer = in_initializer;
2773                 }
2774                 
2775                 public FieldExpr (FieldInfo fi, Location l)
2776                 {
2777                         FieldInfo = fi;
2778                         eclass = ExprClass.Variable;
2779                         type = fi.FieldType;
2780                         loc = l;
2781                 }
2782
2783                 public override string Name {
2784                         get {
2785                                 return FieldInfo.Name;
2786                         }
2787                 }
2788
2789                 public override bool IsInstance {
2790                         get {
2791                                 return !FieldInfo.IsStatic;
2792                         }
2793                 }
2794
2795                 public override bool IsStatic {
2796                         get {
2797                                 return FieldInfo.IsStatic;
2798                         }
2799                 }
2800
2801                 public override Type DeclaringType {
2802                         get {
2803                                 return FieldInfo.DeclaringType;
2804                         }
2805                 }
2806
2807                 public VariableInfo VariableInfo {
2808                         get {
2809                                 return variable_info;
2810                         }
2811                 }
2812
2813                 public override Expression ResolveMemberAccess (EmitContext ec, Expression left, Location loc,
2814                                                                 SimpleName original)
2815                 {
2816                         bool left_is_type = left is TypeExpr;
2817
2818                         Type decl_type = FieldInfo.DeclaringType;
2819                         
2820                         bool is_emitted = FieldInfo is FieldBuilder;
2821                         Type t = FieldInfo.FieldType;
2822                         
2823                         if (is_emitted) {
2824                                 Const c = TypeManager.LookupConstant ((FieldBuilder) FieldInfo);
2825                                 
2826                                 if (c != null) {
2827                                         object o;
2828                                         if (!c.LookupConstantValue (out o))
2829                                                 return null;
2830
2831                                         c.SetMemberIsUsed ();
2832                                         object real_value = ((Constant) c.Expr).GetValue ();
2833
2834                                         Expression exp = Constantify (real_value, t);
2835                                         
2836                                         if (!left_is_type && 
2837                                             (original == null || !original.IdenticalNameAndTypeName (ec, left, loc))) {
2838                                                 Report.SymbolRelatedToPreviousError (c);
2839                                                 error176 (loc, c.GetSignatureForError ());
2840                                                 return null;
2841                                         }
2842                                         
2843                                         return exp;
2844                                 }
2845                         }
2846
2847                         //
2848                         // Decimal constants cannot be encoded in the constant blob, and thus are marked
2849                         // as IsInitOnly ('readonly' in C# parlance).  We get its value from the 
2850                         // DecimalConstantAttribute metadata.
2851                         //
2852                         if (FieldInfo.IsInitOnly && !is_emitted && t == TypeManager.decimal_type) {
2853                                 object[] attrs = FieldInfo.GetCustomAttributes (TypeManager.decimal_constant_attribute_type, false);
2854                                 if (attrs.Length == 1)
2855                                         return new DecimalConstant (((System.Runtime.CompilerServices.DecimalConstantAttribute) attrs [0]).Value);
2856                         }
2857                         
2858                         if (FieldInfo.IsLiteral) {
2859                                 object o;
2860                                 
2861                                 if (is_emitted)
2862                                         o = TypeManager.GetValue ((FieldBuilder) FieldInfo);
2863                                 else
2864                                         o = FieldInfo.GetValue (FieldInfo);
2865                                 
2866                                 if (decl_type.IsSubclassOf (TypeManager.enum_type)) {
2867                                         if (!left_is_type &&
2868                                             (original == null || !original.IdenticalNameAndTypeName (ec, left, loc))) {
2869                                                 error176 (loc, FieldInfo.Name);
2870                                                 return null;
2871                                         }                                       
2872                                         
2873                                         Expression enum_member = MemberLookup (
2874                                                ec, decl_type, "value__", MemberTypes.Field,
2875                                                AllBindingFlags | BindingFlags.NonPublic, loc); 
2876                                         
2877                                         Enum en = TypeManager.LookupEnum (decl_type);
2878                                         
2879                                         Constant c;
2880                                         if (en != null)
2881                                                 c = Constantify (o, en.UnderlyingType);
2882                                         else 
2883                                                 c = Constantify (o, enum_member.Type);
2884                                         
2885                                         return new EnumConstant (c, decl_type);
2886                                 }
2887                                 
2888                                 Expression exp = Constantify (o, t);
2889                                 
2890                                 if (!left_is_type) {
2891                                         error176 (loc, FieldInfo.Name);
2892                                         return null;
2893                                 }
2894                                 
2895                                 return exp;
2896                         }
2897                         
2898                         if (t.IsPointer && !ec.InUnsafe) {
2899                                 UnsafeError (loc);
2900                                 return null;
2901                         }
2902
2903                         return base.ResolveMemberAccess (ec, left, loc, original);
2904                 }
2905
2906                 override public Expression DoResolve (EmitContext ec)
2907                 {
2908                         if (ec.InRefOutArgumentResolving && FieldInfo.IsInitOnly && !ec.IsConstructor && FieldInfo.FieldType.IsValueType) {
2909                                 if (FieldInfo.FieldType is TypeBuilder) {
2910                                         if (FieldInfo.IsStatic)
2911                                                 Report.Error (1651, loc, "Members of readonly static field '{0}.{1}' cannot be passed ref or out (except in a constructor)",
2912                                                         TypeManager.CSharpName (DeclaringType), Name);
2913                                         else
2914                                                 Report.Error (1649, loc, "Members of readonly field '{0}.{1}' cannot be passed ref or out (except in a constructor)",
2915                                                         TypeManager.CSharpName (DeclaringType), Name);
2916                                 } else {
2917                                         if (FieldInfo.IsStatic)
2918                                                 Report.Error (199, loc, "A static readonly field '{0}' cannot be passed ref or out (except in a static constructor)",
2919                                                         Name);
2920                                         else
2921                                                 Report.Error (192, loc, "A readonly field '{0}' cannot be passed ref or out (except in a constructor)",
2922                                                         Name);
2923                                 }
2924                                 return null;
2925                         }
2926
2927                         if (!FieldInfo.IsStatic){
2928                                 if (InstanceExpression == null){
2929                                         //
2930                                         // This can happen when referencing an instance field using
2931                                         // a fully qualified type expression: TypeName.InstanceField = xxx
2932                                         // 
2933                                         SimpleName.Error_ObjectRefRequired (ec, loc, FieldInfo.Name);
2934                                         return null;
2935                                 }
2936
2937                                 // Resolve the field's instance expression while flow analysis is turned
2938                                 // off: when accessing a field "a.b", we must check whether the field
2939                                 // "a.b" is initialized, not whether the whole struct "a" is initialized.
2940                                 InstanceExpression = InstanceExpression.Resolve (ec, ResolveFlags.VariableOrValue |
2941                                                                        ResolveFlags.DisableFlowAnalysis);
2942                                 if (InstanceExpression == null)
2943                                         return null;
2944                         }
2945
2946                         if (!in_initializer) {
2947                                 ObsoleteAttribute oa;
2948                                 FieldBase f = TypeManager.GetField (FieldInfo);
2949                                 if (f != null) {
2950                                         oa = f.GetObsoleteAttribute (f.Parent);
2951                                         if (oa != null)
2952                                                 AttributeTester.Report_ObsoleteMessage (oa, f.GetSignatureForError (), loc);
2953                                 
2954                                         // To be sure that type is external because we do not register generated fields
2955                                 } else if (!(FieldInfo.DeclaringType is TypeBuilder)) {                                
2956                                         oa = AttributeTester.GetMemberObsoleteAttribute (FieldInfo);
2957                                         if (oa != null)
2958                                                 AttributeTester.Report_ObsoleteMessage (oa, TypeManager.GetFullNameSignature (FieldInfo), loc);
2959                                 }
2960                         }
2961
2962                         if (ec.CurrentAnonymousMethod != null){
2963                                 if (!FieldInfo.IsStatic){
2964                                         if (ec.TypeContainer is Struct){
2965                                                 Report.Error (1673, loc, "Can not reference instance variables in anonymous methods hosted in structs");
2966                                                 return null;
2967                                         }
2968                                         ec.CaptureField (this);
2969                                 } 
2970                         }
2971                         
2972                         // If the instance expression is a local variable or parameter.
2973                         IVariable var = InstanceExpression as IVariable;
2974                         if ((var == null) || (var.VariableInfo == null))
2975                                 return this;
2976
2977                         VariableInfo vi = var.VariableInfo;
2978                         if (!vi.IsFieldAssigned (ec, FieldInfo.Name, loc))
2979                                 return null;
2980
2981                         variable_info = vi.GetSubStruct (FieldInfo.Name);
2982                         return this;
2983                 }
2984
2985                 void Report_AssignToReadonly (bool is_instance)
2986                 {
2987                         string msg;
2988                         
2989                         if (is_instance)
2990                                 msg = "Readonly field can not be assigned outside " +
2991                                 "of constructor or variable initializer";
2992                         else
2993                                 msg = "A static readonly field can only be assigned in " +
2994                                 "a static constructor";
2995
2996                         Report.Error (is_instance ? 191 : 198, loc, msg);
2997                 }
2998                 
2999                 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
3000                 {
3001                         IVariable var = InstanceExpression as IVariable;
3002                         if ((var != null) && (var.VariableInfo != null))
3003                                 var.VariableInfo.SetFieldAssigned (ec, FieldInfo.Name);
3004
3005                         Expression e = DoResolve (ec);
3006
3007                         if (e == null)
3008                                 return null;
3009
3010                         if (!FieldInfo.IsStatic && (InstanceExpression.Type.IsValueType && !(InstanceExpression is IMemoryLocation))) {
3011                                 // FIXME: Provide better error reporting.
3012                                 Error (1612, "Cannot modify expression because it is not a variable.");
3013                                 return null;
3014                         }
3015
3016                         FieldBase fb = TypeManager.GetField (FieldInfo);
3017                         if (fb != null)
3018                                 fb.SetAssigned ();
3019
3020                         if (!FieldInfo.IsInitOnly)
3021                                 return this;
3022
3023                         //
3024                         // InitOnly fields can only be assigned in constructors
3025                         //
3026
3027                         if (ec.IsConstructor){
3028                                 if (IsStatic && !ec.IsStatic)
3029                                         Report_AssignToReadonly (false);
3030
3031                                 if (ec.ContainerType == FieldInfo.DeclaringType)
3032                                         return this;
3033                         }
3034
3035                         Report_AssignToReadonly (!IsStatic);
3036                         
3037                         return null;
3038                 }
3039
3040                 public override void CheckMarshallByRefAccess (Type container)
3041                 {
3042                         if (!IsStatic && Type.IsValueType && !container.IsSubclassOf (TypeManager.mbr_type) && DeclaringType.IsSubclassOf (TypeManager.mbr_type)) {
3043                                 Report.SymbolRelatedToPreviousError (DeclaringType);
3044                                 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);
3045                         }
3046                 }
3047
3048                 public bool VerifyFixed (bool is_expression)
3049                 {
3050                         IVariable variable = InstanceExpression as IVariable;
3051                         if ((variable == null) || !variable.VerifyFixed (true))
3052                                 return false;
3053
3054                         return true;
3055                 }
3056
3057                 public override int GetHashCode()
3058                 {
3059                         return FieldInfo.GetHashCode ();
3060                 }
3061
3062                 public override bool Equals (object obj)
3063                 {
3064                         FieldExpr fe = obj as FieldExpr;
3065                         if (fe == null)
3066                                 return false;
3067
3068                         if (FieldInfo != fe.FieldInfo)
3069                                 return false;
3070
3071                         if (InstanceExpression == null || fe.InstanceExpression == null)
3072                                 return true;
3073
3074                         return InstanceExpression.Equals (fe.InstanceExpression);
3075                 }
3076                 
3077                 public void Emit (EmitContext ec, bool leave_copy)
3078                 {
3079                         ILGenerator ig = ec.ig;
3080                         bool is_volatile = false;
3081
3082                         if (FieldInfo is FieldBuilder){
3083                                 FieldBase f = TypeManager.GetField (FieldInfo);
3084                                 if (f != null){
3085                                         if ((f.ModFlags & Modifiers.VOLATILE) != 0)
3086                                                 is_volatile = true;
3087                                         
3088                                         f.SetMemberIsUsed ();
3089                                 }
3090                         } 
3091                         
3092                         if (FieldInfo.IsStatic){
3093                                 if (is_volatile)
3094                                         ig.Emit (OpCodes.Volatile);
3095                                 
3096                                 ig.Emit (OpCodes.Ldsfld, FieldInfo);
3097                         } else {
3098                                 if (!prepared)
3099                                         EmitInstance (ec);
3100                                 
3101                                 if (is_volatile)
3102                                         ig.Emit (OpCodes.Volatile);
3103
3104                                 IFixedBuffer ff = AttributeTester.GetFixedBuffer (FieldInfo);
3105                                 if (ff != null)
3106                                 {
3107                                         ig.Emit (OpCodes.Ldflda, FieldInfo);
3108                                         ig.Emit (OpCodes.Ldflda, ff.Element);
3109                                 }
3110                                 else {
3111                                         ig.Emit (OpCodes.Ldfld, FieldInfo);
3112                                 }
3113                         }
3114
3115                         if (leave_copy) {       
3116                                 ec.ig.Emit (OpCodes.Dup);
3117                                 if (!FieldInfo.IsStatic) {
3118                                         temp = new LocalTemporary (ec, this.Type);
3119                                         temp.Store (ec);
3120                                 }
3121                         }
3122                 }
3123                 
3124                 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
3125                 {
3126                         FieldAttributes fa = FieldInfo.Attributes;
3127                         bool is_static = (fa & FieldAttributes.Static) != 0;
3128                         bool is_readonly = (fa & FieldAttributes.InitOnly) != 0;
3129                         ILGenerator ig = ec.ig;
3130                         prepared = prepare_for_load;
3131
3132                         if (is_readonly && !ec.IsConstructor){
3133                                 Report_AssignToReadonly (!is_static);
3134                                 return;
3135                         }
3136
3137                         if (!is_static) {
3138                                 EmitInstance (ec);
3139                                 if (prepare_for_load)
3140                                         ig.Emit (OpCodes.Dup);
3141                         }
3142
3143                         source.Emit (ec);
3144                         if (leave_copy) {
3145                                 ec.ig.Emit (OpCodes.Dup);
3146                                 if (!FieldInfo.IsStatic) {
3147                                         temp = new LocalTemporary (ec, this.Type);
3148                                         temp.Store (ec);
3149                                 }
3150                         }
3151
3152                         if (FieldInfo is FieldBuilder){
3153                                 FieldBase f = TypeManager.GetField (FieldInfo);
3154                                 if (f != null){
3155                                         if ((f.ModFlags & Modifiers.VOLATILE) != 0)
3156                                                 ig.Emit (OpCodes.Volatile);
3157                                         
3158                                         f.status |= Field.Status.ASSIGNED;
3159                                 }
3160                         } 
3161
3162                         if (is_static)
3163                                 ig.Emit (OpCodes.Stsfld, FieldInfo);
3164                         else 
3165                                 ig.Emit (OpCodes.Stfld, FieldInfo);
3166                         
3167                         if (temp != null)
3168                                 temp.Emit (ec);
3169                 }
3170
3171                 void EmitInstance (EmitContext ec)
3172                 {
3173                         if (InstanceExpression.Type.IsValueType) {
3174                                 if (InstanceExpression is IMemoryLocation) {
3175                                         ((IMemoryLocation) InstanceExpression).AddressOf (ec, AddressOp.LoadStore);
3176                                 } else {
3177                                         LocalTemporary t = new LocalTemporary (ec, InstanceExpression.Type);
3178                                         InstanceExpression.Emit (ec);
3179                                         t.Store (ec);
3180                                         t.AddressOf (ec, AddressOp.Store);
3181                                 }
3182                         } else
3183                                 InstanceExpression.Emit (ec);
3184                 }
3185
3186                 public override void Emit (EmitContext ec)
3187                 {
3188                         Emit (ec, false);
3189                 }
3190
3191                 public void AddressOf (EmitContext ec, AddressOp mode)
3192                 {
3193                         ILGenerator ig = ec.ig;
3194                         
3195                         if (FieldInfo is FieldBuilder){
3196                                 FieldBase f = TypeManager.GetField (FieldInfo);
3197                                 if (f != null){
3198                                         if ((f.ModFlags & Modifiers.VOLATILE) != 0){
3199                                                 Error (676, "volatile variable: can not take its address, or pass as ref/out parameter");
3200                                                 return;
3201                                         }
3202                                         
3203                                         if ((mode & AddressOp.Store) != 0)
3204                                                 f.status |= Field.Status.ASSIGNED;
3205                                         if ((mode & AddressOp.Load) != 0)
3206                                                 f.SetMemberIsUsed ();
3207                                 }
3208                         } 
3209
3210                         //
3211                         // Handle initonly fields specially: make a copy and then
3212                         // get the address of the copy.
3213                         //
3214                         bool need_copy;
3215                         if (FieldInfo.IsInitOnly){
3216                                 need_copy = true;
3217                                 if (ec.IsConstructor){
3218                                         if (FieldInfo.IsStatic){
3219                                                 if (ec.IsStatic)
3220                                                         need_copy = false;
3221                                         } else
3222                                                 need_copy = false;
3223                                 }
3224                         } else
3225                                 need_copy = false;
3226                         
3227                         if (need_copy){
3228                                 LocalBuilder local;
3229                                 Emit (ec);
3230                                 local = ig.DeclareLocal (type);
3231                                 ig.Emit (OpCodes.Stloc, local);
3232                                 ig.Emit (OpCodes.Ldloca, local);
3233                                 return;
3234                         }
3235
3236
3237                         if (FieldInfo.IsStatic){
3238                                 ig.Emit (OpCodes.Ldsflda, FieldInfo);
3239                         } else {
3240                                 EmitInstance (ec);
3241                                 ig.Emit (OpCodes.Ldflda, FieldInfo);
3242                         }
3243                 }
3244         }
3245
3246         //
3247         // A FieldExpr whose address can not be taken
3248         //
3249         public class FieldExprNoAddress : FieldExpr, IMemoryLocation {
3250                 public FieldExprNoAddress (FieldInfo fi, Location loc) : base (fi, loc)
3251                 {
3252                 }
3253                 
3254                 public new void AddressOf (EmitContext ec, AddressOp mode)
3255                 {
3256                         Report.Error (-215, "Report this: Taking the address of a remapped parameter not supported");
3257                 }
3258         }
3259         
3260         /// <summary>
3261         ///   Expression that evaluates to a Property.  The Assign class
3262         ///   might set the `Value' expression if we are in an assignment.
3263         ///
3264         ///   This is not an LValue because we need to re-write the expression, we
3265         ///   can not take data from the stack and store it.  
3266         /// </summary>
3267         public class PropertyExpr : MemberExpr, IAssignMethod {
3268                 public readonly PropertyInfo PropertyInfo;
3269
3270                 //
3271                 // This is set externally by the  `BaseAccess' class
3272                 //
3273                 public bool IsBase;
3274                 MethodInfo getter, setter;
3275                 bool is_static;
3276
3277                 bool resolved;
3278                 
3279                 LocalTemporary temp;
3280                 bool prepared;
3281
3282                 internal static PtrHashtable AccessorTable = new PtrHashtable (); 
3283
3284                 public PropertyExpr (EmitContext ec, PropertyInfo pi, Location l)
3285                 {
3286                         PropertyInfo = pi;
3287                         eclass = ExprClass.PropertyAccess;
3288                         is_static = false;
3289                         loc = l;
3290
3291                         type = TypeManager.TypeToCoreType (pi.PropertyType);
3292
3293                         ResolveAccessors (ec);
3294                 }
3295
3296                 public override string Name {
3297                         get {
3298                                 return PropertyInfo.Name;
3299                         }
3300                 }
3301
3302                 public override bool IsInstance {
3303                         get {
3304                                 return !is_static;
3305                         }
3306                 }
3307
3308                 public override bool IsStatic {
3309                         get {
3310                                 return is_static;
3311                         }
3312                 }
3313                 
3314                 public override Type DeclaringType {
3315                         get {
3316                                 return PropertyInfo.DeclaringType;
3317                         }
3318                 }
3319
3320                 public bool VerifyAssignable ()
3321                 {
3322                         if (setter == null) {
3323                                 Report.Error (200, loc, 
3324                                               "The property `" + PropertyInfo.Name +
3325                                               "' can not be assigned to, as it has not set accessor");
3326                                 return false;
3327                         }
3328
3329                         return true;
3330                 }
3331
3332                 void FindAccessors (Type invocation_type)
3333                 {
3334                         BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic |
3335                                 BindingFlags.Static | BindingFlags.Instance |
3336                                 BindingFlags.DeclaredOnly;
3337
3338                         Type current = PropertyInfo.DeclaringType;
3339                         for (; current != null; current = current.BaseType) {
3340                                 MemberInfo[] group = TypeManager.MemberLookup (
3341                                         invocation_type, invocation_type, current,
3342                                         MemberTypes.Property, flags, PropertyInfo.Name, null);
3343
3344                                 if (group == null)
3345                                         continue;
3346
3347                                 if (group.Length != 1)
3348                                         // Oooops, can this ever happen ?
3349                                         return;
3350
3351                                 PropertyInfo pi = (PropertyInfo) group [0];
3352
3353                                 if (getter == null)
3354                                         getter = pi.GetGetMethod (true);
3355
3356                                 if (setter == null)
3357                                         setter = pi.GetSetMethod (true);
3358
3359                                 MethodInfo accessor = getter != null ? getter : setter;
3360
3361                                 if (!accessor.IsVirtual)
3362                                         return;
3363                         }
3364                 }
3365
3366                 //
3367                 // We also perform the permission checking here, as the PropertyInfo does not
3368                 // hold the information for the accessibility of its setter/getter
3369                 //
3370                 void ResolveAccessors (EmitContext ec)
3371                 {
3372                         FindAccessors (ec.ContainerType);
3373
3374                         if (getter != null) {
3375                                 IMethodData md = TypeManager.GetMethod (getter);
3376                                 if (md != null)
3377                                         md.SetMemberIsUsed ();
3378
3379                                 AccessorTable [getter] = PropertyInfo;
3380                                 is_static = getter.IsStatic;
3381                         }
3382
3383                         if (setter != null) {
3384                                 IMethodData md = TypeManager.GetMethod (setter);
3385                                 if (md != null)
3386                                         md.SetMemberIsUsed ();
3387
3388                                 AccessorTable [setter] = PropertyInfo;
3389                                 is_static = setter.IsStatic;
3390                         }
3391                 }
3392
3393                 bool InstanceResolve (EmitContext ec, bool must_do_cs1540_check)
3394                 {
3395                         if ((InstanceExpression == null) && ec.IsStatic && !is_static) {
3396                                 SimpleName.Error_ObjectRefRequired (ec, loc, PropertyInfo.Name);
3397                                 return false;
3398                         }
3399
3400                         if (!IsInstance || InstanceExpression == EmptyExpression.Null)
3401                                 InstanceExpression = null;
3402
3403                         if (InstanceExpression != null) {
3404                                 InstanceExpression = InstanceExpression.DoResolve (ec);
3405                                 if (InstanceExpression == null)
3406                                         return false;
3407
3408                                 InstanceExpression.CheckMarshallByRefAccess (ec.ContainerType);
3409                         }
3410
3411                         if (must_do_cs1540_check && (InstanceExpression != null)) {
3412                                 if ((InstanceExpression.Type != ec.ContainerType) &&
3413                                     ec.ContainerType.IsSubclassOf (InstanceExpression.Type)) {
3414                                         Report.Error (1540, loc, "Cannot access protected member `" +
3415                                                       PropertyInfo.DeclaringType + "." + PropertyInfo.Name + 
3416                                                       "' via a qualifier of type `" +
3417                                                       TypeManager.CSharpName (InstanceExpression.Type) +
3418                                                       "'; the qualifier must be of type `" +
3419                                                       TypeManager.CSharpName (ec.ContainerType) +
3420                                                       "' (or derived from it)");
3421                                         return false;
3422                                 }
3423                         }
3424
3425                         return true;
3426                 }
3427                 
3428                 override public Expression DoResolve (EmitContext ec)
3429                 {
3430                         if (resolved) {
3431                                 Report.Debug ("Double resolve of " + Name);
3432                                 return this;
3433                         }
3434
3435                         if (getter != null){
3436                                 if (TypeManager.GetArgumentTypes (getter).Length != 0){
3437                                         Report.Error (
3438                                                 117, loc, "`{0}' does not contain a " +
3439                                                 "definition for `{1}'.", getter.DeclaringType,
3440                                                 Name);
3441                                         return null;
3442                                 }
3443                         }
3444
3445                         if (getter == null){
3446                                 //
3447                                 // The following condition happens if the PropertyExpr was
3448                                 // created, but is invalid (ie, the property is inaccessible),
3449                                 // and we did not want to embed the knowledge about this in
3450                                 // the caller routine.  This only avoids double error reporting.
3451                                 //
3452                                 if (setter == null)
3453                                         return null;
3454
3455                                 if (InstanceExpression != EmptyExpression.Null) {
3456                                         Report.Error (154, loc, 
3457                                                 "The property `" + PropertyInfo.Name +
3458                                                 "' can not be used in " +
3459                                                 "this context because it lacks a get accessor");
3460                                         return null;
3461                                 }
3462                         } 
3463
3464                         bool must_do_cs1540_check = false;
3465                         if (getter != null &&
3466                             !IsAccessorAccessible (ec.ContainerType, getter, out must_do_cs1540_check)) {
3467                                 PropertyBase.PropertyMethod pm = TypeManager.GetMethod (getter) as PropertyBase.PropertyMethod;
3468                                 if (pm != null && pm.HasCustomAccessModifier) {
3469                                         Report.SymbolRelatedToPreviousError (pm);
3470                                         Report.Error (271, loc, "The property or indexer '{0}' cannot be used in this context because the get accessor is inaccessible",
3471                                                 TypeManager.CSharpSignature (getter));
3472                                 }
3473                                 else
3474                                         Report.Error (122, loc, "'{0}' is inaccessible due to its protection level",
3475                                                 TypeManager.CSharpSignature (getter));
3476                                 return null;
3477                         }
3478                         
3479                         if (!InstanceResolve (ec, must_do_cs1540_check))
3480                                 return null;
3481
3482                         //
3483                         // Only base will allow this invocation to happen.
3484                         //
3485                         if (IsBase && getter.IsAbstract){
3486                                 Report.Error (205, loc, "Cannot call an abstract base property: " +
3487                                               PropertyInfo.DeclaringType + "." +PropertyInfo.Name);
3488                                 return null;
3489                         }
3490
3491                         if (PropertyInfo.PropertyType.IsPointer && !ec.InUnsafe){
3492                                 UnsafeError (loc);
3493                                 return null;
3494                         }
3495
3496                         resolved = true;
3497
3498                         return this;
3499                 }
3500
3501                 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
3502                 {
3503                         if (setter == null){
3504                                 //
3505                                 // The following condition happens if the PropertyExpr was
3506                                 // created, but is invalid (ie, the property is inaccessible),
3507                                 // and we did not want to embed the knowledge about this in
3508                                 // the caller routine.  This only avoids double error reporting.
3509                                 //
3510                                 if (getter == null)
3511                                         return null;
3512                                 
3513                                 // TODO: Print better property name
3514                                 Report.Error (200, loc, "Property or indexer '{0}' cannot be assigned to -- it is read only",
3515                                               PropertyInfo.Name);
3516                                 return null;
3517                         }
3518
3519                         if (TypeManager.GetArgumentTypes (setter).Length != 1){
3520                                 Report.Error (
3521                                         117, loc, "`{0}' does not contain a " +
3522                                         "definition for `{1}'.", getter.DeclaringType,
3523                                         Name);
3524                                 return null;
3525                         }
3526
3527                         bool must_do_cs1540_check;
3528                         if (!IsAccessorAccessible (ec.ContainerType, setter, out must_do_cs1540_check)) {
3529                                 PropertyBase.PropertyMethod pm = TypeManager.GetMethod (setter) as PropertyBase.PropertyMethod;
3530                                 if (pm != null && pm.HasCustomAccessModifier) {
3531                                         Report.SymbolRelatedToPreviousError (pm);
3532                                         Report.Error (272, loc, "The property or indexer '{0}' cannot be used in this context because the set accessor is inaccessible",
3533                                                 TypeManager.CSharpSignature (setter));
3534                                 }
3535                                 else
3536                                         Report.Error (122, loc, "'{0}' is inaccessible due to its protection level",
3537                                                 TypeManager.CSharpSignature (setter));
3538                                 return null;
3539                         }
3540                         
3541                         if (!InstanceResolve (ec, must_do_cs1540_check))
3542                                 return null;
3543                         
3544                         //
3545                         // Only base will allow this invocation to happen.
3546                         //
3547                         if (IsBase && setter.IsAbstract){
3548                                 Report.Error (205, loc, "Cannot call an abstract base property: " +
3549                                               PropertyInfo.DeclaringType + "." +PropertyInfo.Name);
3550                                 return null;
3551                         }
3552
3553                         //
3554                         // Check that we are not making changes to a temporary memory location
3555                         //
3556                         if (InstanceExpression != null && InstanceExpression.Type.IsValueType && !(InstanceExpression is IMemoryLocation)) {
3557                                 // FIXME: Provide better error reporting.
3558                                 Error (1612, "Cannot modify expression because it is not a variable.");
3559                                 return null;
3560                         }
3561
3562                         return this;
3563                 }
3564
3565
3566                 
3567                 public override void Emit (EmitContext ec)
3568                 {
3569                         Emit (ec, false);
3570                 }
3571                 
3572                 void EmitInstance (EmitContext ec)
3573                 {
3574                         if (is_static)
3575                                 return;
3576
3577                         if (InstanceExpression.Type.IsValueType) {
3578                                 if (InstanceExpression is IMemoryLocation) {
3579                                         ((IMemoryLocation) InstanceExpression).AddressOf (ec, AddressOp.LoadStore);
3580                                 } else {
3581                                         LocalTemporary t = new LocalTemporary (ec, InstanceExpression.Type);
3582                                         InstanceExpression.Emit (ec);
3583                                         t.Store (ec);
3584                                         t.AddressOf (ec, AddressOp.Store);
3585                                 }
3586                         } else
3587                                 InstanceExpression.Emit (ec);
3588                         
3589                         if (prepared)
3590                                 ec.ig.Emit (OpCodes.Dup);
3591                 }
3592
3593                 
3594                 public void Emit (EmitContext ec, bool leave_copy)
3595                 {
3596                         if (!prepared)
3597                                 EmitInstance (ec);
3598                         
3599                         //
3600                         // Special case: length of single dimension array property is turned into ldlen
3601                         //
3602                         if ((getter == TypeManager.system_int_array_get_length) ||
3603                             (getter == TypeManager.int_array_get_length)){
3604                                 Type iet = InstanceExpression.Type;
3605
3606                                 //
3607                                 // System.Array.Length can be called, but the Type does not
3608                                 // support invoking GetArrayRank, so test for that case first
3609                                 //
3610                                 if (iet != TypeManager.array_type && (iet.GetArrayRank () == 1)) {
3611                                         ec.ig.Emit (OpCodes.Ldlen);
3612                                         ec.ig.Emit (OpCodes.Conv_I4);
3613                                         return;
3614                                 }
3615                         }
3616
3617                         Invocation.EmitCall (ec, IsBase, IsStatic, new EmptyAddressOf (), getter, null, loc);
3618                         
3619                         if (!leave_copy)
3620                                 return;
3621                         
3622                         ec.ig.Emit (OpCodes.Dup);
3623                         if (!is_static) {
3624                                 temp = new LocalTemporary (ec, this.Type);
3625                                 temp.Store (ec);
3626                         }
3627                 }
3628
3629                 //
3630                 // Implements the IAssignMethod interface for assignments
3631                 //
3632                 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
3633                 {
3634                         prepared = prepare_for_load;
3635                         
3636                         EmitInstance (ec);
3637
3638                         source.Emit (ec);
3639                         if (leave_copy) {
3640                                 ec.ig.Emit (OpCodes.Dup);
3641                                 if (!is_static) {
3642                                         temp = new LocalTemporary (ec, this.Type);
3643                                         temp.Store (ec);
3644                                 }
3645                         }
3646                         
3647                         ArrayList args = new ArrayList (1);
3648                         args.Add (new Argument (new EmptyAddressOf (), Argument.AType.Expression));
3649                         
3650                         Invocation.EmitCall (ec, IsBase, IsStatic, new EmptyAddressOf (), setter, args, loc);
3651                         
3652                         if (temp != null)
3653                                 temp.Emit (ec);
3654                 }
3655         }
3656
3657         /// <summary>
3658         ///   Fully resolved expression that evaluates to an Event
3659         /// </summary>
3660         public class EventExpr : MemberExpr {
3661                 public readonly EventInfo EventInfo;
3662
3663                 bool is_static;
3664                 MethodInfo add_accessor, remove_accessor;
3665                 
3666                 public EventExpr (EventInfo ei, Location loc)
3667                 {
3668                         EventInfo = ei;
3669                         this.loc = loc;
3670                         eclass = ExprClass.EventAccess;
3671
3672                         add_accessor = TypeManager.GetAddMethod (ei);
3673                         remove_accessor = TypeManager.GetRemoveMethod (ei);
3674                         
3675                         if (add_accessor.IsStatic || remove_accessor.IsStatic)
3676                                 is_static = true;
3677
3678                         if (EventInfo is MyEventBuilder){
3679                                 MyEventBuilder eb = (MyEventBuilder) EventInfo;
3680                                 type = eb.EventType;
3681                                 eb.SetUsed ();
3682                         } else
3683                                 type = EventInfo.EventHandlerType;
3684                 }
3685
3686                 public override string Name {
3687                         get {
3688                                 return EventInfo.Name;
3689                         }
3690                 }
3691
3692                 public override bool IsInstance {
3693                         get {
3694                                 return !is_static;
3695                         }
3696                 }
3697
3698                 public override bool IsStatic {
3699                         get {
3700                                 return is_static;
3701                         }
3702                 }
3703
3704                 public override Type DeclaringType {
3705                         get {
3706                                 return EventInfo.DeclaringType;
3707                         }
3708                 }
3709
3710                 public override Expression ResolveMemberAccess (EmitContext ec, Expression left, Location loc,
3711                                                                 SimpleName original)
3712                 {
3713                         //
3714                         // If the event is local to this class, we transform ourselves into a FieldExpr
3715                         //
3716
3717                         if (EventInfo.DeclaringType == ec.ContainerType ||
3718                             TypeManager.IsNestedChildOf(ec.ContainerType, EventInfo.DeclaringType)) {
3719                                 MemberInfo mi = TypeManager.GetPrivateFieldOfEvent (EventInfo);
3720
3721                                 if (mi != null) {
3722                                         MemberExpr ml = (MemberExpr) ExprClassFromMemberInfo (ec, mi, loc);
3723
3724                                         if (ml == null) {
3725                                                 Report.Error (-200, loc, "Internal error!!");
3726                                                 return null;
3727                                         }
3728
3729                                         InstanceExpression = null;
3730                                 
3731                                         return ml.ResolveMemberAccess (ec, left, loc, original);
3732                                 }
3733                         }
3734
3735                         return base.ResolveMemberAccess (ec, left, loc, original);
3736                 }
3737
3738
3739                 bool InstanceResolve (EmitContext ec, bool must_do_cs1540_check)
3740                 {
3741                         if ((InstanceExpression == null) && ec.IsStatic && !is_static) {
3742                                 SimpleName.Error_ObjectRefRequired (ec, loc, EventInfo.Name);
3743                                 return false;
3744                         }
3745
3746                         if (!IsInstance || InstanceExpression == EmptyExpression.Null)
3747                                 InstanceExpression = null;
3748
3749                         if (InstanceExpression != null) {
3750                                 InstanceExpression = InstanceExpression.DoResolve (ec);
3751                                 if (InstanceExpression == null)
3752                                         return false;
3753                         }
3754
3755                         //
3756                         // This is using the same mechanism as the CS1540 check in PropertyExpr.
3757                         // However, in the Event case, we reported a CS0122 instead.
3758                         //
3759                         if (must_do_cs1540_check && (InstanceExpression != null)) {
3760                                 if ((InstanceExpression.Type != ec.ContainerType) &&
3761                                         ec.ContainerType.IsSubclassOf (InstanceExpression.Type)) {
3762                                         Report.Error (122, loc, "'{0}' is inaccessible due to its protection level",
3763                                                 DeclaringType.Name + "." + EventInfo.Name);
3764
3765                                         return false;
3766                                 }
3767                         }
3768
3769                         return true;
3770                 }
3771
3772                 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
3773                 {
3774                         return DoResolve (ec);
3775                 }
3776
3777                 public override Expression DoResolve (EmitContext ec)
3778                 {
3779                         if (!IsInstance)
3780                                 InstanceExpression = null;
3781
3782                         if (InstanceExpression != null) {
3783                                 InstanceExpression = InstanceExpression.DoResolve (ec);
3784                                 if (InstanceExpression == null)
3785                                         return null;
3786                         }
3787
3788                         bool must_do_cs1540_check;
3789                         if (!(IsAccessorAccessible (ec.ContainerType, add_accessor, out must_do_cs1540_check) &&
3790                               IsAccessorAccessible (ec.ContainerType, remove_accessor, out must_do_cs1540_check))) {
3791                                 
3792                                Report.Error (122, loc, "'{0}' is inaccessible due to its protection level",
3793                                                DeclaringType.Name + "." + EventInfo.Name);
3794                                return null;
3795                         }
3796
3797                         if (!InstanceResolve (ec, must_do_cs1540_check))
3798                                 return null;
3799                         
3800                         return this;
3801                 }               
3802
3803                 public override void Emit (EmitContext ec)
3804                 {
3805                         if (InstanceExpression is This)
3806                                 Report.Error (79, loc, "The event `{0}' can only appear on the left hand side of += or -=, try calling the actual delegate", Name);
3807                         else
3808                                 Report.Error (70, loc, "The event `{0}' can only appear on the left hand side of += or -= "+
3809                                               "(except on the defining type)", Name);
3810                 }
3811
3812                 public void EmitAddOrRemove (EmitContext ec, Expression source)
3813                 {
3814                         BinaryDelegate source_del = (BinaryDelegate) source;
3815                         Expression handler = source_del.Right;
3816                         
3817                         Argument arg = new Argument (handler, Argument.AType.Expression);
3818                         ArrayList args = new ArrayList ();
3819                                 
3820                         args.Add (arg);
3821                         
3822                         if (source_del.IsAddition)
3823                                 Invocation.EmitCall (
3824                                         ec, false, IsStatic, InstanceExpression, add_accessor, args, loc);
3825                         else
3826                                 Invocation.EmitCall (
3827                                         ec, false, IsStatic, InstanceExpression, remove_accessor, args, loc);
3828                 }
3829         }
3830 }