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