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