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