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