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