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