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