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