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