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