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