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