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