2007-02-24 Marek Safar <marek.safar@gmail.com>
[mono.git] / mcs / mcs / ecore.cs
1 //
2 // ecore.cs: Core of the Expression representation for the intermediate tree.
3 //
4 // Author:
5 //   Miguel de Icaza (miguel@ximian.com)
6 //   Marek Safar (marek.safar@seznam.cz)
7 //
8 // (C) 2001, 2002, 2003 Ximian, Inc.
9 //
10 //
11
12 namespace Mono.CSharp {
13         using System;
14         using System.Collections;
15         using System.Diagnostics;
16         using System.Reflection;
17         using System.Reflection.Emit;
18         using System.Text;
19
20         /// <remarks>
21         ///   The ExprClass class contains the is used to pass the 
22         ///   classification of an expression (value, variable, namespace,
23         ///   type, method group, property access, event access, indexer access,
24         ///   nothing).
25         /// </remarks>
26         public enum ExprClass : byte {
27                 Invalid,
28                 
29                 Value,
30                 Variable,
31                 Namespace,
32                 Type,
33                 MethodGroup,
34                 PropertyAccess,
35                 EventAccess,
36                 IndexerAccess,
37                 Nothing, 
38         }
39
40         /// <remarks>
41         ///   This is used to tell Resolve in which types of expressions we're
42         ///   interested.
43         /// </remarks>
44         [Flags]
45         public enum ResolveFlags {
46                 // Returns Value, Variable, PropertyAccess, EventAccess or IndexerAccess.
47                 VariableOrValue         = 1,
48
49                 // Returns a type expression.
50                 Type                    = 2,
51
52                 // Returns a method group.
53                 MethodGroup             = 4,
54
55                 // Mask of all the expression class flags.
56                 MaskExprClass           = 7,
57
58                 // Disable control flow analysis while resolving the expression.
59                 // This is used when resolving the instance expression of a field expression.
60                 DisableFlowAnalysis     = 8,
61
62                 // Set if this is resolving the first part of a MemberAccess.
63                 Intermediate            = 16,
64
65                 // Disable control flow analysis _of struct_ while resolving the expression.
66                 // This is used when resolving the instance expression of a field expression.
67                 DisableStructFlowAnalysis       = 32,
68
69         }
70
71         //
72         // This is just as a hint to AddressOf of what will be done with the
73         // address.
74         [Flags]
75         public enum AddressOp {
76                 Store = 1,
77                 Load  = 2,
78                 LoadStore = 3
79         };
80         
81         /// <summary>
82         ///   This interface is implemented by variables
83         /// </summary>
84         public interface IMemoryLocation {
85                 /// <summary>
86                 ///   The AddressOf method should generate code that loads
87                 ///   the address of the object and leaves it on the stack.
88                 ///
89                 ///   The `mode' argument is used to notify the expression
90                 ///   of whether this will be used to read from the address or
91                 ///   write to the address.
92                 ///
93                 ///   This is just a hint that can be used to provide good error
94                 ///   reporting, and should have no other side effects. 
95                 /// </summary>
96                 void AddressOf (EmitContext ec, AddressOp mode);
97         }
98
99         /// <summary>
100         ///   This interface is implemented by variables
101         /// </summary>
102         public interface IVariable {
103                 VariableInfo VariableInfo {
104                         get;
105                 }
106
107                 bool VerifyFixed ();
108         }
109
110         /// <remarks>
111         ///   Base class for expressions
112         /// </remarks>
113         public abstract class Expression {
114                 public ExprClass eclass;
115                 protected Type type;
116                 protected Location loc;
117                 
118                 public Type Type {
119                         get { return type; }
120                         set { type = value; }
121                 }
122
123                 public virtual Location Location {
124                         get { return loc; }
125                 }
126
127                 /// <summary>
128                 ///   Utility wrapper routine for Error, just to beautify the code
129                 /// </summary>
130                 public void Error (int error, string s)
131                 {
132                         Report.Error (error, loc, s);
133                 }
134
135                 // Not nice but we have broken hierarchy.
136                 public virtual void CheckMarshalByRefAccess ()
137                 {
138                 }
139
140                 public virtual bool GetAttributableValue (Type valueType, 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                         TypeExpr te = ResolveAsBaseTerminal (ec, silent);
239                         if (te == null)
240                                 return null;
241
242                         if (!silent) {
243                                 ObsoleteAttribute obsolete_attr = AttributeTester.GetObsoleteAttribute (te.Type);
244                                 if (obsolete_attr != null && !ec.IsInObsoleteScope) {
245                                         AttributeTester.Report_ObsoleteMessage (obsolete_attr, te.GetSignatureForError (), Location);
246                                 }
247                         }
248
249                         // Constrains don't need to be checked for overrides
250                         GenericMethod gm = ec.GenericDeclContainer as GenericMethod;
251                         if (gm != null && (gm.ModFlags & Modifiers.OVERRIDE) != 0) {
252                                 te.loc = loc;
253                                 return te;
254                         }
255
256                         ConstructedType ct = te as ConstructedType;
257                         if ((ct != null) && !ct.CheckConstraints (ec))
258                                 return null;
259
260                         return te;
261                 }
262
263                 public TypeExpr ResolveAsBaseTerminal (IResolveContext ec, bool silent)
264                 {
265                         int errors = Report.Errors;
266
267                         FullNamedExpression fne = ResolveAsTypeStep (ec, silent);
268
269                         if (fne == null)
270                                 return null;
271
272                         if (fne.eclass != ExprClass.Type) {
273                                 if (!silent && errors == Report.Errors)
274                                         fne.Error_UnexpectedKind (null, "type", loc);
275                                 return null;
276                         }
277
278                         TypeExpr te = fne as TypeExpr;
279
280                         if (!te.CheckAccessLevel (ec.DeclContainer)) {
281                                 Report.SymbolRelatedToPreviousError (te.Type);
282                                 ErrorIsInaccesible (loc, TypeManager.CSharpName (te.Type));
283                                 return null;
284                         }
285
286                         te.loc = loc;
287                         return te;
288                 }
289
290                 public static void ErrorIsInaccesible (Location loc, string name)
291                 {
292                         Report.Error (122, loc, "`{0}' is inaccessible due to its protection level", name);
293                 }
294
295                 protected static void Error_CannotAccessProtected (Location loc, MemberInfo m, Type qualifier, Type container)
296                 {
297                         Report.Error (1540, loc, "Cannot access protected member `{0}' via a qualifier of type `{1}'."
298                                 + " The qualifier must be of type `{2}' or derived from it", 
299                                 TypeManager.GetFullNameSignature (m),
300                                 TypeManager.CSharpName (qualifier),
301                                 TypeManager.CSharpName (container));
302
303                 }
304
305                 public static void Error_InvalidExpressionStatement (Location loc)
306                 {
307                         Report.Error (201, loc, "Only assignment, call, increment, decrement, and new object " +
308                                        "expressions can be used as a statement");
309                 }
310                 
311                 public void Error_InvalidExpressionStatement ()
312                 {
313                         Error_InvalidExpressionStatement (loc);
314                 }
315
316                 protected void Error_CannotAssign (string to, string roContext)
317                 {
318                         Report.Error (1656, loc, "Cannot assign to `{0}' because it is a `{1}'",
319                                 to, roContext);
320                 }
321
322                 public static void Error_VoidInvalidInTheContext (Location loc)
323                 {
324                         Report.Error (1547, loc, "Keyword `void' cannot be used in this context");
325                 }
326
327                 public virtual void Error_ValueCannotBeConverted (EmitContext ec, Location loc, Type target, bool expl)
328                 {
329                         if (Type.FullName == target.FullName){
330                                 Report.ExtraInformation (loc,
331                                         String.Format (
332                                         "The type {0} has two conflicting definitions, one comes from {1} and the other from {2}",
333                                         Type.FullName, Type.Assembly.FullName, target.Assembly.FullName));
334                                                          
335                         }
336
337                         if (expl) {
338                                 Report.Error (30, loc, "Cannot convert type `{0}' to `{1}'",
339                                         GetSignatureForError (), TypeManager.CSharpName (target));
340                                 return;
341                         }
342                         
343                         Expression e = (this is EnumConstant) ? ((EnumConstant)this).Child : this;
344                         bool b = Convert.ExplicitNumericConversion (e, target) != null;
345
346                         if (b ||
347                             Convert.ExplicitReferenceConversionExists (Type, target) ||
348                             Convert.ExplicitUnsafe (e, target) != null ||
349                             (ec != null && Convert.UserDefinedConversion (ec, this, target, Location.Null, true) != null))
350                         {
351                                 Report.Error (266, loc, "Cannot implicitly convert type `{0}' to `{1}'. " +
352                                               "An explicit conversion exists (are you missing a cast?)",
353                                         TypeManager.CSharpName (Type), TypeManager.CSharpName (target));
354                                 return;
355                         }
356
357                         if (Type != TypeManager.string_type && this is Constant && !(this is EmptyConstantCast)) {
358                                 Report.Error (31, loc, "Constant value `{0}' cannot be converted to a `{1}'",
359                                         ((Constant)(this)).GetValue ().ToString (), TypeManager.CSharpName (target));
360                                 return;
361                         }
362
363                         Report.Error (29, loc, "Cannot implicitly convert type {0} to `{1}'",
364                                 Type == TypeManager.anonymous_method_type ?
365                                 "anonymous method" : "`" + GetSignatureForError () + "'",
366                                 TypeManager.CSharpName (target));
367                 }
368
369                 public static void Error_TypeDoesNotContainDefinition (Location loc, Type type, string name)
370                 {
371                         Report.Error (117, loc, "`{0}' does not contain a definition for `{1}'",
372                                 TypeManager.CSharpName (type), name);
373                 }
374
375                 protected static void Error_ValueAssignment (Location loc)
376                 {
377                         Report.Error (131, loc, "The left-hand side of an assignment must be a variable, a property or an indexer");
378                 }
379
380                 ResolveFlags ExprClassToResolveFlags
381                 {
382                         get {
383                                 switch (eclass) {
384                                         case ExprClass.Type:
385                                         case ExprClass.Namespace:
386                                                 return ResolveFlags.Type;
387
388                                         case ExprClass.MethodGroup:
389                                                 return ResolveFlags.MethodGroup;
390
391                                         case ExprClass.Value:
392                                         case ExprClass.Variable:
393                                         case ExprClass.PropertyAccess:
394                                         case ExprClass.EventAccess:
395                                         case ExprClass.IndexerAccess:
396                                                 return ResolveFlags.VariableOrValue;
397
398                                         default:
399                                                 throw new Exception ("Expression " + GetType () +
400                                                         " ExprClass is Invalid after resolve");
401                                 }
402                         }
403                 }
404                
405                 /// <summary>
406                 ///   Resolves an expression and performs semantic analysis on it.
407                 /// </summary>
408                 ///
409                 /// <remarks>
410                 ///   Currently Resolve wraps DoResolve to perform sanity
411                 ///   checking and assertion checking on what we expect from Resolve.
412                 /// </remarks>
413                 public Expression Resolve (EmitContext ec, ResolveFlags flags)
414                 {
415                         if ((flags & ResolveFlags.MaskExprClass) == ResolveFlags.Type) 
416                                 return ResolveAsTypeStep (ec, false);
417
418                         bool do_flow_analysis = ec.DoFlowAnalysis;
419                         bool omit_struct_analysis = ec.OmitStructFlowAnalysis;
420                         if ((flags & ResolveFlags.DisableFlowAnalysis) != 0)
421                                 do_flow_analysis = false;
422                         if ((flags & ResolveFlags.DisableStructFlowAnalysis) != 0)
423                                 omit_struct_analysis = true;
424
425                         Expression e;
426                         using (ec.WithFlowAnalysis (do_flow_analysis, omit_struct_analysis)) {
427                                 if (this is SimpleName) {
428                                         bool intermediate = (flags & ResolveFlags.Intermediate) == ResolveFlags.Intermediate;
429                                         e = ((SimpleName) this).DoResolve (ec, intermediate);
430                                 } else {
431                                         e = DoResolve (ec);
432                                 }
433                         }
434
435                         if (e == null)
436                                 return null;
437
438                         if ((flags & e.ExprClassToResolveFlags) == 0) {
439                                 e.Error_UnexpectedKind (flags, loc);
440                                 return null;
441                         }
442
443                         if (e.type == null && !(e is Namespace)) {
444                                 throw new Exception (
445                                         "Expression " + e.GetType () +
446                                         " did not set its type after Resolve\n" +
447                                         "called from: " + this.GetType ());
448                         }
449
450                         return e;
451                 }
452
453                 /// <summary>
454                 ///   Resolves an expression and performs semantic analysis on it.
455                 /// </summary>
456                 public Expression Resolve (EmitContext ec)
457                 {
458                         Expression e = Resolve (ec, ResolveFlags.VariableOrValue | ResolveFlags.MethodGroup);
459
460                         if (e != null && e.eclass == ExprClass.MethodGroup && RootContext.Version == LanguageVersion.ISO_1) {
461                                 ((MethodGroupExpr) e).ReportUsageError ();
462                                 return null;
463                         }
464                         return e;
465                 }
466
467                 public Constant ResolveAsConstant (EmitContext ec, MemberCore mc)
468                 {
469                         Expression e = Resolve (ec);
470                         if (e == null)
471                                 return null;
472
473                         Constant c = e as Constant;
474                         if (c != null)
475                                 return c;
476
477                         Const.Error_ExpressionMustBeConstant (loc, mc.GetSignatureForError ());
478                         return null;
479                 }
480
481                 /// <summary>
482                 ///   Resolves an expression for LValue assignment
483                 /// </summary>
484                 ///
485                 /// <remarks>
486                 ///   Currently ResolveLValue wraps DoResolveLValue to perform sanity
487                 ///   checking and assertion checking on what we expect from Resolve
488                 /// </remarks>
489                 public Expression ResolveLValue (EmitContext ec, Expression right_side, Location loc)
490                 {
491                         int errors = Report.Errors;
492                         bool out_access = right_side == EmptyExpression.OutAccess;
493
494                         Expression e = DoResolveLValue (ec, right_side);
495
496                         if (e != null && out_access && !(e is IMemoryLocation)) {
497                                 // FIXME: There's no problem with correctness, the 'Expr = null' handles that.
498                                 //        Enabling this 'throw' will "only" result in deleting useless code elsewhere,
499
500                                 //throw new InternalErrorException ("ResolveLValue didn't return an IMemoryLocation: " +
501                                 //                                e.GetType () + " " + e.GetSignatureForError ());
502                                 e = null;
503                         }
504
505                         if (e == null) {
506                                 if (errors == Report.Errors) {
507                                         if (out_access)
508                                                 Report.Error (1510, loc, "A ref or out argument must be an assignable variable");
509                                         else
510                                                 Error_ValueAssignment (loc);
511                                 }
512                                 return null;
513                         }
514
515                         if (e.eclass == ExprClass.Invalid)
516                                 throw new Exception ("Expression " + e + " ExprClass is Invalid after resolve");
517
518                         if (e.eclass == ExprClass.MethodGroup) {
519                                 ((MethodGroupExpr) e).ReportUsageError ();
520                                 return null;
521                         }
522
523                         if ((e.type == null) && !(e is ConstructedType))
524                                 throw new Exception ("Expression " + e + " did not set its type after Resolve");
525
526                         return e;
527                 }
528
529                 /// <summary>
530                 ///   Emits the code for the expression
531                 /// </summary>
532                 ///
533                 /// <remarks>
534                 ///   The Emit method is invoked to generate the code
535                 ///   for the expression.  
536                 /// </remarks>
537                 public abstract void Emit (EmitContext ec);
538
539                 public virtual void EmitBranchable (EmitContext ec, Label target, bool onTrue)
540                 {
541                         Emit (ec);
542                         ec.ig.Emit (onTrue ? OpCodes.Brtrue : OpCodes.Brfalse, target);
543                 }
544
545                 /// <summary>
546                 ///   Protected constructor.  Only derivate types should
547                 ///   be able to be created
548                 /// </summary>
549
550                 protected Expression ()
551                 {
552                         eclass = ExprClass.Invalid;
553                         type = null;
554                 }
555
556                 /// <summary>
557                 ///   Returns a fully formed expression after a MemberLookup
558                 /// </summary>
559                 /// 
560                 public static Expression ExprClassFromMemberInfo (Type containerType, MemberInfo mi, Location loc)
561                 {
562                         if (mi is EventInfo)
563                                 return new EventExpr ((EventInfo) mi, loc);
564                         else if (mi is FieldInfo)
565                                 return new FieldExpr ((FieldInfo) mi, loc);
566                         else if (mi is PropertyInfo)
567                                 return new PropertyExpr (containerType, (PropertyInfo) mi, loc);
568                         else if (mi is Type){
569                                 return new TypeExpression ((System.Type) mi, loc);
570                         }
571
572                         return null;
573                 }
574
575                 protected static ArrayList almostMatchedMembers = new ArrayList (4);
576
577                 //
578                 // FIXME: Probably implement a cache for (t,name,current_access_set)?
579                 //
580                 // This code could use some optimizations, but we need to do some
581                 // measurements.  For example, we could use a delegate to `flag' when
582                 // something can not any longer be a method-group (because it is something
583                 // else).
584                 //
585                 // Return values:
586                 //     If the return value is an Array, then it is an array of
587                 //     MethodBases
588                 //   
589                 //     If the return value is an MemberInfo, it is anything, but a Method
590                 //
591                 //     null on error.
592                 //
593                 // FIXME: When calling MemberLookup inside an `Invocation', we should pass
594                 // the arguments here and have MemberLookup return only the methods that
595                 // match the argument count/type, unlike we are doing now (we delay this
596                 // decision).
597                 //
598                 // This is so we can catch correctly attempts to invoke instance methods
599                 // from a static body (scan for error 120 in ResolveSimpleName).
600                 //
601                 //
602                 // FIXME: Potential optimization, have a static ArrayList
603                 //
604
605                 public static Expression MemberLookup (Type container_type, Type queried_type, string name,
606                                                        MemberTypes mt, BindingFlags bf, Location loc)
607                 {
608                         return MemberLookup (container_type, null, queried_type, name, mt, bf, loc);
609                 }
610
611                 //
612                 // Lookup type `queried_type' for code in class `container_type' with a qualifier of
613                 // `qualifier_type' or null to lookup members in the current class.
614                 //
615
616                 public static Expression MemberLookup (Type container_type,
617                                                        Type qualifier_type, Type queried_type,
618                                                        string name, MemberTypes mt,
619                                                        BindingFlags bf, Location loc)
620                 {
621                         almostMatchedMembers.Clear ();
622
623                         MemberInfo [] mi = TypeManager.MemberLookup (container_type, qualifier_type,
624                                                                      queried_type, mt, bf, name, almostMatchedMembers);
625
626                         if (mi == null)
627                                 return null;
628
629                         if (mi.Length > 1) {
630                                 bool is_interface = qualifier_type != null && qualifier_type.IsInterface;
631                                 ArrayList methods = new ArrayList (2);
632                                 ArrayList non_methods = null;
633
634                                 foreach (MemberInfo m in mi) {
635                                         if (m is MethodBase) {
636                                                 methods.Add (m);
637                                                 continue;
638                                         }
639
640                                         if (non_methods == null) {
641                                                 non_methods = new ArrayList (2);
642                                                 non_methods.Add (m);
643                                                 continue;
644                                         }
645
646                                         foreach (MemberInfo n_m in non_methods) {
647                                                 if (m.DeclaringType.IsInterface && TypeManager.ImplementsInterface (m.DeclaringType, n_m.DeclaringType))
648                                                         continue;
649
650                                                 Report.SymbolRelatedToPreviousError (m);
651                                                 Report.Error (229, loc, "Ambiguity between `{0}' and `{1}'",
652                                                         TypeManager.GetFullNameSignature (m), TypeManager.GetFullNameSignature (n_m));
653                                                 return null;
654                                         }
655                                 }
656
657                                 if (methods.Count == 0)
658                                         return ExprClassFromMemberInfo (container_type, (MemberInfo)non_methods [0], loc);
659
660                                 if (non_methods != null) {
661                                         MethodBase method = (MethodBase) methods [0];
662                                         MemberInfo non_method = (MemberInfo) non_methods [0];
663                                         if (method.DeclaringType == non_method.DeclaringType) {
664                                                 // Cannot happen with C# code, but is valid in IL
665                                                 Report.SymbolRelatedToPreviousError (method);
666                                                 Report.SymbolRelatedToPreviousError (non_method);
667                                                 Report.Error (229, loc, "Ambiguity between `{0}' and `{1}'",
668                                                               TypeManager.GetFullNameSignature (non_method),
669                                                               TypeManager.CSharpSignature (method));
670                                                 return null;
671                                         }
672
673                                         if (is_interface) {
674                                                 Report.SymbolRelatedToPreviousError (method);
675                                                 Report.SymbolRelatedToPreviousError (non_method);
676                                                 Report.Warning (467, 2, loc, "Ambiguity between method `{0}' and non-method `{1}'. Using method `{0}'",
677                                                                 TypeManager.CSharpSignature (method), TypeManager.GetFullNameSignature (non_method));
678                                         }
679                                 }
680
681                                 return new MethodGroupExpr (methods, loc);
682                         }
683
684                         if (mi [0] is MethodBase)
685                                 return new MethodGroupExpr (mi, loc);
686
687                         return ExprClassFromMemberInfo (container_type, mi [0], loc);
688                 }
689
690                 public const MemberTypes AllMemberTypes =
691                         MemberTypes.Constructor |
692                         MemberTypes.Event       |
693                         MemberTypes.Field       |
694                         MemberTypes.Method      |
695                         MemberTypes.NestedType  |
696                         MemberTypes.Property;
697                 
698                 public const BindingFlags AllBindingFlags =
699                         BindingFlags.Public |
700                         BindingFlags.Static |
701                         BindingFlags.Instance;
702
703                 public static Expression MemberLookup (Type container_type, Type queried_type,
704                                                        string name, Location loc)
705                 {
706                         return MemberLookup (container_type, null, queried_type, name,
707                                              AllMemberTypes, AllBindingFlags, loc);
708                 }
709
710                 public static Expression MemberLookup (Type container_type, Type qualifier_type,
711                                                        Type queried_type, string name, Location loc)
712                 {
713                         return MemberLookup (container_type, qualifier_type, queried_type,
714                                              name, AllMemberTypes, AllBindingFlags, loc);
715                 }
716
717                 public static MethodGroupExpr MethodLookup (Type container_type, Type queried_type,
718                                                        string name, Location loc)
719                 {
720                         return (MethodGroupExpr)MemberLookup (container_type, null, queried_type, name,
721                                              MemberTypes.Method, AllBindingFlags, loc);
722                 }
723
724                 /// <summary>
725                 ///   This is a wrapper for MemberLookup that is not used to "probe", but
726                 ///   to find a final definition.  If the final definition is not found, we
727                 ///   look for private members and display a useful debugging message if we
728                 ///   find it.
729                 /// </summary>
730                 public static Expression MemberLookupFinal (EmitContext ec, Type qualifier_type,
731                                                             Type queried_type, string name, Location loc)
732                 {
733                         return MemberLookupFinal (ec, qualifier_type, queried_type, name,
734                                                   AllMemberTypes, AllBindingFlags, loc);
735                 }
736
737                 public static Expression MemberLookupFinal (EmitContext ec, Type qualifier_type,
738                                                             Type queried_type, string name,
739                                                             MemberTypes mt, BindingFlags bf,
740                                                             Location loc)
741                 {
742                         Expression e;
743
744                         int errors = Report.Errors;
745
746                         e = MemberLookup (ec.ContainerType, qualifier_type, queried_type, name, mt, bf, loc);
747
748                         if (e == null && errors == Report.Errors)
749                                 // No errors were reported by MemberLookup, but there was an error.
750                                 MemberLookupFailed (ec.ContainerType, qualifier_type, queried_type, name, null, true, loc);
751
752                         return e;
753                 }
754
755                 public static void MemberLookupFailed (Type container_type, Type qualifier_type,
756                                                        Type queried_type, string name,
757                                                        string class_name, bool complain_if_none_found, 
758                                                        Location loc)
759                 {
760                         if (almostMatchedMembers.Count != 0) {
761                                 for (int i = 0; i < almostMatchedMembers.Count; ++i) {
762                                         MemberInfo m = (MemberInfo) almostMatchedMembers [i];
763                                         for (int j = 0; j < i; ++j) {
764                                                 if (m == almostMatchedMembers [j]) {
765                                                         m = null;
766                                                         break;
767                                                 }
768                                         }
769                                         if (m == null)
770                                                 continue;
771                                         
772                                         Type declaring_type = m.DeclaringType;
773                                         
774                                         Report.SymbolRelatedToPreviousError (m);
775                                         if (qualifier_type == null) {
776                                                 Report.Error (38, loc, "Cannot access a nonstatic member of outer type `{0}' via nested type `{1}'",
777                                                               TypeManager.CSharpName (m.DeclaringType),
778                                                               TypeManager.CSharpName (container_type));
779                                                 
780                                         } else if (qualifier_type != container_type &&
781                                                    TypeManager.IsNestedFamilyAccessible (container_type, declaring_type)) {
782                                                 // Although a derived class can access protected members of
783                                                 // its base class it cannot do so through an instance of the
784                                                 // base class (CS1540).  If the qualifier_type is a base of the
785                                                 // ec.ContainerType and the lookup succeeds with the latter one,
786                                                 // then we are in this situation.
787                                                 Error_CannotAccessProtected (loc, m, qualifier_type, container_type);
788                                         } else {
789                                                 ErrorIsInaccesible (loc, TypeManager.GetFullNameSignature (m));
790                                         }
791                                 }
792                                 almostMatchedMembers.Clear ();
793                                 return;
794                         }
795
796                         MemberInfo[] lookup = null;
797                         if (queried_type == null) {
798                                 class_name = "global::";
799                         } else {
800                                 lookup = TypeManager.MemberLookup (queried_type, null, queried_type,
801                                         AllMemberTypes, AllBindingFlags |
802                                         BindingFlags.NonPublic, name, null);
803                         }
804
805                         if (lookup == null) {
806                                 if (!complain_if_none_found)
807                                         return;
808
809                                 if (class_name != null)
810                                         Report.Error (103, loc, "The name `{0}' does not exist in the context of `{1}'",
811                                                 name, class_name);
812                                 else
813                                         Error_TypeDoesNotContainDefinition (loc, queried_type, name);
814                                 return;
815                         }
816
817                         if (TypeManager.MemberLookup (queried_type, null, queried_type,
818                                                       AllMemberTypes, AllBindingFlags |
819                                                       BindingFlags.NonPublic, name, null) == null) {
820                                 if ((lookup.Length == 1) && (lookup [0] is Type)) {
821                                         Type t = (Type) lookup [0];
822
823                                         Report.Error (305, loc,
824                                                       "Using the generic type `{0}' " +
825                                                       "requires {1} type arguments",
826                                                       TypeManager.CSharpName (t),
827                                                       TypeManager.GetNumberOfTypeArguments (t).ToString ());
828                                         return;
829                                 }
830                         }
831
832                         MemberList ml = TypeManager.FindMembers (queried_type, MemberTypes.Constructor,
833                                                                  BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly, null, null);
834                         if (name == ".ctor" && ml.Count == 0)
835                         {
836                                 Report.Error (143, loc, "The type `{0}' has no constructors defined", TypeManager.CSharpName (queried_type));
837                                 return;
838                         }
839
840                         Report.SymbolRelatedToPreviousError (lookup [0]);
841                         ErrorIsInaccesible (loc, TypeManager.GetFullNameSignature (lookup [0]));
842                 }
843
844                 /// <summary>
845                 ///   Returns an expression that can be used to invoke operator true
846                 ///   on the expression if it exists.
847                 /// </summary>
848                 static public Expression GetOperatorTrue (EmitContext ec, Expression e, Location loc)
849                 {
850                         return GetOperatorTrueOrFalse (ec, e, true, loc);
851                 }
852
853                 /// <summary>
854                 ///   Returns an expression that can be used to invoke operator false
855                 ///   on the expression if it exists.
856                 /// </summary>
857                 static public Expression GetOperatorFalse (EmitContext ec, Expression e, Location loc)
858                 {
859                         return GetOperatorTrueOrFalse (ec, e, false, loc);
860                 }
861
862                 static Expression GetOperatorTrueOrFalse (EmitContext ec, Expression e, bool is_true, Location loc)
863                 {
864                         MethodBase method;
865                         Expression operator_group;
866
867 #if GMCS_SOURCE
868                         if (TypeManager.IsNullableType (e.Type))
869                                 return new Nullable.OperatorTrueOrFalse (e, is_true, loc).Resolve (ec);
870 #endif
871
872                         operator_group = MethodLookup (ec.ContainerType, e.Type, is_true ? "op_True" : "op_False", loc);
873                         if (operator_group == null)
874                                 return null;
875
876                         ArrayList arguments = new ArrayList ();
877                         arguments.Add (new Argument (e, Argument.AType.Expression));
878                         method = ((MethodGroupExpr) operator_group).OverloadResolve (
879                                 ec, arguments, false, loc);
880
881                         if (method == null)
882                                 return null;
883
884                         return new StaticCallExpr ((MethodInfo) method, arguments, loc);
885                 }
886
887                 /// <summary>
888                 ///   Resolves the expression `e' into a boolean expression: either through
889                 ///   an implicit conversion, or through an `operator true' invocation
890                 /// </summary>
891                 public static Expression ResolveBoolean (EmitContext ec, Expression e, Location loc)
892                 {
893                         e = e.Resolve (ec);
894                         if (e == null)
895                                 return null;
896
897                         if (e.Type == TypeManager.bool_type)
898                                 return e;
899
900                         Expression converted = Convert.ImplicitConversion (ec, e, TypeManager.bool_type, Location.Null);
901
902                         if (converted != null)
903                                 return converted;
904
905                         //
906                         // If no implicit conversion to bool exists, try using `operator true'
907                         //
908                         converted = Expression.GetOperatorTrue (ec, e, loc);
909                         if (converted == null){
910                                 e.Error_ValueCannotBeConverted (ec, loc, TypeManager.bool_type, false);
911                                 return null;
912                         }
913                         return converted;
914                 }
915                 
916                 public virtual string ExprClassName
917                 {
918                         get {
919                                 switch (eclass){
920                                         case ExprClass.Invalid:
921                                                 return "Invalid";
922                                         case ExprClass.Value:
923                                                 return "value";
924                                         case ExprClass.Variable:
925                                                 return "variable";
926                                         case ExprClass.Namespace:
927                                                 return "namespace";
928                                         case ExprClass.Type:
929                                                 return "type";
930                                         case ExprClass.MethodGroup:
931                                                 return "method group";
932                                         case ExprClass.PropertyAccess:
933                                                 return "property access";
934                                         case ExprClass.EventAccess:
935                                                 return "event access";
936                                         case ExprClass.IndexerAccess:
937                                                 return "indexer access";
938                                         case ExprClass.Nothing:
939                                                 return "null";
940                                 }
941                                 throw new Exception ("Should not happen");
942                         }
943                 }
944                 
945                 /// <summary>
946                 ///   Reports that we were expecting `expr' to be of class `expected'
947                 /// </summary>
948                 public void Error_UnexpectedKind (DeclSpace ds, string expected, Location loc)
949                 {
950                         Error_UnexpectedKind (ds, expected, ExprClassName, loc);
951                 }
952
953                 public void Error_UnexpectedKind (DeclSpace ds, string expected, string was, Location loc)
954                 {
955                         string name = GetSignatureForError ();
956                         if (ds != null)
957                                 name = ds.GetSignatureForError () + '.' + name;
958
959                         Report.Error (118, loc, "`{0}' is a `{1}' but a `{2}' was expected",
960                               name, was, expected);
961                 }
962
963                 public void Error_UnexpectedKind (ResolveFlags flags, Location loc)
964                 {
965                         string [] valid = new string [4];
966                         int count = 0;
967
968                         if ((flags & ResolveFlags.VariableOrValue) != 0) {
969                                 valid [count++] = "variable";
970                                 valid [count++] = "value";
971                         }
972
973                         if ((flags & ResolveFlags.Type) != 0)
974                                 valid [count++] = "type";
975
976                         if ((flags & ResolveFlags.MethodGroup) != 0)
977                                 valid [count++] = "method group";
978
979                         if (count == 0)
980                                 valid [count++] = "unknown";
981
982                         StringBuilder sb = new StringBuilder (valid [0]);
983                         for (int i = 1; i < count - 1; i++) {
984                                 sb.Append ("', `");
985                                 sb.Append (valid [i]);
986                         }
987                         if (count > 1) {
988                                 sb.Append ("' or `");
989                                 sb.Append (valid [count - 1]);
990                         }
991
992                         Report.Error (119, loc, 
993                                 "Expression denotes a `{0}', where a `{1}' was expected", ExprClassName, sb.ToString ());
994                 }
995                 
996                 public static void UnsafeError (Location loc)
997                 {
998                         Report.Error (214, loc, "Pointers and fixed size buffers may only be used in an unsafe context");
999                 }
1000
1001                 //
1002                 // Load the object from the pointer.  
1003                 //
1004                 public static void LoadFromPtr (ILGenerator ig, Type t)
1005                 {
1006                         if (t == TypeManager.int32_type)
1007                                 ig.Emit (OpCodes.Ldind_I4);
1008                         else if (t == TypeManager.uint32_type)
1009                                 ig.Emit (OpCodes.Ldind_U4);
1010                         else if (t == TypeManager.short_type)
1011                                 ig.Emit (OpCodes.Ldind_I2);
1012                         else if (t == TypeManager.ushort_type)
1013                                 ig.Emit (OpCodes.Ldind_U2);
1014                         else if (t == TypeManager.char_type)
1015                                 ig.Emit (OpCodes.Ldind_U2);
1016                         else if (t == TypeManager.byte_type)
1017                                 ig.Emit (OpCodes.Ldind_U1);
1018                         else if (t == TypeManager.sbyte_type)
1019                                 ig.Emit (OpCodes.Ldind_I1);
1020                         else if (t == TypeManager.uint64_type)
1021                                 ig.Emit (OpCodes.Ldind_I8);
1022                         else if (t == TypeManager.int64_type)
1023                                 ig.Emit (OpCodes.Ldind_I8);
1024                         else if (t == TypeManager.float_type)
1025                                 ig.Emit (OpCodes.Ldind_R4);
1026                         else if (t == TypeManager.double_type)
1027                                 ig.Emit (OpCodes.Ldind_R8);
1028                         else if (t == TypeManager.bool_type)
1029                                 ig.Emit (OpCodes.Ldind_I1);
1030                         else if (t == TypeManager.intptr_type)
1031                                 ig.Emit (OpCodes.Ldind_I);
1032                         else if (TypeManager.IsEnumType (t)) {
1033                                 if (t == TypeManager.enum_type)
1034                                         ig.Emit (OpCodes.Ldind_Ref);
1035                                 else
1036                                         LoadFromPtr (ig, TypeManager.EnumToUnderlying (t));
1037                         } else if (t.IsValueType || TypeManager.IsGenericParameter (t))
1038                                 ig.Emit (OpCodes.Ldobj, t);
1039                         else if (t.IsPointer)
1040                                 ig.Emit (OpCodes.Ldind_I);
1041                         else
1042                                 ig.Emit (OpCodes.Ldind_Ref);
1043                 }
1044
1045                 //
1046                 // The stack contains the pointer and the value of type `type'
1047                 //
1048                 public static void StoreFromPtr (ILGenerator ig, Type type)
1049                 {
1050                         if (TypeManager.IsEnumType (type))
1051                                 type = TypeManager.EnumToUnderlying (type);
1052                         if (type == TypeManager.int32_type || type == TypeManager.uint32_type)
1053                                 ig.Emit (OpCodes.Stind_I4);
1054                         else if (type == TypeManager.int64_type || type == TypeManager.uint64_type)
1055                                 ig.Emit (OpCodes.Stind_I8);
1056                         else if (type == TypeManager.char_type || type == TypeManager.short_type ||
1057                                  type == TypeManager.ushort_type)
1058                                 ig.Emit (OpCodes.Stind_I2);
1059                         else if (type == TypeManager.float_type)
1060                                 ig.Emit (OpCodes.Stind_R4);
1061                         else if (type == TypeManager.double_type)
1062                                 ig.Emit (OpCodes.Stind_R8);
1063                         else if (type == TypeManager.byte_type || type == TypeManager.sbyte_type ||
1064                                  type == TypeManager.bool_type)
1065                                 ig.Emit (OpCodes.Stind_I1);
1066                         else if (type == TypeManager.intptr_type)
1067                                 ig.Emit (OpCodes.Stind_I);
1068                         else if (type.IsValueType || TypeManager.IsGenericParameter (type))
1069                                 ig.Emit (OpCodes.Stobj, type);
1070                         else
1071                                 ig.Emit (OpCodes.Stind_Ref);
1072                 }
1073                 
1074                 //
1075                 // Returns the size of type `t' if known, otherwise, 0
1076                 //
1077                 public static int GetTypeSize (Type t)
1078                 {
1079                         t = TypeManager.TypeToCoreType (t);
1080                         if (t == TypeManager.int32_type ||
1081                             t == TypeManager.uint32_type ||
1082                             t == TypeManager.float_type)
1083                                 return 4;
1084                         else if (t == TypeManager.int64_type ||
1085                                  t == TypeManager.uint64_type ||
1086                                  t == TypeManager.double_type)
1087                                 return 8;
1088                         else if (t == TypeManager.byte_type ||
1089                                  t == TypeManager.sbyte_type ||
1090                                  t == TypeManager.bool_type)    
1091                                 return 1;
1092                         else if (t == TypeManager.short_type ||
1093                                  t == TypeManager.char_type ||
1094                                  t == TypeManager.ushort_type)
1095                                 return 2;
1096                         else if (t == TypeManager.decimal_type)
1097                                 return 16;
1098                         else
1099                                 return 0;
1100                 }
1101
1102                 public static void Error_NegativeArrayIndex (Location loc)
1103                 {
1104                         Report.Error (248, loc, "Cannot create an array with a negative size");
1105                 }
1106
1107                 protected void Error_CannotCallAbstractBase (string name)
1108                 {
1109                         Report.Error (205, loc, "Cannot call an abstract base member `{0}'", name);
1110                 }
1111                 
1112                 //
1113                 // Converts `source' to an int, uint, long or ulong.
1114                 //
1115                 public Expression ExpressionToArrayArgument (EmitContext ec, Expression source, Location loc)
1116                 {
1117                         Expression target;
1118                         
1119                         using (ec.With (EmitContext.Flags.CheckState, true)) {
1120                                 target = Convert.ImplicitConversion (ec, source, TypeManager.int32_type, loc);
1121                                 if (target == null)
1122                                         target = Convert.ImplicitConversion (ec, source, TypeManager.uint32_type, loc);
1123                                 if (target == null)
1124                                         target = Convert.ImplicitConversion (ec, source, TypeManager.int64_type, loc);
1125                                 if (target == null)
1126                                         target = Convert.ImplicitConversion (ec, source, TypeManager.uint64_type, loc);
1127
1128                                 if (target == null) {
1129                                         source.Error_ValueCannotBeConverted (ec, loc, TypeManager.int32_type, false);
1130                                         return null;
1131                                 }
1132                         }
1133
1134                         //
1135                         // Only positive constants are allowed at compile time
1136                         //
1137                         if (target is Constant){
1138                                 if (target is IntConstant){
1139                                         if (((IntConstant) target).Value < 0){
1140                                                 Error_NegativeArrayIndex (loc);
1141                                                 return null;
1142                                         }
1143                                 }
1144
1145                                 if (target is LongConstant){
1146                                         if (((LongConstant) target).Value < 0){
1147                                                 Error_NegativeArrayIndex (loc);
1148                                                 return null;
1149                                         }
1150                                 }
1151                                 
1152                         }
1153
1154                         return target;
1155                 }
1156
1157                 //
1158                 // Derived classes implement this method by cloning the fields that
1159                 // could become altered during the Resolve stage
1160                 //
1161                 // Only expressions that are created for the parser need to implement
1162                 // this.
1163                 //
1164                 protected virtual void CloneTo (CloneContext clonectx, Expression target)
1165                 {
1166                         throw new NotImplementedException (
1167                                 String.Format (
1168                                         "CloneTo not implemented for expression {0}", this.GetType ()));
1169                 }
1170
1171                 //
1172                 // Clones an expression created by the parser.
1173                 //
1174                 // We only support expressions created by the parser so far, not
1175                 // expressions that have been resolved (many more classes would need
1176                 // to implement CloneTo).
1177                 //
1178                 // This infrastructure is here merely for Lambda expressions which
1179                 // compile the same code using different type values for the same
1180                 // arguments to find the correct overload
1181                 //
1182                 public Expression Clone (CloneContext clonectx)
1183                 {
1184                         Expression cloned = (Expression) MemberwiseClone ();
1185                         CloneTo (clonectx, cloned);
1186
1187                         return cloned;
1188                 }
1189         }
1190
1191         /// <summary>
1192         ///   This is just a base class for expressions that can
1193         ///   appear on statements (invocations, object creation,
1194         ///   assignments, post/pre increment and decrement).  The idea
1195         ///   being that they would support an extra Emition interface that
1196         ///   does not leave a result on the stack.
1197         /// </summary>
1198         public abstract class ExpressionStatement : Expression {
1199
1200                 public virtual ExpressionStatement ResolveStatement (EmitContext ec)
1201                 {
1202                         Expression e = Resolve (ec);
1203                         if (e == null)
1204                                 return null;
1205
1206                         ExpressionStatement es = e as ExpressionStatement;
1207                         if (es == null)
1208                                 Error_InvalidExpressionStatement ();
1209
1210                         return es;
1211                 }
1212
1213                 /// <summary>
1214                 ///   Requests the expression to be emitted in a `statement'
1215                 ///   context.  This means that no new value is left on the
1216                 ///   stack after invoking this method (constrasted with
1217                 ///   Emit that will always leave a value on the stack).
1218                 /// </summary>
1219                 public abstract void EmitStatement (EmitContext ec);
1220         }
1221
1222         /// <summary>
1223         ///   This kind of cast is used to encapsulate the child
1224         ///   whose type is child.Type into an expression that is
1225         ///   reported to return "return_type".  This is used to encapsulate
1226         ///   expressions which have compatible types, but need to be dealt
1227         ///   at higher levels with.
1228         ///
1229         ///   For example, a "byte" expression could be encapsulated in one
1230         ///   of these as an "unsigned int".  The type for the expression
1231         ///   would be "unsigned int".
1232         ///
1233         /// </summary>
1234         public class EmptyCast : Expression {
1235                 protected Expression child;
1236
1237                 public EmptyCast (Expression child, Type return_type)
1238                 {
1239                         eclass = child.eclass;
1240                         loc = child.Location;
1241                         type = return_type;
1242                         this.child = child;
1243                 }
1244
1245                 public override Expression DoResolve (EmitContext ec)
1246                 {
1247                         // This should never be invoked, we are born in fully
1248                         // initialized state.
1249
1250                         return this;
1251                 }
1252
1253                 public override void Emit (EmitContext ec)
1254                 {
1255                         child.Emit (ec);
1256                 }
1257
1258                 public override bool GetAttributableValue (Type valueType, out object value)
1259                 {
1260                         return child.GetAttributableValue (valueType, out value);
1261                 }
1262
1263                 protected override void CloneTo (CloneContext clonectx, Expression t)
1264                 {
1265                         EmptyCast target = (EmptyCast) t;
1266
1267                         target.child = child.Clone (clonectx);
1268                 }
1269         }
1270
1271         /// <summary>
1272         ///    Performs a cast using an operator (op_Explicit or op_Implicit)
1273         /// </summary>
1274         public class OperatorCast : EmptyCast {
1275                 MethodInfo conversion_operator;
1276                 bool find_explicit;
1277                         
1278                 public OperatorCast (Expression child, Type target_type) : this (child, target_type, false) {}
1279
1280                 public OperatorCast (Expression child, Type target_type, bool find_explicit)
1281                         : base (child, target_type)
1282                 {
1283                         this.find_explicit = find_explicit;
1284                 }
1285
1286                 // Returns the implicit operator that converts from
1287                 // 'child.Type' to our target type (type)
1288                 MethodInfo GetConversionOperator (bool find_explicit)
1289                 {
1290                         string operator_name = find_explicit ? "op_Explicit" : "op_Implicit";
1291
1292                         MemberInfo [] mi;
1293
1294                         mi = TypeManager.MemberLookup (child.Type, child.Type, child.Type, MemberTypes.Method,
1295                                 BindingFlags.Static | BindingFlags.Public, operator_name, null);
1296
1297                         if (mi == null){
1298                                 mi = TypeManager.MemberLookup (type, type, type, MemberTypes.Method,
1299                                                                BindingFlags.Static | BindingFlags.Public, operator_name, null);
1300                         }
1301                         
1302                         foreach (MethodInfo oper in mi) {
1303                                 ParameterData pd = TypeManager.GetParameterData (oper);
1304
1305                                 if (pd.ParameterType (0) == child.Type && oper.ReturnType == type)
1306                                         return oper;
1307                         }
1308
1309                         return null;
1310
1311
1312                 }
1313                 public override void Emit (EmitContext ec)
1314                 {
1315                         ILGenerator ig = ec.ig;
1316
1317                         child.Emit (ec);
1318                         conversion_operator = GetConversionOperator (find_explicit);
1319
1320                         if (conversion_operator == null)
1321                                 throw new InternalErrorException ("Outer conversion routine is out of sync");
1322
1323                         ig.Emit (OpCodes.Call, conversion_operator);
1324                 }
1325                 
1326         }
1327         
1328         /// <summary>
1329         ///     This is a numeric cast to a Decimal
1330         /// </summary>
1331         public class CastToDecimal : EmptyCast {
1332                 MethodInfo conversion_operator;
1333
1334                 public CastToDecimal (Expression child)
1335                         : this (child, false)
1336                 {
1337                 }
1338
1339                 public CastToDecimal (Expression child, bool find_explicit)
1340                         : base (child, TypeManager.decimal_type)
1341                 {
1342                         conversion_operator = GetConversionOperator (find_explicit);
1343
1344                         if (conversion_operator == null)
1345                                 throw new InternalErrorException ("Outer conversion routine is out of sync");
1346                 }
1347
1348                 // Returns the implicit operator that converts from
1349                 // 'child.Type' to System.Decimal.
1350                 MethodInfo GetConversionOperator (bool find_explicit)
1351                 {
1352                         string operator_name = find_explicit ? "op_Explicit" : "op_Implicit";
1353                         
1354                         MemberInfo [] mi = TypeManager.MemberLookup (type, type, type, MemberTypes.Method,
1355                                 BindingFlags.Static | BindingFlags.Public, operator_name, null);
1356
1357                         foreach (MethodInfo oper in mi) {
1358                                 ParameterData pd = TypeManager.GetParameterData (oper);
1359
1360                                 if (pd.ParameterType (0) == child.Type && oper.ReturnType == type)
1361                                         return oper;
1362                         }
1363
1364                         return null;
1365                 }
1366                 public override void Emit (EmitContext ec)
1367                 {
1368                         ILGenerator ig = ec.ig;
1369                         child.Emit (ec);
1370
1371                         ig.Emit (OpCodes.Call, conversion_operator);
1372                 }
1373         }
1374
1375         /// <summary>
1376         ///     This is an explicit numeric cast from a Decimal
1377         /// </summary>
1378         public class CastFromDecimal : EmptyCast
1379         {
1380                 static IDictionary operators;
1381
1382                 public CastFromDecimal (Expression child, Type return_type)
1383                         : base (child, return_type)
1384                 {
1385                         if (child.Type != TypeManager.decimal_type)
1386                                 throw new InternalErrorException (
1387                                         "The expected type is Decimal, instead it is " + child.Type.FullName);
1388                 }
1389
1390                 // Returns the explicit operator that converts from an
1391                 // express of type System.Decimal to 'type'.
1392                 public Expression Resolve ()
1393                 {
1394                         if (operators == null) {
1395                                  MemberInfo[] all_oper = TypeManager.MemberLookup (TypeManager.decimal_type,
1396                                         TypeManager.decimal_type, TypeManager.decimal_type, MemberTypes.Method,
1397                                         BindingFlags.Static | BindingFlags.Public, "op_Explicit", null);
1398
1399                                 operators = new System.Collections.Specialized.HybridDictionary ();
1400                                 foreach (MethodInfo oper in all_oper) {
1401                                         ParameterData pd = TypeManager.GetParameterData (oper);
1402                                         if (pd.ParameterType (0) == TypeManager.decimal_type)
1403                                                 operators.Add (oper.ReturnType, oper);
1404                                 }
1405                         }
1406
1407                         return operators.Contains (type) ? this : null;
1408                 }
1409
1410                 public override void Emit (EmitContext ec)
1411                 {
1412                         ILGenerator ig = ec.ig;
1413                         child.Emit (ec);
1414
1415                         ig.Emit (OpCodes.Call, (MethodInfo)operators [type]);
1416                 }
1417         }
1418
1419         
1420         //
1421         // Constant specialization of EmptyCast.
1422         // We need to special case this since an empty cast of
1423         // a constant is still a constant. 
1424         //
1425         public class EmptyConstantCast : Constant
1426         {
1427                 public readonly Constant child;
1428
1429                 public EmptyConstantCast(Constant child, Type type)
1430                         : base (child.Location)
1431                 {
1432                         eclass = child.eclass;
1433                         this.child = child;
1434                         this.type = type;
1435                 }
1436
1437                 public override string AsString ()
1438                 {
1439                         return child.AsString ();
1440                 }
1441
1442                 public override object GetValue ()
1443                 {
1444                         return child.GetValue ();
1445                 }
1446
1447                 public override Constant ConvertExplicitly (bool inCheckedContext, Type target_type)
1448                 {
1449                         // FIXME: check that 'type' can be converted to 'target_type' first
1450                         return child.ConvertExplicitly (inCheckedContext, target_type);
1451                 }
1452
1453                 public override Constant Increment ()
1454                 {
1455                         return child.Increment ();
1456                 }
1457
1458                 public override bool IsDefaultValue {
1459                         get { return child.IsDefaultValue; }
1460                 }
1461
1462                 public override bool IsNegative {
1463                         get { return child.IsNegative; }
1464                 }
1465
1466                 public override void Emit (EmitContext ec)
1467                 {
1468                         child.Emit (ec);
1469                 }
1470
1471                 public override Constant ConvertImplicitly (Type target_type)
1472                 {
1473                         // FIXME: Do we need to check user conversions?
1474                         if (!Convert.ImplicitStandardConversionExists (this, target_type))
1475                                 return null;
1476                         return child.ConvertImplicitly (target_type);
1477                 }
1478         }
1479
1480
1481         /// <summary>
1482         ///  This class is used to wrap literals which belong inside Enums
1483         /// </summary>
1484         public class EnumConstant : Constant {
1485                 public Constant Child;
1486
1487                 public EnumConstant (Constant child, Type enum_type):
1488                         base (child.Location)
1489                 {
1490                         eclass = child.eclass;
1491                         this.Child = child;
1492                         type = enum_type;
1493                 }
1494                 
1495                 public override Expression DoResolve (EmitContext ec)
1496                 {
1497                         // This should never be invoked, we are born in fully
1498                         // initialized state.
1499
1500                         return this;
1501                 }
1502
1503                 public override void Emit (EmitContext ec)
1504                 {
1505                         Child.Emit (ec);
1506                 }
1507
1508                 public override bool GetAttributableValue (Type valueType, out object value)
1509                 {
1510                         value = GetTypedValue ();
1511                         return true;
1512                 }
1513
1514                 public override string GetSignatureForError()
1515                 {
1516                         return TypeManager.CSharpName (Type);
1517                 }
1518
1519                 public override object GetValue ()
1520                 {
1521                         return Child.GetValue ();
1522                 }
1523
1524                 public override object GetTypedValue ()
1525                 {
1526                         // FIXME: runtime is not ready to work with just emited enums
1527                         if (!RootContext.StdLib) {
1528                                 return Child.GetValue ();
1529                         }
1530
1531                         return System.Enum.ToObject (type, Child.GetValue ());
1532                 }
1533                 
1534                 public override string AsString ()
1535                 {
1536                         return TypeManager.CSharpEnumValue (type, Child.GetValue ());
1537                 }
1538
1539                 public override Constant Increment()
1540                 {
1541                         return new EnumConstant (Child.Increment (), type);
1542                 }
1543
1544                 public override bool IsDefaultValue {
1545                         get {
1546                                 return Child.IsDefaultValue;
1547                         }
1548                 }
1549
1550                 public override bool IsZeroInteger {
1551                         get { return Child.IsZeroInteger; }
1552                 }
1553
1554                 public override bool IsNegative {
1555                         get {
1556                                 return Child.IsNegative;
1557                         }
1558                 }
1559
1560                 public override Constant ConvertExplicitly(bool inCheckedContext, Type target_type)
1561                 {
1562                         if (Child.Type == target_type)
1563                                 return Child;
1564
1565                         return Child.ConvertExplicitly (inCheckedContext, target_type);
1566                 }
1567
1568                 public override Constant ConvertImplicitly (Type type)
1569                 {
1570                         if (Type == type) {
1571                                 // This is workaround of mono bug. It can be removed when the latest corlib spreads enough
1572                                 if (TypeManager.IsEnumType (type.UnderlyingSystemType))
1573                                         return this;
1574
1575                                 if (type.UnderlyingSystemType != Child.Type)
1576                                         Child = Child.ConvertImplicitly (type.UnderlyingSystemType);
1577                                 return this;
1578                         }
1579
1580                         if (!Convert.ImplicitStandardConversionExists (this, type)){
1581                                 return null;
1582                         }
1583
1584                         return Child.ConvertImplicitly(type);
1585                 }
1586
1587         }
1588
1589         /// <summary>
1590         ///   This kind of cast is used to encapsulate Value Types in objects.
1591         ///
1592         ///   The effect of it is to box the value type emitted by the previous
1593         ///   operation.
1594         /// </summary>
1595         public class BoxedCast : EmptyCast {
1596
1597                 public BoxedCast (Expression expr, Type target_type)
1598                         : base (expr, target_type)
1599                 {
1600                         eclass = ExprClass.Value;
1601                 }
1602                 
1603                 public override Expression DoResolve (EmitContext ec)
1604                 {
1605                         // This should never be invoked, we are born in fully
1606                         // initialized state.
1607
1608                         return this;
1609                 }
1610
1611                 public override void Emit (EmitContext ec)
1612                 {
1613                         base.Emit (ec);
1614                         
1615                         ec.ig.Emit (OpCodes.Box, child.Type);
1616                 }
1617         }
1618
1619         public class UnboxCast : EmptyCast {
1620                 public UnboxCast (Expression expr, Type return_type)
1621                         : base (expr, return_type)
1622                 {
1623                 }
1624
1625                 public override Expression DoResolve (EmitContext ec)
1626                 {
1627                         // This should never be invoked, we are born in fully
1628                         // initialized state.
1629
1630                         return this;
1631                 }
1632
1633                 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
1634                 {
1635                         if (right_side == EmptyExpression.LValueMemberAccess || right_side == EmptyExpression.LValueMemberOutAccess)
1636                                 Report.Error (445, loc, "Cannot modify the result of an unboxing conversion");
1637                         return base.DoResolveLValue (ec, right_side);
1638                 }
1639
1640                 public override void Emit (EmitContext ec)
1641                 {
1642                         Type t = type;
1643                         ILGenerator ig = ec.ig;
1644                         
1645                         base.Emit (ec);
1646 #if GMCS_SOURCE
1647                         if (t.IsGenericParameter || t.IsGenericType && t.IsValueType)
1648                                 ig.Emit (OpCodes.Unbox_Any, t);
1649                         else
1650 #endif
1651                         {
1652                                 ig.Emit (OpCodes.Unbox, t);
1653
1654                                 LoadFromPtr (ig, t);
1655                         }
1656                 }
1657         }
1658         
1659         /// <summary>
1660         ///   This is used to perform explicit numeric conversions.
1661         ///
1662         ///   Explicit numeric conversions might trigger exceptions in a checked
1663         ///   context, so they should generate the conv.ovf opcodes instead of
1664         ///   conv opcodes.
1665         /// </summary>
1666         public class ConvCast : EmptyCast {
1667                 public enum Mode : byte {
1668                         I1_U1, I1_U2, I1_U4, I1_U8, I1_CH,
1669                         U1_I1, U1_CH,
1670                         I2_I1, I2_U1, I2_U2, I2_U4, I2_U8, I2_CH,
1671                         U2_I1, U2_U1, U2_I2, U2_CH,
1672                         I4_I1, I4_U1, I4_I2, I4_U2, I4_U4, I4_U8, I4_CH,
1673                         U4_I1, U4_U1, U4_I2, U4_U2, U4_I4, U4_CH,
1674                         I8_I1, I8_U1, I8_I2, I8_U2, I8_I4, I8_U4, I8_U8, I8_CH,
1675                         U8_I1, U8_U1, U8_I2, U8_U2, U8_I4, U8_U4, U8_I8, U8_CH,
1676                         CH_I1, CH_U1, CH_I2,
1677                         R4_I1, R4_U1, R4_I2, R4_U2, R4_I4, R4_U4, R4_I8, R4_U8, R4_CH,
1678                         R8_I1, R8_U1, R8_I2, R8_U2, R8_I4, R8_U4, R8_I8, R8_U8, R8_CH, R8_R4
1679                 }
1680
1681                 Mode mode;
1682                 
1683                 public ConvCast (Expression child, Type return_type, Mode m)
1684                         : base (child, return_type)
1685                 {
1686                         mode = m;
1687                 }
1688
1689                 public override Expression DoResolve (EmitContext ec)
1690                 {
1691                         // This should never be invoked, we are born in fully
1692                         // initialized state.
1693
1694                         return this;
1695                 }
1696
1697                 public override string ToString ()
1698                 {
1699                         return String.Format ("ConvCast ({0}, {1})", mode, child);
1700                 }
1701                 
1702                 public override void Emit (EmitContext ec)
1703                 {
1704                         ILGenerator ig = ec.ig;
1705                         
1706                         base.Emit (ec);
1707
1708                         if (ec.CheckState){
1709                                 switch (mode){
1710                                 case Mode.I1_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1711                                 case Mode.I1_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1712                                 case Mode.I1_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1713                                 case Mode.I1_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1714                                 case Mode.I1_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1715
1716                                 case Mode.U1_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1717                                 case Mode.U1_CH: /* nothing */ break;
1718
1719                                 case Mode.I2_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1720                                 case Mode.I2_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1721                                 case Mode.I2_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1722                                 case Mode.I2_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1723                                 case Mode.I2_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1724                                 case Mode.I2_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1725
1726                                 case Mode.U2_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1727                                 case Mode.U2_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1728                                 case Mode.U2_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1729                                 case Mode.U2_CH: /* nothing */ break;
1730
1731                                 case Mode.I4_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1732                                 case Mode.I4_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1733                                 case Mode.I4_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1734                                 case Mode.I4_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1735                                 case Mode.I4_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1736                                 case Mode.I4_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1737                                 case Mode.I4_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1738
1739                                 case Mode.U4_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1740                                 case Mode.U4_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1741                                 case Mode.U4_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1742                                 case Mode.U4_U2: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1743                                 case Mode.U4_I4: ig.Emit (OpCodes.Conv_Ovf_I4_Un); break;
1744                                 case Mode.U4_CH: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1745
1746                                 case Mode.I8_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1747                                 case Mode.I8_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1748                                 case Mode.I8_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1749                                 case Mode.I8_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1750                                 case Mode.I8_I4: ig.Emit (OpCodes.Conv_Ovf_I4); break;
1751                                 case Mode.I8_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1752                                 case Mode.I8_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1753                                 case Mode.I8_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1754
1755                                 case Mode.U8_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1756                                 case Mode.U8_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1757                                 case Mode.U8_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1758                                 case Mode.U8_U2: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1759                                 case Mode.U8_I4: ig.Emit (OpCodes.Conv_Ovf_I4_Un); break;
1760                                 case Mode.U8_U4: ig.Emit (OpCodes.Conv_Ovf_U4_Un); break;
1761                                 case Mode.U8_I8: ig.Emit (OpCodes.Conv_Ovf_I8_Un); break;
1762                                 case Mode.U8_CH: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1763
1764                                 case Mode.CH_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1765                                 case Mode.CH_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1766                                 case Mode.CH_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1767
1768                                 case Mode.R4_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1769                                 case Mode.R4_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1770                                 case Mode.R4_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1771                                 case Mode.R4_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1772                                 case Mode.R4_I4: ig.Emit (OpCodes.Conv_Ovf_I4); break;
1773                                 case Mode.R4_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1774                                 case Mode.R4_I8: ig.Emit (OpCodes.Conv_Ovf_I8); break;
1775                                 case Mode.R4_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1776                                 case Mode.R4_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1777
1778                                 case Mode.R8_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1779                                 case Mode.R8_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1780                                 case Mode.R8_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1781                                 case Mode.R8_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1782                                 case Mode.R8_I4: ig.Emit (OpCodes.Conv_Ovf_I4); break;
1783                                 case Mode.R8_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1784                                 case Mode.R8_I8: ig.Emit (OpCodes.Conv_Ovf_I8); break;
1785                                 case Mode.R8_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1786                                 case Mode.R8_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1787                                 case Mode.R8_R4: ig.Emit (OpCodes.Conv_R4); break;
1788                                 }
1789                         } else {
1790                                 switch (mode){
1791                                 case Mode.I1_U1: ig.Emit (OpCodes.Conv_U1); break;
1792                                 case Mode.I1_U2: ig.Emit (OpCodes.Conv_U2); break;
1793                                 case Mode.I1_U4: ig.Emit (OpCodes.Conv_U4); break;
1794                                 case Mode.I1_U8: ig.Emit (OpCodes.Conv_I8); break;
1795                                 case Mode.I1_CH: ig.Emit (OpCodes.Conv_U2); break;
1796
1797                                 case Mode.U1_I1: ig.Emit (OpCodes.Conv_I1); break;
1798                                 case Mode.U1_CH: ig.Emit (OpCodes.Conv_U2); break;
1799
1800                                 case Mode.I2_I1: ig.Emit (OpCodes.Conv_I1); break;
1801                                 case Mode.I2_U1: ig.Emit (OpCodes.Conv_U1); break;
1802                                 case Mode.I2_U2: ig.Emit (OpCodes.Conv_U2); break;
1803                                 case Mode.I2_U4: ig.Emit (OpCodes.Conv_U4); break;
1804                                 case Mode.I2_U8: ig.Emit (OpCodes.Conv_I8); break;
1805                                 case Mode.I2_CH: ig.Emit (OpCodes.Conv_U2); break;
1806
1807                                 case Mode.U2_I1: ig.Emit (OpCodes.Conv_I1); break;
1808                                 case Mode.U2_U1: ig.Emit (OpCodes.Conv_U1); break;
1809                                 case Mode.U2_I2: ig.Emit (OpCodes.Conv_I2); break;
1810                                 case Mode.U2_CH: /* nothing */ break;
1811
1812                                 case Mode.I4_I1: ig.Emit (OpCodes.Conv_I1); break;
1813                                 case Mode.I4_U1: ig.Emit (OpCodes.Conv_U1); break;
1814                                 case Mode.I4_I2: ig.Emit (OpCodes.Conv_I2); break;
1815                                 case Mode.I4_U4: /* nothing */ break;
1816                                 case Mode.I4_U2: ig.Emit (OpCodes.Conv_U2); break;
1817                                 case Mode.I4_U8: ig.Emit (OpCodes.Conv_I8); break;
1818                                 case Mode.I4_CH: ig.Emit (OpCodes.Conv_U2); break;
1819
1820                                 case Mode.U4_I1: ig.Emit (OpCodes.Conv_I1); break;
1821                                 case Mode.U4_U1: ig.Emit (OpCodes.Conv_U1); break;
1822                                 case Mode.U4_I2: ig.Emit (OpCodes.Conv_I2); break;
1823                                 case Mode.U4_U2: ig.Emit (OpCodes.Conv_U2); break;
1824                                 case Mode.U4_I4: /* nothing */ break;
1825                                 case Mode.U4_CH: ig.Emit (OpCodes.Conv_U2); break;
1826
1827                                 case Mode.I8_I1: ig.Emit (OpCodes.Conv_I1); break;
1828                                 case Mode.I8_U1: ig.Emit (OpCodes.Conv_U1); break;
1829                                 case Mode.I8_I2: ig.Emit (OpCodes.Conv_I2); break;
1830                                 case Mode.I8_U2: ig.Emit (OpCodes.Conv_U2); break;
1831                                 case Mode.I8_I4: ig.Emit (OpCodes.Conv_I4); break;
1832                                 case Mode.I8_U4: ig.Emit (OpCodes.Conv_U4); break;
1833                                 case Mode.I8_U8: /* nothing */ break;
1834                                 case Mode.I8_CH: ig.Emit (OpCodes.Conv_U2); break;
1835
1836                                 case Mode.U8_I1: ig.Emit (OpCodes.Conv_I1); break;
1837                                 case Mode.U8_U1: ig.Emit (OpCodes.Conv_U1); break;
1838                                 case Mode.U8_I2: ig.Emit (OpCodes.Conv_I2); break;
1839                                 case Mode.U8_U2: ig.Emit (OpCodes.Conv_U2); break;
1840                                 case Mode.U8_I4: ig.Emit (OpCodes.Conv_I4); break;
1841                                 case Mode.U8_U4: ig.Emit (OpCodes.Conv_U4); break;
1842                                 case Mode.U8_I8: /* nothing */ break;
1843                                 case Mode.U8_CH: ig.Emit (OpCodes.Conv_U2); break;
1844
1845                                 case Mode.CH_I1: ig.Emit (OpCodes.Conv_I1); break;
1846                                 case Mode.CH_U1: ig.Emit (OpCodes.Conv_U1); break;
1847                                 case Mode.CH_I2: ig.Emit (OpCodes.Conv_I2); break;
1848
1849                                 case Mode.R4_I1: ig.Emit (OpCodes.Conv_I1); break;
1850                                 case Mode.R4_U1: ig.Emit (OpCodes.Conv_U1); break;
1851                                 case Mode.R4_I2: ig.Emit (OpCodes.Conv_I2); break;
1852                                 case Mode.R4_U2: ig.Emit (OpCodes.Conv_U2); break;
1853                                 case Mode.R4_I4: ig.Emit (OpCodes.Conv_I4); break;
1854                                 case Mode.R4_U4: ig.Emit (OpCodes.Conv_U4); break;
1855                                 case Mode.R4_I8: ig.Emit (OpCodes.Conv_I8); break;
1856                                 case Mode.R4_U8: ig.Emit (OpCodes.Conv_U8); break;
1857                                 case Mode.R4_CH: ig.Emit (OpCodes.Conv_U2); break;
1858
1859                                 case Mode.R8_I1: ig.Emit (OpCodes.Conv_I1); break;
1860                                 case Mode.R8_U1: ig.Emit (OpCodes.Conv_U1); break;
1861                                 case Mode.R8_I2: ig.Emit (OpCodes.Conv_I2); break;
1862                                 case Mode.R8_U2: ig.Emit (OpCodes.Conv_U2); break;
1863                                 case Mode.R8_I4: ig.Emit (OpCodes.Conv_I4); break;
1864                                 case Mode.R8_U4: ig.Emit (OpCodes.Conv_U4); break;
1865                                 case Mode.R8_I8: ig.Emit (OpCodes.Conv_I8); break;
1866                                 case Mode.R8_U8: ig.Emit (OpCodes.Conv_U8); break;
1867                                 case Mode.R8_CH: ig.Emit (OpCodes.Conv_U2); break;
1868                                 case Mode.R8_R4: ig.Emit (OpCodes.Conv_R4); break;
1869                                 }
1870                         }
1871                 }
1872         }
1873         
1874         public class OpcodeCast : EmptyCast {
1875                 OpCode op, op2;
1876                 bool second_valid;
1877                 
1878                 public OpcodeCast (Expression child, Type return_type, OpCode op)
1879                         : base (child, return_type)
1880                         
1881                 {
1882                         this.op = op;
1883                         second_valid = false;
1884                 }
1885
1886                 public OpcodeCast (Expression child, Type return_type, OpCode op, OpCode op2)
1887                         : base (child, return_type)
1888                         
1889                 {
1890                         this.op = op;
1891                         this.op2 = op2;
1892                         second_valid = true;
1893                 }
1894
1895                 public override Expression DoResolve (EmitContext ec)
1896                 {
1897                         // This should never be invoked, we are born in fully
1898                         // initialized state.
1899
1900                         return this;
1901                 }
1902
1903                 public override void Emit (EmitContext ec)
1904                 {
1905                         base.Emit (ec);
1906                         ec.ig.Emit (op);
1907
1908                         if (second_valid)
1909                                 ec.ig.Emit (op2);
1910                 }                       
1911         }
1912
1913         /// <summary>
1914         ///   This kind of cast is used to encapsulate a child and cast it
1915         ///   to the class requested
1916         /// </summary>
1917         public class ClassCast : EmptyCast {
1918                 public ClassCast (Expression child, Type return_type)
1919                         : base (child, return_type)
1920                         
1921                 {
1922                 }
1923
1924                 public override Expression DoResolve (EmitContext ec)
1925                 {
1926                         // This should never be invoked, we are born in fully
1927                         // initialized state.
1928
1929                         return this;
1930                 }
1931
1932                 public override void Emit (EmitContext ec)
1933                 {
1934                         base.Emit (ec);
1935
1936                         if (TypeManager.IsGenericParameter (child.Type))
1937                                 ec.ig.Emit (OpCodes.Box, child.Type);
1938
1939 #if GMCS_SOURCE
1940                         if (type.IsGenericParameter)
1941                                 ec.ig.Emit (OpCodes.Unbox_Any, type);
1942                         else
1943 #endif
1944                                 ec.ig.Emit (OpCodes.Castclass, type);
1945                 }
1946         }
1947         
1948         /// <summary>
1949         ///   SimpleName expressions are formed of a single word and only happen at the beginning 
1950         ///   of a dotted-name.
1951         /// </summary>
1952         public class SimpleName : Expression {
1953                 public string Name;
1954                 public readonly TypeArguments Arguments;
1955                 bool in_transit;
1956
1957                 public SimpleName (string name, Location l)
1958                 {
1959                         Name = name;
1960                         loc = l;
1961                 }
1962
1963                 public SimpleName (string name, TypeArguments args, Location l)
1964                 {
1965                         Name = name;
1966                         Arguments = args;
1967                         loc = l;
1968                 }
1969
1970                 public SimpleName (string name, TypeParameter[] type_params, Location l)
1971                 {
1972                         Name = name;
1973                         loc = l;
1974
1975                         Arguments = new TypeArguments (l);
1976                         foreach (TypeParameter type_param in type_params)
1977                                 Arguments.Add (new TypeParameterExpr (type_param, l));
1978                 }
1979
1980                 public static string RemoveGenericArity (string name)
1981                 {
1982                         int start = 0;
1983                         StringBuilder sb = null;
1984                         do {
1985                                 int pos = name.IndexOf ('`', start);
1986                                 if (pos < 0) {
1987                                         if (start == 0)
1988                                                 return name;
1989
1990                                         sb.Append (name.Substring (start));
1991                                         break;
1992                                 }
1993
1994                                 if (sb == null)
1995                                         sb = new StringBuilder ();
1996                                 sb.Append (name.Substring (start, pos-start));
1997
1998                                 pos++;
1999                                 while ((pos < name.Length) && Char.IsNumber (name [pos]))
2000                                         pos++;
2001
2002                                 start = pos;
2003                         } while (start < name.Length);
2004
2005                         return sb.ToString ();
2006                 }
2007
2008                 public SimpleName GetMethodGroup ()
2009                 {
2010                         return new SimpleName (RemoveGenericArity (Name), Arguments, loc);
2011                 }
2012
2013                 public static void Error_ObjectRefRequired (EmitContext ec, Location l, string name)
2014                 {
2015                         if (ec.IsFieldInitializer)
2016                                 Report.Error (236, l,
2017                                         "A field initializer cannot reference the nonstatic field, method, or property `{0}'",
2018                                         name);
2019                         else
2020                                 Report.Error (
2021                                         120, l, "`{0}': An object reference is required for the nonstatic field, method or property",
2022                                         name);
2023                 }
2024
2025                 public bool IdenticalNameAndTypeName (EmitContext ec, Expression resolved_to, Location loc)
2026                 {
2027                         return resolved_to != null && resolved_to.Type != null && 
2028                                 resolved_to.Type.Name == Name &&
2029                                 (ec.DeclContainer.LookupNamespaceOrType (Name, loc, /* ignore_cs0104 = */ true) != null);
2030                 }
2031
2032                 public override Expression DoResolve (EmitContext ec)
2033                 {
2034                         return SimpleNameResolve (ec, null, false);
2035                 }
2036
2037                 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
2038                 {
2039                         return SimpleNameResolve (ec, right_side, false);
2040                 }
2041                 
2042
2043                 public Expression DoResolve (EmitContext ec, bool intermediate)
2044                 {
2045                         return SimpleNameResolve (ec, null, intermediate);
2046                 }
2047
2048                 private bool IsNestedChild (Type t, Type parent)
2049                 {
2050                         if (parent == null)
2051                                 return false;
2052
2053                         while (parent != null) {
2054                                 parent = TypeManager.DropGenericTypeArguments (parent);
2055                                 if (TypeManager.IsNestedChildOf (t, parent))
2056                                         return true;
2057
2058                                 parent = parent.BaseType;
2059                         }
2060
2061                         return false;
2062                 }
2063
2064                 FullNamedExpression ResolveNested (IResolveContext ec, Type t)
2065                 {
2066                         if (!TypeManager.IsGenericTypeDefinition (t))
2067                                 return null;
2068
2069                         DeclSpace ds = ec.DeclContainer;
2070                         while (ds != null) {
2071                                 if (IsNestedChild (t, ds.TypeBuilder))
2072                                         break;
2073
2074                                 ds = ds.Parent;
2075                         }
2076
2077                         if (ds == null)
2078                                 return null;
2079
2080                         Type[] gen_params = TypeManager.GetTypeArguments (t);
2081
2082                         int arg_count = Arguments != null ? Arguments.Count : 0;
2083
2084                         for (; (ds != null) && ds.IsGeneric; ds = ds.Parent) {
2085                                 if (arg_count + ds.CountTypeParameters == gen_params.Length) {
2086                                         TypeArguments new_args = new TypeArguments (loc);
2087                                         foreach (TypeParameter param in ds.TypeParameters)
2088                                                 new_args.Add (new TypeParameterExpr (param, loc));
2089
2090                                         if (Arguments != null)
2091                                                 new_args.Add (Arguments);
2092
2093                                         return new ConstructedType (t, new_args, loc);
2094                                 }
2095                         }
2096
2097                         return null;
2098                 }
2099
2100                 public override FullNamedExpression ResolveAsTypeStep (IResolveContext ec, bool silent)
2101                 {
2102                         FullNamedExpression fne = ec.GenericDeclContainer.LookupGeneric (Name, loc);
2103                         if (fne != null)
2104                                 return fne.ResolveAsTypeStep (ec, silent);
2105
2106                         int errors = Report.Errors;
2107                         fne = ec.DeclContainer.LookupNamespaceOrType (Name, loc, /*ignore_cs0104=*/ false);
2108
2109                         if (fne != null) {
2110                                 if (fne.Type == null)
2111                                         return fne;
2112
2113                                 FullNamedExpression nested = ResolveNested (ec, fne.Type);
2114                                 if (nested != null)
2115                                         return nested.ResolveAsTypeStep (ec, false);
2116
2117                                 if (Arguments != null) {
2118                                         ConstructedType ct = new ConstructedType (fne, Arguments, loc);
2119                                         return ct.ResolveAsTypeStep (ec, false);
2120                                 }
2121
2122                                 return fne;
2123                         }
2124
2125                         if (silent || errors != Report.Errors)
2126                                 return null;
2127
2128                         MemberCore mc = ec.DeclContainer.GetDefinition (Name);
2129                         if (mc != null) {
2130                                 Error_UnexpectedKind (ec.DeclContainer, "type", GetMemberType (mc), loc);
2131                                 return null;
2132                         }
2133
2134                         string ns = ec.DeclContainer.NamespaceEntry.NS.Name;
2135                         string fullname = (ns.Length > 0) ? ns + "." + Name : Name;
2136                         foreach (Assembly a in RootNamespace.Global.Assemblies) {
2137                                 Type type = a.GetType (fullname);
2138                                 if (type != null) {
2139                                         Report.SymbolRelatedToPreviousError (type);
2140                                         Expression.ErrorIsInaccesible (loc, fullname);
2141                                         return null;
2142                                 }
2143                         }
2144
2145                         Type t = ec.DeclContainer.LookupAnyGeneric (Name);
2146                         if (t != null) {
2147                                 Namespace.Error_InvalidNumberOfTypeArguments (t, loc);
2148                                 return null;
2149                         }
2150
2151                         NamespaceEntry.Error_NamespaceNotFound (loc, Name);
2152                         return null;
2153                 }
2154
2155                 // TODO: I am still not convinced about this. If someone else will need it
2156                 // implement this as virtual property in MemberCore hierarchy
2157                 public static string GetMemberType (MemberCore mc)
2158                 {
2159                         if (mc is Property)
2160                                 return "property";
2161                         if (mc is Indexer)
2162                                 return "indexer";
2163                         if (mc is FieldBase)
2164                                 return "field";
2165                         if (mc is MethodCore)
2166                                 return "method";
2167                         if (mc is EnumMember)
2168                                 return "enum";
2169                         if (mc is Event)
2170                                 return "event";
2171
2172                         return "type";
2173                 }
2174
2175                 Expression SimpleNameResolve (EmitContext ec, Expression right_side, bool intermediate)
2176                 {
2177                         if (in_transit)
2178                                 return null;
2179                         in_transit = true;
2180
2181                         Expression e = DoSimpleNameResolve (ec, right_side, intermediate);
2182                         if (e == null)
2183                                 return null;
2184
2185                         if (ec.CurrentBlock == null || ec.CurrentBlock.CheckInvariantMeaningInBlock (Name, e, Location))
2186                                 return e;
2187
2188                         return null;
2189                 }
2190
2191                 /// <remarks>
2192                 ///   7.5.2: Simple Names. 
2193                 ///
2194                 ///   Local Variables and Parameters are handled at
2195                 ///   parse time, so they never occur as SimpleNames.
2196                 ///
2197                 ///   The `intermediate' flag is used by MemberAccess only
2198                 ///   and it is used to inform us that it is ok for us to 
2199                 ///   avoid the static check, because MemberAccess might end
2200                 ///   up resolving the Name as a Type name and the access as
2201                 ///   a static type access.
2202                 ///
2203                 ///   ie: Type Type; .... { Type.GetType (""); }
2204                 ///
2205                 ///   Type is both an instance variable and a Type;  Type.GetType
2206                 ///   is the static method not an instance method of type.
2207                 /// </remarks>
2208                 Expression DoSimpleNameResolve (EmitContext ec, Expression right_side, bool intermediate)
2209                 {
2210                         Expression e = null;
2211
2212                         //
2213                         // Stage 1: Performed by the parser (binding to locals or parameters).
2214                         //
2215                         Block current_block = ec.CurrentBlock;
2216                         if (current_block != null){
2217                                 LocalInfo vi = current_block.GetLocalInfo (Name);
2218                                 if (vi != null){
2219                                         if (Arguments != null) {
2220                                                 Report.Error (307, loc,
2221                                                               "The variable `{0}' cannot be used with type arguments",
2222                                                               Name);
2223                                                 return null;
2224                                         }
2225
2226                                         LocalVariableReference var = new LocalVariableReference (ec.CurrentBlock, Name, loc);
2227                                         if (right_side != null) {
2228                                                 return var.ResolveLValue (ec, right_side, loc);
2229                                         } else {
2230                                                 ResolveFlags rf = ResolveFlags.VariableOrValue;
2231                                                 if (intermediate)
2232                                                         rf |= ResolveFlags.DisableFlowAnalysis;
2233                                                 return var.Resolve (ec, rf);
2234                                         }
2235                                 }
2236
2237                                 ParameterReference pref = current_block.Toplevel.GetParameterReference (Name, loc);
2238                                 if (pref != null) {
2239                                         if (Arguments != null) {
2240                                                 Report.Error (307, loc,
2241                                                               "The variable `{0}' cannot be used with type arguments",
2242                                                               Name);
2243                                                 return null;
2244                                         }
2245
2246                                         if (right_side != null)
2247                                                 return pref.ResolveLValue (ec, right_side, loc);
2248                                         else
2249                                                 return pref.Resolve (ec);
2250                                 }
2251                         }
2252                         
2253                         //
2254                         // Stage 2: Lookup members 
2255                         //
2256
2257                         DeclSpace lookup_ds = ec.DeclContainer;
2258                         Type almost_matched_type = null;
2259                         ArrayList almost_matched = null;
2260                         do {
2261                                 if (lookup_ds.TypeBuilder == null)
2262                                         break;
2263
2264                                 e = MemberLookup (ec.ContainerType, lookup_ds.TypeBuilder, Name, loc);
2265                                 if (e != null)
2266                                         break;
2267
2268                                 if (almost_matched == null && almostMatchedMembers.Count > 0) {
2269                                         almost_matched_type = lookup_ds.TypeBuilder;
2270                                         almost_matched = (ArrayList) almostMatchedMembers.Clone ();
2271                                 }
2272
2273                                 lookup_ds =lookup_ds.Parent;
2274                         } while (lookup_ds != null);
2275
2276                         if (e == null && ec.ContainerType != null)
2277                                 e = MemberLookup (ec.ContainerType, ec.ContainerType, Name, loc);
2278
2279                         if (e == null) {
2280                                 if (almost_matched == null && almostMatchedMembers.Count > 0) {
2281                                         almost_matched_type = ec.ContainerType;
2282                                         almost_matched = (ArrayList) almostMatchedMembers.Clone ();
2283                                 }
2284                                 e = ResolveAsTypeStep (ec, true);
2285                         }
2286
2287                         if (e == null) {
2288                                 if (almost_matched != null)
2289                                         almostMatchedMembers = almost_matched;
2290                                 if (almost_matched_type == null)
2291                                         almost_matched_type = ec.ContainerType;
2292                                 MemberLookupFailed (ec.ContainerType, null, almost_matched_type, ((SimpleName) this).Name, ec.DeclContainer.Name, true, loc);
2293                                 return null;
2294                         }
2295
2296                         if (e is TypeExpr) {
2297                                 if (Arguments == null)
2298                                         return e;
2299
2300                                 ConstructedType ct = new ConstructedType (
2301                                         (FullNamedExpression) e, Arguments, loc);
2302                                 return ct.ResolveAsTypeStep (ec, false);
2303                         }
2304
2305                         if (e is MemberExpr) {
2306                                 MemberExpr me = (MemberExpr) e;
2307
2308                                 Expression left;
2309                                 if (me.IsInstance) {
2310                                         if (ec.IsStatic || ec.IsFieldInitializer) {
2311                                                 //
2312                                                 // Note that an MemberExpr can be both IsInstance and IsStatic.
2313                                                 // An unresolved MethodGroupExpr can contain both kinds of methods
2314                                                 // and each predicate is true if the MethodGroupExpr contains
2315                                                 // at least one of that kind of method.
2316                                                 //
2317
2318                                                 if (!me.IsStatic &&
2319                                                     (!intermediate || !IdenticalNameAndTypeName (ec, me, loc))) {
2320                                                         Error_ObjectRefRequired (ec, loc, me.GetSignatureForError ());
2321                                                         return EmptyExpression.Null;
2322                                                 }
2323
2324                                                 //
2325                                                 // Pass the buck to MemberAccess and Invocation.
2326                                                 //
2327                                                 left = EmptyExpression.Null;
2328                                         } else {
2329                                                 left = ec.GetThis (loc);
2330                                         }
2331                                 } else {
2332                                         left = new TypeExpression (ec.ContainerType, loc);
2333                                 }
2334
2335                                 e = me.ResolveMemberAccess (ec, left, loc, null);
2336                                 if (e == null)
2337                                         return null;
2338
2339                                 me = e as MemberExpr;
2340                                 if (me == null)
2341                                         return e;
2342
2343                                 if (Arguments != null) {
2344                                         MethodGroupExpr mg = me as MethodGroupExpr;
2345                                         if (mg == null)
2346                                                 return null;
2347
2348                                         return mg.ResolveGeneric (ec, Arguments);
2349                                 }
2350
2351                                 if (!me.IsStatic && (me.InstanceExpression != null) &&
2352                                     TypeManager.IsNestedFamilyAccessible (me.InstanceExpression.Type, me.DeclaringType) &&
2353                                     me.InstanceExpression.Type != me.DeclaringType &&
2354                                     !TypeManager.IsFamilyAccessible (me.InstanceExpression.Type, me.DeclaringType) &&
2355                                     (!intermediate || !IdenticalNameAndTypeName (ec, e, loc))) {
2356                                         Report.Error (38, loc, "Cannot access a nonstatic member of outer type `{0}' via nested type `{1}'",
2357                                                 TypeManager.CSharpName (me.DeclaringType), TypeManager.CSharpName (me.InstanceExpression.Type));
2358                                         return null;
2359                                 }
2360
2361                                 return (right_side != null)
2362                                         ? me.DoResolveLValue (ec, right_side)
2363                                         : me.DoResolve (ec);
2364                         }
2365
2366                         return e;
2367                 }
2368                 
2369                 public override void Emit (EmitContext ec)
2370                 {
2371                         //
2372                         // If this is ever reached, then we failed to
2373                         // find the name as a namespace
2374                         //
2375
2376                         Error (103, "The name `" + Name +
2377                                "' does not exist in the class `" +
2378                                ec.DeclContainer.Name + "'");
2379                 }
2380
2381                 public override string ToString ()
2382                 {
2383                         return Name;
2384                 }
2385
2386                 public override string GetSignatureForError ()
2387                 {
2388                         return Name;
2389                 }
2390
2391                 protected override void CloneTo (CloneContext clonectx, Expression target)
2392                 {
2393                         // CloneTo: Nothing, we do not keep any state on this expression
2394                 }
2395         }
2396
2397         /// <summary>
2398         ///   Represents a namespace or a type.  The name of the class was inspired by
2399         ///   section 10.8.1 (Fully Qualified Names).
2400         /// </summary>
2401         public abstract class FullNamedExpression : Expression {
2402                 public override FullNamedExpression ResolveAsTypeStep (IResolveContext ec, bool silent)
2403                 {
2404                         return this;
2405                 }
2406
2407                 public abstract string FullName {
2408                         get;
2409                 }
2410         }
2411         
2412         /// <summary>
2413         ///   Expression that evaluates to a type
2414         /// </summary>
2415         public abstract class TypeExpr : FullNamedExpression {
2416                 override public FullNamedExpression ResolveAsTypeStep (IResolveContext ec, bool silent)
2417                 {
2418                         TypeExpr t = DoResolveAsTypeStep (ec);
2419                         if (t == null)
2420                                 return null;
2421
2422                         eclass = ExprClass.Type;
2423                         return t;
2424                 }
2425
2426                 override public Expression DoResolve (EmitContext ec)
2427                 {
2428                         return ResolveAsTypeTerminal (ec, false);
2429                 }
2430
2431                 override public void Emit (EmitContext ec)
2432                 {
2433                         throw new Exception ("Should never be called");
2434                 }
2435
2436                 public virtual bool CheckAccessLevel (DeclSpace ds)
2437                 {
2438                         return ds.CheckAccessLevel (Type);
2439                 }
2440
2441                 public virtual bool AsAccessible (DeclSpace ds, int flags)
2442                 {
2443                         return ds.AsAccessible (Type, flags);
2444                 }
2445
2446                 public virtual bool IsClass {
2447                         get { return Type.IsClass; }
2448                 }
2449
2450                 public virtual bool IsValueType {
2451                         get { return Type.IsValueType; }
2452                 }
2453
2454                 public virtual bool IsInterface {
2455                         get { return Type.IsInterface; }
2456                 }
2457
2458                 public virtual bool IsSealed {
2459                         get { return Type.IsSealed; }
2460                 }
2461
2462                 public virtual bool CanInheritFrom ()
2463                 {
2464                         if (Type == TypeManager.enum_type ||
2465                             (Type == TypeManager.value_type && RootContext.StdLib) ||
2466                             Type == TypeManager.multicast_delegate_type ||
2467                             Type == TypeManager.delegate_type ||
2468                             Type == TypeManager.array_type)
2469                                 return false;
2470
2471                         return true;
2472                 }
2473
2474                 protected abstract TypeExpr DoResolveAsTypeStep (IResolveContext ec);
2475
2476                 public abstract string Name {
2477                         get;
2478                 }
2479
2480                 public override bool Equals (object obj)
2481                 {
2482                         TypeExpr tobj = obj as TypeExpr;
2483                         if (tobj == null)
2484                                 return false;
2485
2486                         return Type == tobj.Type;
2487                 }
2488
2489                 public override int GetHashCode ()
2490                 {
2491                         return Type.GetHashCode ();
2492                 }
2493                 
2494                 public override string ToString ()
2495                 {
2496                         return Name;
2497                 }
2498         }
2499
2500         /// <summary>
2501         ///   Fully resolved Expression that already evaluated to a type
2502         /// </summary>
2503         public class TypeExpression : TypeExpr {
2504                 public TypeExpression (Type t, Location l)
2505                 {
2506                         Type = t;
2507                         eclass = ExprClass.Type;
2508                         loc = l;
2509                 }
2510
2511                 protected override TypeExpr DoResolveAsTypeStep (IResolveContext ec)
2512                 {
2513                         return this;
2514                 }
2515
2516                 public override TypeExpr ResolveAsTypeTerminal (IResolveContext ec, bool silent)
2517                 {
2518                         return this;
2519                 }
2520
2521                 public override string Name {
2522                         get { return Type.ToString (); }
2523                 }
2524
2525                 public override string FullName {
2526                         get { return Type.FullName; }
2527                 }
2528         }
2529
2530         /// <summary>
2531         ///   Used to create types from a fully qualified name.  These are just used
2532         ///   by the parser to setup the core types.  A TypeLookupExpression is always
2533         ///   classified as a type.
2534         /// </summary>
2535         public sealed class TypeLookupExpression : TypeExpr {
2536                 readonly string name;
2537                 
2538                 public TypeLookupExpression (string name)
2539                 {
2540                         this.name = name;
2541                         eclass = ExprClass.Type;
2542                 }
2543
2544                 public override TypeExpr ResolveAsTypeTerminal (IResolveContext ec, bool silent)
2545                 {
2546                         // It's null for corlib compilation only
2547                         if (type == null)
2548                                 return DoResolveAsTypeStep (ec);
2549
2550                         return this;
2551                 }
2552
2553                 static readonly char [] dot_array = { '.' };
2554                 protected override TypeExpr DoResolveAsTypeStep (IResolveContext ec)
2555                 {
2556                         // If name is of the form `N.I', first lookup `N', then search a member `I' in it.
2557                         string rest = null;
2558                         string lookup_name = name;
2559                         int pos = name.IndexOf ('.');
2560                         if (pos >= 0) {
2561                                 rest = name.Substring (pos + 1);
2562                                 lookup_name = name.Substring (0, pos);
2563                         }
2564
2565                         FullNamedExpression resolved = RootNamespace.Global.Lookup (ec.DeclContainer, lookup_name, Location.Null);
2566
2567                         if (resolved != null && rest != null) {
2568                                 // Now handle the rest of the the name.
2569                                 string [] elements = rest.Split (dot_array);
2570                                 string element;
2571                                 int count = elements.Length;
2572                                 int i = 0;
2573                                 while (i < count && resolved != null && resolved is Namespace) {
2574                                         Namespace ns = resolved as Namespace;
2575                                         element = elements [i++];
2576                                         lookup_name += "." + element;
2577                                         resolved = ns.Lookup (ec.DeclContainer, element, Location.Null);
2578                                 }
2579
2580                                 if (resolved != null && resolved is TypeExpr) {
2581                                         Type t = ((TypeExpr) resolved).Type;
2582                                         while (t != null) {
2583                                                 if (!ec.DeclContainer.CheckAccessLevel (t)) {
2584                                                         resolved = null;
2585                                                         lookup_name = t.FullName;
2586                                                         break;
2587                                                 }
2588                                                 if (i == count) {
2589                                                         type = t;
2590                                                         return this;
2591                                                 }
2592                                                 t = TypeManager.GetNestedType (t, elements [i++]);
2593                                         }
2594                                 }
2595                         }
2596
2597                         if (resolved == null) {
2598                                 NamespaceEntry.Error_NamespaceNotFound (loc, lookup_name);
2599                                 return null;
2600                         }
2601
2602                         if (!(resolved is TypeExpr)) {
2603                                 resolved.Error_UnexpectedKind (ec.DeclContainer, "type", loc);
2604                                 return null;
2605                         }
2606
2607                         type = resolved.Type;
2608                         return this;
2609                 }
2610
2611                 public override string Name {
2612                         get { return name; }
2613                 }
2614
2615                 public override string FullName {
2616                         get { return name; }
2617                 }
2618
2619                 protected override void CloneTo (CloneContext clonectx, Expression target)
2620                 {
2621                         // CloneTo: Nothing, we do not keep any state on this expression
2622                 }
2623         }
2624
2625         /// <summary>
2626         ///   Represents an "unbound generic type", ie. typeof (Foo<>).
2627         ///   See 14.5.11.
2628         /// </summary>
2629         public class UnboundTypeExpression : TypeExpr
2630         {
2631                 MemberName name;
2632
2633                 public UnboundTypeExpression (MemberName name, Location l)
2634                 {
2635                         this.name = name;
2636                         loc = l;
2637                 }
2638
2639                 protected override TypeExpr DoResolveAsTypeStep (IResolveContext ec)
2640                 {
2641                         Expression expr;
2642                         if (name.Left != null) {
2643                                 Expression lexpr = name.Left.GetTypeExpression ();
2644                                 expr = new MemberAccess (lexpr, name.Basename);
2645                         } else {
2646                                 expr = new SimpleName (name.Basename, loc);
2647                         }
2648
2649                         FullNamedExpression fne = expr.ResolveAsTypeStep (ec, false);
2650                         if (fne == null)
2651                                 return null;
2652
2653                         type = fne.Type;
2654                         return new TypeExpression (type, loc);
2655                 }
2656
2657                 public override string Name {
2658                         get { return name.FullName; }
2659                 }
2660
2661                 public override string FullName {
2662                         get { return name.FullName; }
2663                 }
2664         }
2665
2666         public class TypeAliasExpression : TypeExpr {
2667                 FullNamedExpression alias;
2668                 TypeExpr texpr;
2669                 TypeArguments args;
2670                 string name;
2671
2672                 public TypeAliasExpression (FullNamedExpression alias, TypeArguments args, Location l)
2673                 {
2674                         this.alias = alias;
2675                         this.args = args;
2676                         loc = l;
2677
2678                         eclass = ExprClass.Type;
2679                         if (args != null)
2680                                 name = alias.FullName + "<" + args.ToString () + ">";
2681                         else
2682                                 name = alias.FullName;
2683                 }
2684
2685                 public override string Name {
2686                         get { return alias.FullName; }
2687                 }
2688
2689                 public override string FullName {
2690                         get { return name; }
2691                 }
2692
2693                 protected override TypeExpr DoResolveAsTypeStep (IResolveContext ec)
2694                 {
2695                         texpr = alias.ResolveAsTypeTerminal (ec, false);
2696                         if (texpr == null)
2697                                 return null;
2698
2699                         Type type = texpr.Type;
2700                         int num_args = TypeManager.GetNumberOfTypeArguments (type);
2701
2702                         if (args != null) {
2703                                 if (num_args == 0) {
2704                                         Report.Error (308, loc,
2705                                                       "The non-generic type `{0}' cannot " +
2706                                                       "be used with type arguments.",
2707                                                       TypeManager.CSharpName (type));
2708                                         return null;
2709                                 }
2710
2711                                 ConstructedType ctype = new ConstructedType (type, args, loc);
2712                                 return ctype.ResolveAsTypeTerminal (ec, false);
2713                         } else if (num_args > 0) {
2714                                 Report.Error (305, loc,
2715                                               "Using the generic type `{0}' " +
2716                                               "requires {1} type arguments",
2717                                               TypeManager.CSharpName (type), num_args.ToString ());
2718                                 return null;
2719                         }
2720
2721                         return texpr;
2722                 }
2723
2724                 public override bool CheckAccessLevel (DeclSpace ds)
2725                 {
2726                         return texpr.CheckAccessLevel (ds);
2727                 }
2728
2729                 public override bool AsAccessible (DeclSpace ds, int flags)
2730                 {
2731                         return texpr.AsAccessible (ds, flags);
2732                 }
2733
2734                 public override bool IsClass {
2735                         get { return texpr.IsClass; }
2736                 }
2737
2738                 public override bool IsValueType {
2739                         get { return texpr.IsValueType; }
2740                 }
2741
2742                 public override bool IsInterface {
2743                         get { return texpr.IsInterface; }
2744                 }
2745
2746                 public override bool IsSealed {
2747                         get { return texpr.IsSealed; }
2748                 }
2749         }
2750
2751         /// <summary>
2752         ///   This class denotes an expression which evaluates to a member
2753         ///   of a struct or a class.
2754         /// </summary>
2755         public abstract class MemberExpr : Expression
2756         {
2757                 /// <summary>
2758                 ///   The name of this member.
2759                 /// </summary>
2760                 public abstract string Name {
2761                         get;
2762                 }
2763
2764                 /// <summary>
2765                 ///   Whether this is an instance member.
2766                 /// </summary>
2767                 public abstract bool IsInstance {
2768                         get;
2769                 }
2770
2771                 /// <summary>
2772                 ///   Whether this is a static member.
2773                 /// </summary>
2774                 public abstract bool IsStatic {
2775                         get;
2776                 }
2777
2778                 /// <summary>
2779                 ///   The type which declares this member.
2780                 /// </summary>
2781                 public abstract Type DeclaringType {
2782                         get;
2783                 }
2784
2785                 /// <summary>
2786                 ///   The instance expression associated with this member, if it's a
2787                 ///   non-static member.
2788                 /// </summary>
2789                 public Expression InstanceExpression;
2790
2791                 public static void error176 (Location loc, string name)
2792                 {
2793                         Report.Error (176, loc, "Static member `{0}' cannot be accessed " +
2794                                       "with an instance reference, qualify it with a type name instead", name);
2795                 }
2796
2797                 // TODO: possible optimalization
2798                 // Cache resolved constant result in FieldBuilder <-> expression map
2799                 public virtual Expression ResolveMemberAccess (EmitContext ec, Expression left, Location loc,
2800                                                                SimpleName original)
2801                 {
2802                         //
2803                         // Precondition:
2804                         //   original == null || original.Resolve (...) ==> left
2805                         //
2806
2807                         if (left is TypeExpr) {
2808                                 if (!IsStatic) {
2809                                         SimpleName.Error_ObjectRefRequired (ec, loc, GetSignatureForError ());
2810                                         return null;
2811                                 }
2812
2813                                 return this;
2814                         }
2815                                 
2816                         if (!IsInstance) {
2817                                 if (original != null && original.IdenticalNameAndTypeName (ec, left, loc))
2818                                         return this;
2819
2820                                 error176 (loc, GetSignatureForError ());
2821                                 return null;
2822                         }
2823
2824                         InstanceExpression = left;
2825
2826                         return this;
2827                 }
2828
2829                 protected void EmitInstance (EmitContext ec, bool prepare_for_load)
2830                 {
2831                         if (IsStatic)
2832                                 return;
2833
2834                         if (InstanceExpression == EmptyExpression.Null) {
2835                                 SimpleName.Error_ObjectRefRequired (ec, loc, GetSignatureForError ());
2836                                 return;
2837                         }
2838                                 
2839                         if (InstanceExpression.Type.IsValueType) {
2840                                 if (InstanceExpression is IMemoryLocation) {
2841                                         ((IMemoryLocation) InstanceExpression).AddressOf (ec, AddressOp.LoadStore);
2842                                 } else {
2843                                         LocalTemporary t = new LocalTemporary (InstanceExpression.Type);
2844                                         InstanceExpression.Emit (ec);
2845                                         t.Store (ec);
2846                                         t.AddressOf (ec, AddressOp.Store);
2847                                 }
2848                         } else
2849                                 InstanceExpression.Emit (ec);
2850
2851                         if (prepare_for_load)
2852                                 ec.ig.Emit (OpCodes.Dup);
2853                 }
2854         }
2855
2856         /// 
2857         /// Represents group of extension methods
2858         /// 
2859         public class ExtensionMethodGroupExpr : MethodGroupExpr
2860         {
2861                 NamespaceEntry namespaceEntry;
2862                 readonly bool usingCandidates;
2863
2864                 public ExtensionMethodGroupExpr (ArrayList list, NamespaceEntry n, bool usingCandidates,
2865                         Type extensionType, Location l)
2866                         : base (list, l)
2867                 {
2868                         this.namespaceEntry = n;
2869                         this.usingCandidates = usingCandidates;
2870                         this.type = extensionType;
2871                 }
2872
2873                 public override bool IsBase {
2874                         get { return true; }
2875                 }
2876
2877                 public override bool IsStatic {
2878                         get { return true; }
2879                 }
2880
2881                 public bool IsTopLevel {
2882                         get { return namespaceEntry == null; }
2883                 }
2884
2885                 public override MethodBase OverloadExtensionResolve (EmitContext ec, ref ArrayList arguments, ref MethodGroupExpr mg,
2886                         Expression expr, Location loc)
2887                 {
2888                         if (arguments == null)
2889                                 arguments = new ArrayList (1);
2890                 
2891                         Argument a = new Argument (((MemberAccess)expr).Expr);
2892                         a.Resolve (ec, loc);
2893                         arguments.Insert (0, a);
2894
2895                         mg = this;
2896                         do {
2897                                 MethodBase method = mg.OverloadResolve (ec, arguments, true, loc);
2898                                 if (method != null)
2899                                         return method;
2900
2901                                 ExtensionMethodGroupExpr e = namespaceEntry.LookupExtensionMethod (type, usingCandidates, Name);
2902                                 if (e == null)
2903                                         return mg.OverloadResolve (ec, arguments, false, loc);
2904
2905                 mg = e;
2906                                 namespaceEntry = e.namespaceEntry;
2907                         } while (true);
2908                 }
2909         }
2910
2911         /// <summary>
2912         ///   MethodGroup Expression.
2913         ///  
2914         ///   This is a fully resolved expression that evaluates to a type
2915         /// </summary>
2916         public class MethodGroupExpr : MemberExpr {
2917                 public MethodBase [] Methods;
2918                 bool has_type_arguments = false;
2919                 bool identical_type_name = false;
2920                 bool is_base;
2921                 
2922                 public MethodGroupExpr (MemberInfo [] mi, Location l)
2923                 {
2924                         Methods = new MethodBase [mi.Length];
2925                         mi.CopyTo (Methods, 0);
2926                         eclass = ExprClass.MethodGroup;
2927
2928                         // Set the type to something that will never be useful, which will
2929                         // trigger the proper conversions.
2930                         type = typeof (MethodGroupExpr);
2931                         loc = l;
2932                 }
2933
2934                 public MethodGroupExpr (ArrayList list, Location l)
2935                 {
2936                         Methods = new MethodBase [list.Count];
2937
2938                         try {
2939                                 list.CopyTo (Methods, 0);
2940                         } catch {
2941                                 foreach (MemberInfo m in list){
2942                                         if (!(m is MethodBase)){
2943                                                 Console.WriteLine ("Name " + m.Name);
2944                                                 Console.WriteLine ("Found a: " + m.GetType ().FullName);
2945                                         }
2946                                 }
2947                                 throw;
2948                         }
2949
2950                         loc = l;
2951                         eclass = ExprClass.MethodGroup;
2952                         type = TypeManager.object_type;
2953                 }
2954
2955                 public override Type DeclaringType {
2956                         get {
2957                                 //
2958                                 // We assume that the top-level type is in the end
2959                                 //
2960                                 return Methods [Methods.Length - 1].DeclaringType;
2961                                 //return Methods [0].DeclaringType;
2962                         }
2963                 }
2964
2965                 public bool HasTypeArguments {
2966                         get {
2967                                 return has_type_arguments;
2968                         }
2969
2970                         set {
2971                                 has_type_arguments = value;
2972                         }
2973                 }
2974
2975                 public bool IdenticalTypeName {
2976                         get {
2977                                 return identical_type_name;
2978                         }
2979
2980                         set {
2981                                 identical_type_name = value;
2982                         }
2983                 }
2984
2985                 public virtual bool IsBase {
2986                         get {
2987                                 return is_base;
2988                         }
2989                         set {
2990                                 is_base = value;
2991                         }
2992                 }
2993
2994                 public override string GetSignatureForError ()
2995                 {
2996                         return TypeManager.CSharpSignature (Methods [0]);
2997                 }
2998
2999                 public override string Name {
3000                         get {
3001                                 return Methods [0].Name;
3002                         }
3003                 }
3004
3005                 public override bool IsInstance {
3006                         get {
3007                                 foreach (MethodBase mb in Methods)
3008                                         if (!mb.IsStatic)
3009                                                 return true;
3010
3011                                 return false;
3012                         }
3013                 }
3014
3015                 public override bool IsStatic {
3016                         get {
3017                                 foreach (MethodBase mb in Methods)
3018                                         if (mb.IsStatic)
3019                                                 return true;
3020
3021                                 return false;
3022                         }
3023                 }
3024
3025                 /// <summary>
3026                 ///   Determines "better conversion" as specified in 14.4.2.3
3027                 ///
3028                 ///    Returns : p    if a->p is better,
3029                 ///              q    if a->q is better,
3030                 ///              null if neither is better
3031                 /// </summary>
3032                 static Type BetterConversion (EmitContext ec, Argument a, Type p, Type q)
3033                 {
3034                         Type argument_type = TypeManager.TypeToCoreType (a.Type);
3035                         Expression argument_expr = a.Expr;
3036
3037                         if (argument_type == null)
3038                                 throw new Exception ("Expression of type " + a.Expr +
3039                                         " does not resolve its type");
3040
3041                         if (p == null || q == null)
3042                                 throw new InternalErrorException ("BetterConversion Got a null conversion");
3043
3044                         if (p == q)
3045                                 return null;
3046
3047                         if (argument_expr is NullLiteral) 
3048                         {
3049                                 //
3050                                 // If the argument is null and one of the types to compare is 'object' and
3051                                 // the other is a reference type, we prefer the other.
3052                                 //
3053                                 // This follows from the usual rules:
3054                                 //   * There is an implicit conversion from 'null' to type 'object'
3055                                 //   * There is an implicit conversion from 'null' to any reference type
3056                                 //   * There is an implicit conversion from any reference type to type 'object'
3057                                 //   * There is no implicit conversion from type 'object' to other reference types
3058                                 //  => Conversion of 'null' to a reference type is better than conversion to 'object'
3059                                 //
3060                                 //  FIXME: This probably isn't necessary, since the type of a NullLiteral is the 
3061                                 //         null type. I think it used to be 'object' and thus needed a special 
3062                                 //         case to avoid the immediately following two checks.
3063                                 //
3064                                 if (!p.IsValueType && q == TypeManager.object_type)
3065                                         return p;
3066                                 if (!q.IsValueType && p == TypeManager.object_type)
3067                                         return q;
3068                         }
3069                                 
3070                         if (argument_type == p)
3071                                 return p;
3072
3073                         if (argument_type == q)
3074                                 return q;
3075
3076                         Expression p_tmp = new EmptyExpression (p);
3077                         Expression q_tmp = new EmptyExpression (q);
3078
3079                         bool p_to_q = Convert.ImplicitConversionExists (ec, p_tmp, q);
3080                         bool q_to_p = Convert.ImplicitConversionExists (ec, q_tmp, p);
3081
3082                         if (p_to_q && !q_to_p)
3083                                 return p;
3084
3085                         if (q_to_p && !p_to_q)
3086                                 return q;
3087
3088                         if (p == TypeManager.sbyte_type)
3089                                 if (q == TypeManager.byte_type || q == TypeManager.ushort_type ||
3090                                         q == TypeManager.uint32_type || q == TypeManager.uint64_type)
3091                                         return p;
3092                         if (q == TypeManager.sbyte_type)
3093                                 if (p == TypeManager.byte_type || p == TypeManager.ushort_type ||
3094                                         p == TypeManager.uint32_type || p == TypeManager.uint64_type)
3095                                         return q;
3096
3097                         if (p == TypeManager.short_type)
3098                                 if (q == TypeManager.ushort_type || q == TypeManager.uint32_type ||
3099                                         q == TypeManager.uint64_type)
3100                                         return p;
3101                         if (q == TypeManager.short_type)
3102                                 if (p == TypeManager.ushort_type || p == TypeManager.uint32_type ||
3103                                         p == TypeManager.uint64_type)
3104                                         return q;
3105
3106                         if (p == TypeManager.int32_type)
3107                                 if (q == TypeManager.uint32_type || q == TypeManager.uint64_type)
3108                                         return p;
3109                         if (q == TypeManager.int32_type)
3110                                 if (p == TypeManager.uint32_type || p == TypeManager.uint64_type)
3111                                         return q;
3112
3113                         if (p == TypeManager.int64_type)
3114                                 if (q == TypeManager.uint64_type)
3115                                         return p;
3116                         if (q == TypeManager.int64_type)
3117                                 if (p == TypeManager.uint64_type)
3118                                         return q;
3119
3120                         return null;
3121                 }
3122
3123                 /// <summary>
3124                 ///   Determines "Better function" between candidate
3125                 ///   and the current best match
3126                 /// </summary>
3127                 /// <remarks>
3128                 ///    Returns a boolean indicating :
3129                 ///     false if candidate ain't better
3130                 ///     true  if candidate is better than the current best match
3131                 /// </remarks>
3132                 static bool BetterFunction (EmitContext ec, ArrayList args, int argument_count,
3133                         MethodBase candidate, bool candidate_params,
3134                         MethodBase best, bool best_params)
3135                 {
3136                         ParameterData candidate_pd = TypeManager.GetParameterData (candidate);
3137                         ParameterData best_pd = TypeManager.GetParameterData (best);
3138                 
3139                         bool better_at_least_one = false;
3140                         bool same = true;
3141                         for (int j = 0, c_idx = 0, b_idx = 0; j < argument_count; ++j, ++c_idx, ++b_idx) 
3142                         {
3143                                 Argument a = (Argument) args [j];
3144
3145                                 Type ct = TypeManager.TypeToCoreType (candidate_pd.ParameterType (c_idx));
3146                                 Type bt = TypeManager.TypeToCoreType (best_pd.ParameterType (b_idx));
3147
3148                                 if (candidate_params && candidate_pd.ParameterModifier (c_idx) == Parameter.Modifier.PARAMS) 
3149                                 {
3150                                         ct = TypeManager.GetElementType (ct);
3151                                         --c_idx;
3152                                 }
3153
3154                                 if (best_params && best_pd.ParameterModifier (b_idx) == Parameter.Modifier.PARAMS) 
3155                                 {
3156                                         bt = TypeManager.GetElementType (bt);
3157                                         --b_idx;
3158                                 }
3159
3160                                 if (ct.Equals (bt))
3161                                         continue;
3162
3163                                 same = false;
3164                                 Type better = BetterConversion (ec, a, ct, bt);
3165
3166                                 // for each argument, the conversion to 'ct' should be no worse than 
3167                                 // the conversion to 'bt'.
3168                                 if (better == bt)
3169                                         return false;
3170
3171                                 // for at least one argument, the conversion to 'ct' should be better than 
3172                                 // the conversion to 'bt'.
3173                                 if (better == ct)
3174                                         better_at_least_one = true;
3175                         }
3176
3177                         if (better_at_least_one)
3178                                 return true;
3179
3180                         //
3181                         // This handles the case
3182                         //
3183                         //   Add (float f1, float f2, float f3);
3184                         //   Add (params decimal [] foo);
3185                         //
3186                         // The call Add (3, 4, 5) should be ambiguous.  Without this check, the
3187                         // first candidate would've chosen as better.
3188                         //
3189                         if (!same)
3190                                 return false;
3191
3192                         //
3193                         // The two methods have equal parameter types.  Now apply tie-breaking rules
3194                         //
3195                         if (TypeManager.IsGenericMethod (best) && !TypeManager.IsGenericMethod (candidate))
3196                                 return true;
3197                         if (!TypeManager.IsGenericMethod (best) && TypeManager.IsGenericMethod (candidate))
3198                                 return false;
3199
3200                         //
3201                         // This handles the following cases:
3202                         //
3203                         //   Trim () is better than Trim (params char[] chars)
3204                         //   Concat (string s1, string s2, string s3) is better than
3205                         //     Concat (string s1, params string [] srest)
3206                         //   Foo (int, params int [] rest) is better than Foo (params int [] rest)
3207                         //
3208                         if (!candidate_params && best_params)
3209                                 return true;
3210                         if (candidate_params && !best_params)
3211                                 return false;
3212
3213                         int candidate_param_count = candidate_pd.Count;
3214                         int best_param_count = best_pd.Count;
3215
3216                         if (candidate_param_count != best_param_count)
3217                                 // can only happen if (candidate_params && best_params)
3218                                 return candidate_param_count > best_param_count;
3219
3220                         //
3221                         // now, both methods have the same number of parameters, and the parameters have the same types
3222                         // Pick the "more specific" signature
3223                         //
3224
3225                         MethodBase orig_candidate = TypeManager.DropGenericMethodArguments (candidate);
3226                         MethodBase orig_best = TypeManager.DropGenericMethodArguments (best);
3227
3228                         ParameterData orig_candidate_pd = TypeManager.GetParameterData (orig_candidate);
3229                         ParameterData orig_best_pd = TypeManager.GetParameterData (orig_best);
3230
3231                         bool specific_at_least_once = false;
3232                         for (int j = 0; j < candidate_param_count; ++j) 
3233                         {
3234                                 Type ct = TypeManager.TypeToCoreType (orig_candidate_pd.ParameterType (j));
3235                                 Type bt = TypeManager.TypeToCoreType (orig_best_pd.ParameterType (j));
3236                                 if (ct.Equals (bt))
3237                                         continue;
3238                                 Type specific = MoreSpecific (ct, bt);
3239                                 if (specific == bt)
3240                                         return false;
3241                                 if (specific == ct)
3242                                         specific_at_least_once = true;
3243                         }
3244
3245                         if (specific_at_least_once)
3246                                 return true;
3247
3248                         // FIXME: handle lifted operators
3249                         // ...
3250
3251                         return false;
3252                 }
3253
3254                 public override Expression ResolveMemberAccess (EmitContext ec, Expression left, Location loc,
3255                                                                 SimpleName original)
3256                 {
3257                         if (!(left is TypeExpr) &&
3258                             original != null && original.IdenticalNameAndTypeName (ec, left, loc))
3259                                 IdenticalTypeName = true;
3260
3261                         return base.ResolveMemberAccess (ec, left, loc, original);
3262                 }
3263                 
3264                 override public Expression DoResolve (EmitContext ec)
3265                 {
3266                         if (!IsInstance)
3267                                 InstanceExpression = null;
3268
3269                         if (InstanceExpression != null) {
3270                                 InstanceExpression = InstanceExpression.DoResolve (ec);
3271                                 if (InstanceExpression == null)
3272                                         return null;
3273                         }
3274
3275                         return this;
3276                 }
3277
3278                 public void ReportUsageError ()
3279                 {
3280                         Report.Error (654, loc, "Method `" + DeclaringType + "." +
3281                                       Name + "()' is referenced without parentheses");
3282                 }
3283
3284                 override public void Emit (EmitContext ec)
3285                 {
3286                         ReportUsageError ();
3287                 }
3288
3289                 public static bool IsAncestralType (Type first_type, Type second_type)
3290                 {
3291                         return first_type != second_type &&
3292                                 (TypeManager.IsSubclassOf (second_type, first_type) ||
3293                                 TypeManager.ImplementsInterface (second_type, first_type));
3294                 }               
3295
3296                 public static bool IsOverride (MethodBase cand_method, MethodBase base_method)
3297                 {
3298                         if (!IsAncestralType (base_method.DeclaringType, cand_method.DeclaringType))
3299                                 return false;
3300
3301                         ParameterData cand_pd = TypeManager.GetParameterData (cand_method);
3302                         ParameterData base_pd = TypeManager.GetParameterData (base_method);
3303                 
3304                         if (cand_pd.Count != base_pd.Count)
3305                                 return false;
3306
3307                         for (int j = 0; j < cand_pd.Count; ++j) 
3308                         {
3309                                 Parameter.Modifier cm = cand_pd.ParameterModifier (j);
3310                                 Parameter.Modifier bm = base_pd.ParameterModifier (j);
3311                                 Type ct = TypeManager.TypeToCoreType (cand_pd.ParameterType (j));
3312                                 Type bt = TypeManager.TypeToCoreType (base_pd.ParameterType (j));
3313
3314                                 if (cm != bm || ct != bt)
3315                                         return false;
3316                         }
3317
3318                         return true;
3319                 }
3320
3321                 static Type MoreSpecific (Type p, Type q)
3322                 {
3323                         if (TypeManager.IsGenericParameter (p) && !TypeManager.IsGenericParameter (q))
3324                                 return q;
3325                         if (!TypeManager.IsGenericParameter (p) && TypeManager.IsGenericParameter (q))
3326                                 return p;
3327
3328                         if (TypeManager.HasElementType (p)) 
3329                         {
3330                                 Type pe = TypeManager.GetElementType (p);
3331                                 Type qe = TypeManager.GetElementType (q);
3332                                 Type specific = MoreSpecific (pe, qe);
3333                                 if (specific == pe)
3334                                         return p;
3335                                 if (specific == qe)
3336                                         return q;
3337                         } 
3338                         else if (TypeManager.IsGenericType (p)) 
3339                         {
3340                                 Type[] pargs = TypeManager.GetTypeArguments (p);
3341                                 Type[] qargs = TypeManager.GetTypeArguments (q);
3342
3343                                 bool p_specific_at_least_once = false;
3344                                 bool q_specific_at_least_once = false;
3345
3346                                 for (int i = 0; i < pargs.Length; i++) 
3347                                 {
3348                                         Type specific = MoreSpecific (pargs [i], qargs [i]);
3349                                         if (specific == pargs [i])
3350                                                 p_specific_at_least_once = true;
3351                                         if (specific == qargs [i])
3352                                                 q_specific_at_least_once = true;
3353                                 }
3354
3355                                 if (p_specific_at_least_once && !q_specific_at_least_once)
3356                                         return p;
3357                                 if (!p_specific_at_least_once && q_specific_at_least_once)
3358                                         return q;
3359                         }
3360
3361                         return null;
3362                 }
3363
3364                 public virtual MethodBase OverloadExtensionResolve (EmitContext ec, ref ArrayList arguments, ref MethodGroupExpr mg,
3365                         Expression expr, Location loc)
3366                 {
3367                         MethodBase method = OverloadResolve (ec, arguments, true, loc);
3368                         if (method != null) {
3369                                 mg = this;
3370                                 return method;
3371                         }
3372
3373                         MemberAccess mexpr = expr as MemberAccess;
3374                         if (mexpr != null) {
3375                                 ExtensionMethodGroupExpr emg = ec.DeclContainer.LookupExtensionMethod (mexpr.Expr.Type, Name);
3376                                 if (emg != null) {
3377                                         return OverloadExtensionResolve (ec, ref arguments, ref mg, expr, loc);
3378                                 }
3379                         }
3380
3381                         return OverloadResolve (ec, arguments, false, loc);
3382                 }
3383
3384                 /// <summary>
3385                 ///   Find the Applicable Function Members (7.4.2.1)
3386                 ///
3387                 ///   me: Method Group expression with the members to select.
3388                 ///       it might contain constructors or methods (or anything
3389                 ///       that maps to a method).
3390                 ///
3391                 ///   Arguments: ArrayList containing resolved Argument objects.
3392                 ///
3393                 ///   loc: The location if we want an error to be reported, or a Null
3394                 ///        location for "probing" purposes.
3395                 ///
3396                 ///   Returns: The MethodBase (either a ConstructorInfo or a MethodInfo)
3397                 ///            that is the best match of me on Arguments.
3398                 ///
3399                 /// </summary>
3400                 public virtual MethodBase OverloadResolve (EmitContext ec, ArrayList Arguments,
3401                         bool may_fail, Location loc)
3402                 {
3403                         MethodBase method = null;
3404                         bool method_params = false;
3405                         Type applicable_type = null;
3406                         int arg_count = 0;
3407                         ArrayList candidates = new ArrayList (2);
3408                         ArrayList candidate_overrides = null;
3409
3410                         //
3411                         // Used to keep a map between the candidate
3412                         // and whether it is being considered in its
3413                         // normal or expanded form
3414                         //
3415                         // false is normal form, true is expanded form
3416                         //
3417                         Hashtable candidate_to_form = null;
3418
3419                         if (Arguments != null)
3420                                 arg_count = Arguments.Count;
3421
3422                         if (RootContext.Version == LanguageVersion.ISO_1 && Name == "Invoke" && TypeManager.IsDelegateType (DeclaringType)) {
3423                                 if (!may_fail)
3424                                         Report.Error (1533, loc, "Invoke cannot be called directly on a delegate");
3425                                 return null;
3426                         }
3427
3428                         int nmethods = Methods.Length;
3429
3430                         if (!IsBase) {
3431                                 //
3432                                 // Methods marked 'override' don't take part in 'applicable_type'
3433                                 // computation, nor in the actual overload resolution.
3434                                 // However, they still need to be emitted instead of a base virtual method.
3435                                 // So, we salt them away into the 'candidate_overrides' array.
3436                                 //
3437                                 // In case of reflected methods, we replace each overriding method with
3438                                 // its corresponding base virtual method.  This is to improve compatibility
3439                                 // with non-C# libraries which change the visibility of overrides (#75636)
3440                                 //
3441                                 int j = 0;
3442                                 for (int i = 0; i < Methods.Length; ++i) {
3443                                         MethodBase m = Methods [i];
3444 #if GMCS_SOURCE
3445                                         Type [] gen_args = null;
3446                                         if (m.IsGenericMethod && !m.IsGenericMethodDefinition)
3447                                                 gen_args = m.GetGenericArguments ();
3448 #endif
3449                                         if (TypeManager.IsOverride (m)) {
3450                                                 if (candidate_overrides == null)
3451                                                         candidate_overrides = new ArrayList ();
3452                                                 candidate_overrides.Add (m);
3453                                                 m = TypeManager.TryGetBaseDefinition (m);
3454 #if GMCS_SOURCE
3455                                                 if (m != null && gen_args != null) {
3456                                                         if (!m.IsGenericMethodDefinition)
3457                                                                 throw new InternalErrorException ("GetBaseDefinition didn't return a GenericMethodDefinition");
3458                                                         m = ((MethodInfo) m).MakeGenericMethod (gen_args);
3459                                                 }
3460 #endif
3461                                         }
3462                                         if (m != null)
3463                                                 Methods [j++] = m;
3464                                 }
3465                                 nmethods = j;
3466                         }
3467
3468                         int applicable_errors = Report.Errors;
3469                         
3470                         //
3471                         // First we construct the set of applicable methods
3472                         //
3473                         bool is_sorted = true;
3474                         for (int i = 0; i < nmethods; i++) {
3475                                 Type decl_type = Methods [i].DeclaringType;
3476
3477                                 //
3478                                 // If we have already found an applicable method
3479                                 // we eliminate all base types (Section 14.5.5.1)
3480                                 //
3481                                 if (applicable_type != null && IsAncestralType (decl_type, applicable_type))
3482                                         continue;
3483
3484                                 //
3485                                 // Check if candidate is applicable (section 14.4.2.1)
3486                                 //   Is candidate applicable in normal form?
3487                                 //
3488                                 bool is_applicable = Invocation.IsApplicable (ec, this, Arguments, arg_count, ref Methods [i]);
3489
3490                                 if (!is_applicable && Invocation.IsParamsMethodApplicable (ec, this, Arguments, arg_count, ref Methods [i])) {
3491                                         MethodBase candidate = Methods [i];
3492                                         if (candidate_to_form == null)
3493                                                 candidate_to_form = new PtrHashtable ();
3494                                         candidate_to_form [candidate] = candidate;
3495                                         // Candidate is applicable in expanded form
3496                                         is_applicable = true;
3497                                 }
3498
3499                                 if (!is_applicable)
3500                                         continue;
3501
3502                                 candidates.Add (Methods [i]);
3503
3504                                 if (applicable_type == null)
3505                                         applicable_type = decl_type;
3506                                 else if (applicable_type != decl_type) {
3507                                         is_sorted = false;
3508                                         if (IsAncestralType (applicable_type, decl_type))
3509                                                 applicable_type = decl_type;
3510                                 }
3511                         }
3512
3513                         if (applicable_errors != Report.Errors)
3514                                 return null;
3515                         
3516                         int candidate_top = candidates.Count;
3517
3518                         if (applicable_type == null) {
3519                                 //
3520                                 // Okay so we have failed to find anything so we
3521                                 // return by providing info about the closest match
3522                                 //
3523                                 int errors = Report.Errors;
3524                                 for (int i = 0; i < nmethods; ++i) {
3525                                         MethodBase c = Methods [i];
3526                                         ParameterData pd = TypeManager.GetParameterData (c);
3527
3528                                         if (pd.Count != arg_count)
3529                                                 continue;
3530
3531 #if GMCS_SOURCE
3532                                         if (!TypeManager.InferTypeArguments (Arguments, ref c))
3533                                                 continue;
3534                                         if (TypeManager.IsGenericMethodDefinition (c))
3535                                                 continue;
3536 #endif
3537
3538                                         Invocation.VerifyArgumentsCompat (ec, Arguments, arg_count,
3539                                                 c, false, null, may_fail, loc);
3540
3541                                         if (!may_fail && errors == Report.Errors)
3542                                                 throw new InternalErrorException (
3543                                                         "VerifyArgumentsCompat and IsApplicable do not agree; " +
3544                                                         "likely reason: ImplicitConversion and ImplicitConversionExists have gone out of sync");
3545
3546                                         break;
3547                                 }
3548
3549                                 if (!may_fail && errors == Report.Errors) {
3550                                         string report_name = Name;
3551                                         if (report_name == ".ctor")
3552                                                 report_name = TypeManager.CSharpName (DeclaringType);
3553                                         
3554 #if GMCS_SOURCE
3555                                         //
3556                                         // Type inference
3557                                         //
3558                                         for (int i = 0; i < Methods.Length; ++i) {
3559                                                 MethodBase c = Methods [i];
3560                                                 ParameterData pd = TypeManager.GetParameterData (c);
3561
3562                                                 if (pd.Count != arg_count)
3563                                                         continue;
3564
3565                                                 if (TypeManager.InferTypeArguments (Arguments, ref c))
3566                                                         continue;
3567
3568                                                 Report.Error (
3569                                                         411, loc, "The type arguments for " +
3570                                                         "method `{0}' cannot be inferred from " +
3571                                                         "the usage. Try specifying the type " +
3572                                                         "arguments explicitly.", report_name);
3573                                                 return null;
3574                                         }
3575 #endif
3576
3577                                         Invocation.Error_WrongNumArguments (loc, report_name, arg_count);
3578                                 }
3579                                 
3580                                 return null;
3581                         }
3582
3583                         if (!is_sorted) {
3584                                 //
3585                                 // At this point, applicable_type is _one_ of the most derived types
3586                                 // in the set of types containing the methods in this MethodGroup.
3587                                 // Filter the candidates so that they only contain methods from the
3588                                 // most derived types.
3589                                 //
3590
3591                                 int finalized = 0; // Number of finalized candidates
3592
3593                                 do {
3594                                         // Invariant: applicable_type is a most derived type
3595                                         
3596                                         // We'll try to complete Section 14.5.5.1 for 'applicable_type' by 
3597                                         // eliminating all it's base types.  At the same time, we'll also move
3598                                         // every unrelated type to the end of the array, and pick the next
3599                                         // 'applicable_type'.
3600
3601                                         Type next_applicable_type = null;
3602                                         int j = finalized; // where to put the next finalized candidate
3603                                         int k = finalized; // where to put the next undiscarded candidate
3604                                         for (int i = finalized; i < candidate_top; ++i) {
3605                                                 MethodBase candidate = (MethodBase) candidates [i];
3606                                                 Type decl_type = candidate.DeclaringType;
3607
3608                                                 if (decl_type == applicable_type) {
3609                                                         candidates [k++] = candidates [j];
3610                                                         candidates [j++] = candidates [i];
3611                                                         continue;
3612                                                 }
3613
3614                                                 if (IsAncestralType (decl_type, applicable_type))
3615                                                         continue;
3616
3617                                                 if (next_applicable_type != null &&
3618                                                         IsAncestralType (decl_type, next_applicable_type))
3619                                                         continue;
3620
3621                                                 candidates [k++] = candidates [i];
3622
3623                                                 if (next_applicable_type == null ||
3624                                                         IsAncestralType (next_applicable_type, decl_type))
3625                                                         next_applicable_type = decl_type;
3626                                         }
3627
3628                                         applicable_type = next_applicable_type;
3629                                         finalized = j;
3630                                         candidate_top = k;
3631                                 } while (applicable_type != null);
3632                         }
3633
3634                         //
3635                         // Now we actually find the best method
3636                         //
3637
3638                         method = (MethodBase) candidates [0];
3639                         method_params = candidate_to_form != null && candidate_to_form.Contains (method);
3640                         for (int ix = 1; ix < candidate_top; ix++) {
3641                                 MethodBase candidate = (MethodBase) candidates [ix];
3642
3643                                 if (candidate == method)
3644                                         continue;
3645
3646                                 bool cand_params = candidate_to_form != null && candidate_to_form.Contains (candidate);
3647
3648                                 if (BetterFunction (ec, Arguments, arg_count, 
3649                                         candidate, cand_params,
3650                                         method, method_params)) {
3651                                         method = candidate;
3652                                         method_params = cand_params;
3653                                 }
3654                         }
3655                         //
3656                         // Now check that there are no ambiguities i.e the selected method
3657                         // should be better than all the others
3658                         //
3659                         MethodBase ambiguous = null;
3660                         for (int ix = 0; ix < candidate_top; ix++) {
3661                                 MethodBase candidate = (MethodBase) candidates [ix];
3662
3663                                 if (candidate == method)
3664                                         continue;
3665
3666                                 bool cand_params = candidate_to_form != null && candidate_to_form.Contains (candidate);
3667                                 if (!BetterFunction (ec, Arguments, arg_count,
3668                                         method, method_params,
3669                                         candidate, cand_params)) 
3670                                 {
3671                                         if (!may_fail)
3672                                                 Report.SymbolRelatedToPreviousError (candidate);
3673                                         ambiguous = candidate;
3674                                 }
3675                         }
3676
3677                         if (ambiguous != null) {
3678                                 Report.SymbolRelatedToPreviousError (method);
3679                                 Report.Error (121, loc, "The call is ambiguous between the following methods or properties: `{0}' and `{1}'",
3680                                         TypeManager.CSharpSignature (ambiguous), TypeManager.CSharpSignature (method));
3681                                 return method;
3682                         }
3683
3684                         //
3685                         // If the method is a virtual function, pick an override closer to the LHS type.
3686                         //
3687                         if (!IsBase && method.IsVirtual) {
3688                                 if (TypeManager.IsOverride (method))
3689                                         throw new InternalErrorException (
3690                                                 "Should not happen.  An 'override' method took part in overload resolution: " + method);
3691
3692                                 if (candidate_overrides != null)
3693                                         foreach (MethodBase candidate in candidate_overrides) {
3694                                                 if (IsOverride (candidate, method))
3695                                                         method = candidate;
3696                                         }
3697                         }
3698
3699                         //
3700                         // And now check if the arguments are all
3701                         // compatible, perform conversions if
3702                         // necessary etc. and return if everything is
3703                         // all right
3704                         //
3705                         if (!Invocation.VerifyArgumentsCompat (ec, Arguments, arg_count, method,
3706                                 method_params, null, may_fail, loc))
3707                                 return null;
3708
3709                         if (method == null)
3710                                 return null;
3711
3712                         MethodBase the_method = TypeManager.DropGenericMethodArguments (method);
3713 #if GMCS_SOURCE
3714                         if (the_method.IsGenericMethodDefinition &&
3715                             !ConstraintChecker.CheckConstraints (ec, the_method, method, loc))
3716                                 return null;
3717 #endif
3718
3719                         IMethodData data = TypeManager.GetMethod (the_method);
3720                         if (data != null)
3721                                 data.SetMemberIsUsed ();
3722
3723                         return method;
3724                 }
3725
3726
3727                 bool RemoveMethods (bool keep_static)
3728                 {
3729                         ArrayList smethods = new ArrayList ();
3730
3731                         foreach (MethodBase mb in Methods){
3732                                 if (mb.IsStatic == keep_static)
3733                                         smethods.Add (mb);
3734                         }
3735
3736                         if (smethods.Count == 0)
3737                                 return false;
3738
3739                         Methods = new MethodBase [smethods.Count];
3740                         smethods.CopyTo (Methods, 0);
3741
3742                         return true;
3743                 }
3744                 
3745                 /// <summary>
3746                 ///   Removes any instance methods from the MethodGroup, returns
3747                 ///   false if the resulting set is empty.
3748                 /// </summary>
3749                 public bool RemoveInstanceMethods ()
3750                 {
3751                         return RemoveMethods (true);
3752                 }
3753
3754                 /// <summary>
3755                 ///   Removes any static methods from the MethodGroup, returns
3756                 ///   false if the resulting set is empty.
3757                 /// </summary>
3758                 public bool RemoveStaticMethods ()
3759                 {
3760                         return RemoveMethods (false);
3761                 }
3762
3763                 public Expression ResolveGeneric (EmitContext ec, TypeArguments args)
3764                 {
3765 #if GMCS_SOURCE
3766                         if (args.Resolve (ec) == false)
3767                                 return null;
3768
3769                         Type[] atypes = args.Arguments;
3770
3771                         int first_count = 0;
3772                         MethodInfo first = null;
3773
3774                         ArrayList list = new ArrayList ();
3775                         foreach (MethodBase mb in Methods) {
3776                                 MethodInfo mi = mb as MethodInfo;
3777                                 if ((mi == null) || !mi.IsGenericMethod)
3778                                         continue;
3779
3780                                 Type[] gen_params = mi.GetGenericArguments ();
3781
3782                                 if (first == null) {
3783                                         first = mi;
3784                                         first_count = gen_params.Length;
3785                                 }
3786
3787                                 if (gen_params.Length != atypes.Length)
3788                                         continue;
3789
3790                                 list.Add (mi.MakeGenericMethod (atypes));
3791                         }
3792
3793                         if (list.Count > 0) {
3794                                 MethodGroupExpr new_mg = new MethodGroupExpr (list, Location);
3795                                 new_mg.InstanceExpression = InstanceExpression;
3796                                 new_mg.HasTypeArguments = true;
3797                                 new_mg.IsBase = IsBase;
3798                                 return new_mg;
3799                         }
3800
3801                         if (first != null)
3802                                 Report.Error (
3803                                         305, loc, "Using the generic method `{0}' " +
3804                                         "requires {1} type arguments", Name,
3805                                         first_count.ToString ());
3806                         else
3807                                 Report.Error (
3808                                         308, loc, "The non-generic method `{0}' " +
3809                                         "cannot be used with type arguments", Name);
3810
3811                         return null;
3812 #else
3813                         throw new NotImplementedException ();
3814 #endif
3815                 }
3816         }
3817
3818         /// <summary>
3819         ///   Fully resolved expression that evaluates to a Field
3820         /// </summary>
3821         public class FieldExpr : MemberExpr, IAssignMethod, IMemoryLocation, IVariable {
3822                 public readonly FieldInfo FieldInfo;
3823                 VariableInfo variable_info;
3824                 
3825                 LocalTemporary temp;
3826                 bool prepared;
3827                 bool in_initializer;
3828
3829                 public FieldExpr (FieldInfo fi, Location l, bool in_initializer):
3830                         this (fi, l)
3831                 {
3832                         this.in_initializer = in_initializer;
3833                 }
3834                 
3835                 public FieldExpr (FieldInfo fi, Location l)
3836                 {
3837                         FieldInfo = fi;
3838                         eclass = ExprClass.Variable;
3839                         type = TypeManager.TypeToCoreType (fi.FieldType);
3840                         loc = l;
3841                 }
3842
3843                 public override string Name {
3844                         get {
3845                                 return FieldInfo.Name;
3846                         }
3847                 }
3848
3849                 public override bool IsInstance {
3850                         get {
3851                                 return !FieldInfo.IsStatic;
3852                         }
3853                 }
3854
3855                 public override bool IsStatic {
3856                         get {
3857                                 return FieldInfo.IsStatic;
3858                         }
3859                 }
3860
3861                 public override Type DeclaringType {
3862                         get {
3863                                 return FieldInfo.DeclaringType;
3864                         }
3865                 }
3866
3867                 public override string GetSignatureForError ()
3868                 {
3869                         return TypeManager.GetFullNameSignature (FieldInfo);
3870                 }
3871
3872                 public VariableInfo VariableInfo {
3873                         get {
3874                                 return variable_info;
3875                         }
3876                 }
3877
3878                 public override Expression ResolveMemberAccess (EmitContext ec, Expression left, Location loc,
3879                                                                 SimpleName original)
3880                 {
3881                         FieldInfo fi = TypeManager.GetGenericFieldDefinition (FieldInfo);
3882
3883                         Type t = fi.FieldType;
3884
3885                         if (fi.IsLiteral || (fi.IsInitOnly && t == TypeManager.decimal_type)) {
3886                                 IConstant ic = TypeManager.GetConstant (fi);
3887                                 if (ic == null) {
3888                                         if (fi.IsLiteral) {
3889                                                 ic = new ExternalConstant (fi);
3890                                         } else {
3891                                                 ic = ExternalConstant.CreateDecimal (fi);
3892                                                 if (ic == null) {
3893                                                         return base.ResolveMemberAccess (ec, left, loc, original);
3894                                                 }
3895                                         }
3896                                         TypeManager.RegisterConstant (fi, ic);
3897                                 }
3898
3899                                 bool left_is_type = left is TypeExpr;
3900                                 if (!left_is_type && (original == null || !original.IdenticalNameAndTypeName (ec, left, loc))) {
3901                                         Report.SymbolRelatedToPreviousError (FieldInfo);
3902                                         error176 (loc, TypeManager.GetFullNameSignature (FieldInfo));
3903                                         return null;
3904                                 }
3905
3906                                 if (ic.ResolveValue ()) {
3907                                         if (!ec.IsInObsoleteScope)
3908                                                 ic.CheckObsoleteness (loc);
3909                                 }
3910
3911                                 return ic.CreateConstantReference (loc);
3912                         }
3913                         
3914                         if (t.IsPointer && !ec.InUnsafe) {
3915                                 UnsafeError (loc);
3916                                 return null;
3917                         }
3918
3919                         return base.ResolveMemberAccess (ec, left, loc, original);
3920                 }
3921
3922                 override public Expression DoResolve (EmitContext ec)
3923                 {
3924                         return DoResolve (ec, false, false);
3925                 }
3926
3927                 Expression DoResolve (EmitContext ec, bool lvalue_instance, bool out_access)
3928                 {
3929                         if (!FieldInfo.IsStatic){
3930                                 if (InstanceExpression == null){
3931                                         //
3932                                         // This can happen when referencing an instance field using
3933                                         // a fully qualified type expression: TypeName.InstanceField = xxx
3934                                         // 
3935                                         SimpleName.Error_ObjectRefRequired (ec, loc, GetSignatureForError ());
3936                                         return null;
3937                                 }
3938
3939                                 // Resolve the field's instance expression while flow analysis is turned
3940                                 // off: when accessing a field "a.b", we must check whether the field
3941                                 // "a.b" is initialized, not whether the whole struct "a" is initialized.
3942
3943                                 if (lvalue_instance) {
3944                                         using (ec.With (EmitContext.Flags.DoFlowAnalysis, false)) {
3945                                                 Expression right_side =
3946                                                         out_access ? EmptyExpression.LValueMemberOutAccess : EmptyExpression.LValueMemberAccess;
3947                                                 InstanceExpression = InstanceExpression.ResolveLValue (ec, right_side, loc);
3948                                         }
3949                                 } else {
3950                                         ResolveFlags rf = ResolveFlags.VariableOrValue | ResolveFlags.DisableFlowAnalysis;
3951                                         InstanceExpression = InstanceExpression.Resolve (ec, rf);
3952                                 }
3953
3954                                 if (InstanceExpression == null)
3955                                         return null;
3956
3957                                 InstanceExpression.CheckMarshalByRefAccess ();
3958                         }
3959
3960                         if (!in_initializer && !ec.IsFieldInitializer) {
3961                                 ObsoleteAttribute oa;
3962                                 FieldBase f = TypeManager.GetField (FieldInfo);
3963                                 if (f != null) {
3964                                         if (!ec.IsInObsoleteScope)
3965                                                 f.CheckObsoleteness (loc);
3966                                 
3967                                         // To be sure that type is external because we do not register generated fields
3968                                 } else if (!(FieldInfo.DeclaringType is TypeBuilder)) {                                
3969                                         oa = AttributeTester.GetMemberObsoleteAttribute (FieldInfo);
3970                                         if (oa != null)
3971                                                 AttributeTester.Report_ObsoleteMessage (oa, TypeManager.GetFullNameSignature (FieldInfo), loc);
3972                                 }
3973                         }
3974
3975                         AnonymousContainer am = ec.CurrentAnonymousMethod;
3976                         if (am != null){
3977                                 if (!FieldInfo.IsStatic){
3978                                         if (!am.IsIterator && (ec.TypeContainer is Struct)){
3979                                                 Report.Error (1673, loc,
3980                                                 "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",
3981                                                         "this");
3982                                                 return null;
3983                                         }
3984                                 }
3985                         }
3986                         
3987                         // If the instance expression is a local variable or parameter.
3988                         IVariable var = InstanceExpression as IVariable;
3989                         if ((var == null) || (var.VariableInfo == null))
3990                                 return this;
3991
3992                         VariableInfo vi = var.VariableInfo;
3993                         if (!vi.IsFieldAssigned (ec, FieldInfo.Name, loc))
3994                                 return null;
3995
3996                         variable_info = vi.GetSubStruct (FieldInfo.Name);
3997                         return this;
3998                 }
3999
4000                 static readonly int [] codes = {
4001                         191,    // instance, write access
4002                         192,    // instance, out access
4003                         198,    // static, write access
4004                         199,    // static, out access
4005                         1648,   // member of value instance, write access
4006                         1649,   // member of value instance, out access
4007                         1650,   // member of value static, write access
4008                         1651    // member of value static, out access
4009                 };
4010
4011                 static readonly string [] msgs = {
4012                         /*0191*/ "A readonly field `{0}' cannot be assigned to (except in a constructor or a variable initializer)",
4013                         /*0192*/ "A readonly field `{0}' cannot be passed ref or out (except in a constructor)",
4014                         /*0198*/ "A static readonly field `{0}' cannot be assigned to (except in a static constructor or a variable initializer)",
4015                         /*0199*/ "A static readonly field `{0}' cannot be passed ref or out (except in a static constructor)",
4016                         /*1648*/ "Members of readonly field `{0}' cannot be modified (except in a constructor or a variable initializer)",
4017                         /*1649*/ "Members of readonly field `{0}' cannot be passed ref or out (except in a constructor)",
4018                         /*1650*/ "Fields of static readonly field `{0}' cannot be assigned to (except in a static constructor or a variable initializer)",
4019                         /*1651*/ "Fields of static readonly field `{0}' cannot be passed ref or out (except in a static constructor)"
4020                 };
4021
4022                 // The return value is always null.  Returning a value simplifies calling code.
4023                 Expression Report_AssignToReadonly (Expression right_side)
4024                 {
4025                         int i = 0;
4026                         if (right_side == EmptyExpression.OutAccess || right_side == EmptyExpression.LValueMemberOutAccess)
4027                                 i += 1;
4028                         if (IsStatic)
4029                                 i += 2;
4030                         if (right_side == EmptyExpression.LValueMemberAccess || right_side == EmptyExpression.LValueMemberOutAccess)
4031                                 i += 4;
4032                         Report.Error (codes [i], loc, msgs [i], GetSignatureForError ());
4033
4034                         return null;
4035                 }
4036                 
4037                 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
4038                 {
4039                         IVariable var = InstanceExpression as IVariable;
4040                         if ((var != null) && (var.VariableInfo != null))
4041                                 var.VariableInfo.SetFieldAssigned (ec, FieldInfo.Name);
4042
4043                         bool lvalue_instance = !FieldInfo.IsStatic && FieldInfo.DeclaringType.IsValueType;
4044                         bool out_access = right_side == EmptyExpression.OutAccess || right_side == EmptyExpression.LValueMemberOutAccess;
4045
4046                         Expression e = DoResolve (ec, lvalue_instance, out_access);
4047
4048                         if (e == null)
4049                                 return null;
4050
4051                         FieldBase fb = TypeManager.GetField (FieldInfo);
4052                         if (fb != null)
4053                                 fb.SetAssigned ();
4054
4055                         if (FieldInfo.IsInitOnly) {
4056                                 // InitOnly fields can only be assigned in constructors or initializers
4057                                 if (!ec.IsFieldInitializer && !ec.IsConstructor)
4058                                         return Report_AssignToReadonly (right_side);
4059
4060                                 if (ec.IsConstructor) {
4061                                         Type ctype = ec.TypeContainer.CurrentType;
4062                                         if (ctype == null)
4063                                                 ctype = ec.ContainerType;
4064
4065                                         // InitOnly fields cannot be assigned-to in a different constructor from their declaring type
4066                                         if (!TypeManager.IsEqual (ctype, FieldInfo.DeclaringType))
4067                                                 return Report_AssignToReadonly (right_side);
4068                                         // static InitOnly fields cannot be assigned-to in an instance constructor
4069                                         if (IsStatic && !ec.IsStatic)
4070                                                 return Report_AssignToReadonly (right_side);
4071                                         // instance constructors can't modify InitOnly fields of other instances of the same type
4072                                         if (!IsStatic && !(InstanceExpression is This))
4073                                                 return Report_AssignToReadonly (right_side);
4074                                 }
4075                         }
4076
4077                         if (right_side == EmptyExpression.OutAccess &&
4078                             !IsStatic && !(InstanceExpression is This) && DeclaringType.IsSubclassOf (TypeManager.mbr_type)) {
4079                                 Report.SymbolRelatedToPreviousError (DeclaringType);
4080                                 Report.Warning (197, 1, loc,
4081                                                 "Passing `{0}' as ref or out or taking its address may cause a runtime exception because it is a field of a marshal-by-reference class",
4082                                                 GetSignatureForError ());
4083                         }
4084
4085                         return this;
4086                 }
4087
4088                 public override void CheckMarshalByRefAccess ()
4089                 {
4090                         if (!IsStatic && Type.IsValueType && !(InstanceExpression is This) && DeclaringType.IsSubclassOf (TypeManager.mbr_type)) {
4091                                 Report.SymbolRelatedToPreviousError (DeclaringType);
4092                                 Report.Warning (1690, 1, loc, "Cannot call methods, properties, or indexers on `{0}' because it is a value type member of a marshal-by-reference class",
4093                                                 GetSignatureForError ());
4094                         }
4095                 }
4096
4097                 public bool VerifyFixed ()
4098                 {
4099                         IVariable variable = InstanceExpression as IVariable;
4100                         // A variable of the form V.I is fixed when V is a fixed variable of a struct type.
4101                         // We defer the InstanceExpression check after the variable check to avoid a 
4102                         // separate null check on InstanceExpression.
4103                         return variable != null && InstanceExpression.Type.IsValueType && variable.VerifyFixed ();
4104                 }
4105
4106                 public override int GetHashCode ()
4107                 {
4108                         return FieldInfo.GetHashCode ();
4109                 }
4110
4111                 public override bool Equals (object obj)
4112                 {
4113                         FieldExpr fe = obj as FieldExpr;
4114                         if (fe == null)
4115                                 return false;
4116
4117                         if (FieldInfo != fe.FieldInfo)
4118                                 return false;
4119
4120                         if (InstanceExpression == null || fe.InstanceExpression == null)
4121                                 return true;
4122
4123                         return InstanceExpression.Equals (fe.InstanceExpression);
4124                 }
4125                 
4126                 public void Emit (EmitContext ec, bool leave_copy)
4127                 {
4128                         ILGenerator ig = ec.ig;
4129                         bool is_volatile = false;
4130
4131                         FieldBase f = TypeManager.GetField (FieldInfo);
4132                         if (f != null){
4133                                 if ((f.ModFlags & Modifiers.VOLATILE) != 0)
4134                                         is_volatile = true;
4135
4136                                 f.SetMemberIsUsed ();
4137                         }
4138                         
4139                         if (FieldInfo.IsStatic){
4140                                 if (is_volatile)
4141                                         ig.Emit (OpCodes.Volatile);
4142                                 
4143                                 ig.Emit (OpCodes.Ldsfld, FieldInfo);
4144                         } else {
4145                                 if (!prepared)
4146                                         EmitInstance (ec, false);
4147
4148                                 if (is_volatile)
4149                                         ig.Emit (OpCodes.Volatile);
4150
4151                                 IFixedBuffer ff = AttributeTester.GetFixedBuffer (FieldInfo);
4152                                 if (ff != null)
4153                                 {
4154                                         ig.Emit (OpCodes.Ldflda, FieldInfo);
4155                                         ig.Emit (OpCodes.Ldflda, ff.Element);
4156                                 }
4157                                 else {
4158                                         ig.Emit (OpCodes.Ldfld, FieldInfo);
4159                                 }
4160                         }
4161
4162                         if (leave_copy) {
4163                                 ec.ig.Emit (OpCodes.Dup);
4164                                 if (!FieldInfo.IsStatic) {
4165                                         temp = new LocalTemporary (this.Type);
4166                                         temp.Store (ec);
4167                                 }
4168                         }
4169                 }
4170
4171                 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
4172                 {
4173                         FieldAttributes fa = FieldInfo.Attributes;
4174                         bool is_static = (fa & FieldAttributes.Static) != 0;
4175                         bool is_readonly = (fa & FieldAttributes.InitOnly) != 0;
4176                         ILGenerator ig = ec.ig;
4177                         prepared = prepare_for_load;
4178
4179                         if (is_readonly && !ec.IsConstructor){
4180                                 Report_AssignToReadonly (source);
4181                                 return;
4182                         }
4183
4184                         EmitInstance (ec, prepare_for_load);
4185
4186                         source.Emit (ec);
4187                         if (leave_copy) {
4188                                 ec.ig.Emit (OpCodes.Dup);
4189                                 if (!FieldInfo.IsStatic) {
4190                                         temp = new LocalTemporary (this.Type);
4191                                         temp.Store (ec);
4192                                 }
4193                         }
4194
4195                         FieldBase f = TypeManager.GetField (FieldInfo);
4196                         if (f != null){
4197                                 if ((f.ModFlags & Modifiers.VOLATILE) != 0)
4198                                         ig.Emit (OpCodes.Volatile);
4199                                         
4200                                 f.SetAssigned ();
4201                         }
4202
4203                         if (is_static)
4204                                 ig.Emit (OpCodes.Stsfld, FieldInfo);
4205                         else 
4206                                 ig.Emit (OpCodes.Stfld, FieldInfo);
4207                         
4208                         if (temp != null) {
4209                                 temp.Emit (ec);
4210                                 temp.Release (ec);
4211                         }
4212                 }
4213
4214                 public override void Emit (EmitContext ec)
4215                 {
4216                         Emit (ec, false);
4217                 }
4218
4219                 public void AddressOf (EmitContext ec, AddressOp mode)
4220                 {
4221                         ILGenerator ig = ec.ig;
4222
4223                         FieldBase f = TypeManager.GetField (FieldInfo);
4224                         if (f != null){
4225                                 if ((f.ModFlags & Modifiers.VOLATILE) != 0){
4226                                         Report.Warning (420, 1, loc, "`{0}': A volatile fields cannot be passed using a ref or out parameter",
4227                                                         f.GetSignatureForError ());
4228                                         return;
4229                                 }
4230                                         
4231                                 if ((mode & AddressOp.Store) != 0)
4232                                         f.SetAssigned ();
4233                                 if ((mode & AddressOp.Load) != 0)
4234                                         f.SetMemberIsUsed ();
4235                         }
4236
4237                         //
4238                         // Handle initonly fields specially: make a copy and then
4239                         // get the address of the copy.
4240                         //
4241                         bool need_copy;
4242                         if (FieldInfo.IsInitOnly){
4243                                 need_copy = true;
4244                                 if (ec.IsConstructor){
4245                                         if (FieldInfo.IsStatic){
4246                                                 if (ec.IsStatic)
4247                                                         need_copy = false;
4248                                         } else
4249                                                 need_copy = false;
4250                                 }
4251                         } else
4252                                 need_copy = false;
4253                         
4254                         if (need_copy){
4255                                 LocalBuilder local;
4256                                 Emit (ec);
4257                                 local = ig.DeclareLocal (type);
4258                                 ig.Emit (OpCodes.Stloc, local);
4259                                 ig.Emit (OpCodes.Ldloca, local);
4260                                 return;
4261                         }
4262
4263
4264                         if (FieldInfo.IsStatic){
4265                                 ig.Emit (OpCodes.Ldsflda, FieldInfo);
4266                         } else {
4267                                 if (!prepared)
4268                                         EmitInstance (ec, false);
4269                                 ig.Emit (OpCodes.Ldflda, FieldInfo);
4270                         }
4271                 }
4272         }
4273
4274         //
4275         // A FieldExpr whose address can not be taken
4276         //
4277         public class FieldExprNoAddress : FieldExpr, IMemoryLocation {
4278                 public FieldExprNoAddress (FieldInfo fi, Location loc) : base (fi, loc)
4279                 {
4280                 }
4281                 
4282                 public new void AddressOf (EmitContext ec, AddressOp mode)
4283                 {
4284                         Report.Error (-215, "Report this: Taking the address of a remapped parameter not supported");
4285                 }
4286         }
4287         
4288         /// <summary>
4289         ///   Expression that evaluates to a Property.  The Assign class
4290         ///   might set the `Value' expression if we are in an assignment.
4291         ///
4292         ///   This is not an LValue because we need to re-write the expression, we
4293         ///   can not take data from the stack and store it.  
4294         /// </summary>
4295         public class PropertyExpr : MemberExpr, IAssignMethod {
4296                 public readonly PropertyInfo PropertyInfo;
4297
4298                 //
4299                 // This is set externally by the  `BaseAccess' class
4300                 //
4301                 public bool IsBase;
4302                 MethodInfo getter, setter;
4303                 bool is_static;
4304
4305                 bool resolved;
4306                 
4307                 LocalTemporary temp;
4308                 bool prepared;
4309
4310                 public PropertyExpr (Type containerType, PropertyInfo pi, Location l)
4311                 {
4312                         PropertyInfo = pi;
4313                         eclass = ExprClass.PropertyAccess;
4314                         is_static = false;
4315                         loc = l;
4316
4317                         type = TypeManager.TypeToCoreType (pi.PropertyType);
4318
4319                         ResolveAccessors (containerType);
4320                 }
4321
4322                 public override string Name {
4323                         get {
4324                                 return PropertyInfo.Name;
4325                         }
4326                 }
4327
4328                 public override bool IsInstance {
4329                         get {
4330                                 return !is_static;
4331                         }
4332                 }
4333
4334                 public override bool IsStatic {
4335                         get {
4336                                 return is_static;
4337                         }
4338                 }
4339                 
4340                 public override Type DeclaringType {
4341                         get {
4342                                 return PropertyInfo.DeclaringType;
4343                         }
4344                 }
4345
4346                 public override string GetSignatureForError ()
4347                 {
4348                         return TypeManager.GetFullNameSignature (PropertyInfo);
4349                 }
4350
4351                 void FindAccessors (Type invocation_type)
4352                 {
4353                         const BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic |
4354                                 BindingFlags.Static | BindingFlags.Instance |
4355                                 BindingFlags.DeclaredOnly;
4356
4357                         Type current = PropertyInfo.DeclaringType;
4358                         for (; current != null; current = current.BaseType) {
4359                                 MemberInfo[] group = TypeManager.MemberLookup (
4360                                         invocation_type, invocation_type, current,
4361                                         MemberTypes.Property, flags, PropertyInfo.Name, null);
4362
4363                                 if (group == null)
4364                                         continue;
4365
4366                                 if (group.Length != 1)
4367                                         // Oooops, can this ever happen ?
4368                                         return;
4369
4370                                 PropertyInfo pi = (PropertyInfo) group [0];
4371
4372                                 if (getter == null)
4373                                         getter = pi.GetGetMethod (true);
4374
4375                                 if (setter == null)
4376                                         setter = pi.GetSetMethod (true);
4377
4378                                 MethodInfo accessor = getter != null ? getter : setter;
4379
4380                                 if (!accessor.IsVirtual)
4381                                         return;
4382                         }
4383                 }
4384
4385                 //
4386                 // We also perform the permission checking here, as the PropertyInfo does not
4387                 // hold the information for the accessibility of its setter/getter
4388                 //
4389                 // TODO: Refactor to use some kind of cache together with GetPropertyFromAccessor
4390                 void ResolveAccessors (Type containerType)
4391                 {
4392                         FindAccessors (containerType);
4393
4394                         if (getter != null) {
4395                                 MethodBase the_getter = TypeManager.DropGenericMethodArguments (getter);
4396                                 IMethodData md = TypeManager.GetMethod (the_getter);
4397                                 if (md != null)
4398                                         md.SetMemberIsUsed ();
4399
4400                                 is_static = getter.IsStatic;
4401                         }
4402
4403                         if (setter != null) {
4404                                 MethodBase the_setter = TypeManager.DropGenericMethodArguments (setter);
4405                                 IMethodData md = TypeManager.GetMethod (the_setter);
4406                                 if (md != null)
4407                                         md.SetMemberIsUsed ();
4408
4409                                 is_static = setter.IsStatic;
4410                         }
4411                 }
4412
4413                 bool InstanceResolve (EmitContext ec, bool lvalue_instance, bool must_do_cs1540_check)
4414                 {
4415                         if (is_static) {
4416                                 InstanceExpression = null;
4417                                 return true;
4418                         }
4419
4420                         if (InstanceExpression == null) {
4421                                 SimpleName.Error_ObjectRefRequired (ec, loc, GetSignatureForError ());
4422                                 return false;
4423                         }
4424
4425                         InstanceExpression = InstanceExpression.DoResolve (ec);
4426                         if (lvalue_instance && InstanceExpression != null)
4427                                 InstanceExpression = InstanceExpression.ResolveLValue (ec, EmptyExpression.LValueMemberAccess, loc);
4428
4429                         if (InstanceExpression == null)
4430                                 return false;
4431
4432                         InstanceExpression.CheckMarshalByRefAccess ();
4433
4434                         if (must_do_cs1540_check && (InstanceExpression != EmptyExpression.Null) &&
4435                             !TypeManager.IsInstantiationOfSameGenericType (InstanceExpression.Type, ec.ContainerType) &&
4436                             !TypeManager.IsNestedChildOf (ec.ContainerType, InstanceExpression.Type) &&
4437                             !TypeManager.IsSubclassOf (InstanceExpression.Type, ec.ContainerType)) {
4438                                 Report.SymbolRelatedToPreviousError (PropertyInfo);
4439                                 Error_CannotAccessProtected (loc, PropertyInfo, InstanceExpression.Type, ec.ContainerType);
4440                                 return false;
4441                         }
4442
4443                         return true;
4444                 }
4445
4446                 void Error_PropertyNotFound (MethodInfo mi, bool getter)
4447                 {
4448                         // TODO: correctly we should compare arguments but it will lead to bigger changes
4449                         if (mi is MethodBuilder) {
4450                                 Error_TypeDoesNotContainDefinition (loc, PropertyInfo.DeclaringType, Name);
4451                                 return;
4452                         }
4453
4454                         StringBuilder sig = new StringBuilder (TypeManager.CSharpName (mi.DeclaringType));
4455                         sig.Append ('.');
4456                         ParameterData iparams = TypeManager.GetParameterData (mi);
4457                         sig.Append (getter ? "get_" : "set_");
4458                         sig.Append (Name);
4459                         sig.Append (iparams.GetSignatureForError ());
4460
4461                         Report.SymbolRelatedToPreviousError (mi);
4462                         Report.Error (1546, loc, "Property `{0}' is not supported by the C# language. Try to call the accessor method `{1}' directly",
4463                                 Name, sig.ToString ());
4464                 }
4465                 
4466                 override public Expression DoResolve (EmitContext ec)
4467                 {
4468                         if (resolved)
4469                                 return this;
4470
4471                         if (getter != null){
4472                                 if (TypeManager.GetParameterData (getter).Count != 0){
4473                                         Error_PropertyNotFound (getter, true);
4474                                         return null;
4475                                 }
4476                         }
4477
4478                         if (getter == null){
4479                                 //
4480                                 // The following condition happens if the PropertyExpr was
4481                                 // created, but is invalid (ie, the property is inaccessible),
4482                                 // and we did not want to embed the knowledge about this in
4483                                 // the caller routine.  This only avoids double error reporting.
4484                                 //
4485                                 if (setter == null)
4486                                         return null;
4487
4488                                 if (InstanceExpression != EmptyExpression.Null) {
4489                                         Report.Error (154, loc, "The property or indexer `{0}' cannot be used in this context because it lacks the `get' accessor",
4490                                                 TypeManager.GetFullNameSignature (PropertyInfo));
4491                                         return null;
4492                                 }
4493                         } 
4494
4495                         bool must_do_cs1540_check = false;
4496                         if (getter != null &&
4497                             !IsAccessorAccessible (ec.ContainerType, getter, out must_do_cs1540_check)) {
4498                                 PropertyBase.PropertyMethod pm = TypeManager.GetMethod (getter) as PropertyBase.PropertyMethod;
4499                                 if (pm != null && pm.HasCustomAccessModifier) {
4500                                         Report.SymbolRelatedToPreviousError (pm);
4501                                         Report.Error (271, loc, "The property or indexer `{0}' cannot be used in this context because the get accessor is inaccessible",
4502                                                 TypeManager.CSharpSignature (getter));
4503                                 }
4504                                 else {
4505                                         Report.SymbolRelatedToPreviousError (getter);
4506                                         ErrorIsInaccesible (loc, TypeManager.CSharpSignature (getter));
4507                                 }
4508                                 return null;
4509                         }
4510                         
4511                         if (!InstanceResolve (ec, false, must_do_cs1540_check))
4512                                 return null;
4513
4514                         //
4515                         // Only base will allow this invocation to happen.
4516                         //
4517                         if (IsBase && getter.IsAbstract) {
4518                                 Error_CannotCallAbstractBase (TypeManager.GetFullNameSignature (PropertyInfo));
4519                                 return null;
4520                         }
4521
4522                         if (PropertyInfo.PropertyType.IsPointer && !ec.InUnsafe){
4523                                 UnsafeError (loc);
4524                                 return null;
4525                         }
4526
4527                         resolved = true;
4528
4529                         return this;
4530                 }
4531
4532                 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
4533                 {
4534                         if (right_side == EmptyExpression.OutAccess) {
4535                                 Report.Error (206, loc, "A property or indexer `{0}' may not be passed as an out or ref parameter",
4536                                               GetSignatureForError ());
4537                                 return null;
4538                         }
4539
4540                         if (right_side == EmptyExpression.LValueMemberAccess || right_side == EmptyExpression.LValueMemberOutAccess) {
4541                                 Report.Error (1612, loc, "Cannot modify the return value of `{0}' because it is not a variable",
4542                                               GetSignatureForError ());
4543                                 return null;
4544                         }
4545
4546                         if (setter == null){
4547                                 //
4548                                 // The following condition happens if the PropertyExpr was
4549                                 // created, but is invalid (ie, the property is inaccessible),
4550                                 // and we did not want to embed the knowledge about this in
4551                                 // the caller routine.  This only avoids double error reporting.
4552                                 //
4553                                 if (getter == null)
4554                                         return null;
4555                                 Report.Error (200, loc, "Property or indexer `{0}' cannot be assigned to (it is read only)",
4556                                               GetSignatureForError ());
4557                                 return null;
4558                         }
4559
4560                         if (TypeManager.GetParameterData (setter).Count != 1){
4561                                 Error_PropertyNotFound (setter, false);
4562                                 return null;
4563                         }
4564
4565                         bool must_do_cs1540_check;
4566                         if (!IsAccessorAccessible (ec.ContainerType, setter, out must_do_cs1540_check)) {
4567                                 PropertyBase.PropertyMethod pm = TypeManager.GetMethod (setter) as PropertyBase.PropertyMethod;
4568                                 if (pm != null && pm.HasCustomAccessModifier) {
4569                                         Report.SymbolRelatedToPreviousError (pm);
4570                                         Report.Error (272, loc, "The property or indexer `{0}' cannot be used in this context because the set accessor is inaccessible",
4571                                                 TypeManager.CSharpSignature (setter));
4572                                 }
4573                                 else {
4574                                         Report.SymbolRelatedToPreviousError (setter);
4575                                         ErrorIsInaccesible (loc, TypeManager.CSharpSignature (setter));
4576                                 }
4577                                 return null;
4578                         }
4579                         
4580                         if (!InstanceResolve (ec, PropertyInfo.DeclaringType.IsValueType, must_do_cs1540_check))
4581                                 return null;
4582                         
4583                         //
4584                         // Only base will allow this invocation to happen.
4585                         //
4586                         if (IsBase && setter.IsAbstract){
4587                                 Error_CannotCallAbstractBase (TypeManager.GetFullNameSignature (PropertyInfo));
4588                                 return null;
4589                         }
4590
4591                         return this;
4592                 }
4593                 
4594                 public override void Emit (EmitContext ec)
4595                 {
4596                         Emit (ec, false);
4597                 }
4598                 
4599                 public void Emit (EmitContext ec, bool leave_copy)
4600                 {
4601                         //
4602                         // Special case: length of single dimension array property is turned into ldlen
4603                         //
4604                         if ((getter == TypeManager.system_int_array_get_length) ||
4605                             (getter == TypeManager.int_array_get_length)){
4606                                 Type iet = InstanceExpression.Type;
4607
4608                                 //
4609                                 // System.Array.Length can be called, but the Type does not
4610                                 // support invoking GetArrayRank, so test for that case first
4611                                 //
4612                                 if (iet != TypeManager.array_type && (iet.GetArrayRank () == 1)) {
4613                                         if (!prepared)
4614                                                 EmitInstance (ec, false);
4615                                         ec.ig.Emit (OpCodes.Ldlen);
4616                                         ec.ig.Emit (OpCodes.Conv_I4);
4617                                         return;
4618                                 }
4619                         }
4620
4621                         Invocation.EmitCall (ec, IsBase, IsStatic, InstanceExpression, getter, null, loc, prepared, false);
4622                         
4623                         if (leave_copy) {
4624                                 ec.ig.Emit (OpCodes.Dup);
4625                                 if (!is_static) {
4626                                         temp = new LocalTemporary (this.Type);
4627                                         temp.Store (ec);
4628                                 }
4629                         }
4630                 }
4631
4632                 //
4633                 // Implements the IAssignMethod interface for assignments
4634                 //
4635                 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
4636                 {
4637                         Expression my_source = source;
4638
4639                         prepared = prepare_for_load;
4640                         
4641                         if (prepared) {
4642                                 source.Emit (ec);
4643                                 if (leave_copy) {
4644                                         ec.ig.Emit (OpCodes.Dup);
4645                                         if (!is_static) {
4646                                                 temp = new LocalTemporary (this.Type);
4647                                                 temp.Store (ec);
4648                                         }
4649                                 }
4650                         } else if (leave_copy) {
4651                                 source.Emit (ec);
4652                                 if (!is_static) {
4653                                         temp = new LocalTemporary (this.Type);
4654                                         temp.Store (ec);
4655                                 }
4656                                 my_source = temp;
4657                         }
4658                         
4659                         ArrayList args = new ArrayList (1);
4660                         args.Add (new Argument (my_source, Argument.AType.Expression));
4661                         
4662                         Invocation.EmitCall (ec, IsBase, IsStatic, InstanceExpression, setter, args, loc, false, prepared);
4663                         
4664                         if (temp != null) {
4665                                 temp.Emit (ec);
4666                                 temp.Release (ec);
4667                         }
4668                 }
4669         }
4670
4671         /// <summary>
4672         ///   Fully resolved expression that evaluates to an Event
4673         /// </summary>
4674         public class EventExpr : MemberExpr {
4675                 public readonly EventInfo EventInfo;
4676
4677                 bool is_static;
4678                 MethodInfo add_accessor, remove_accessor;
4679
4680                 public EventExpr (EventInfo ei, Location loc)
4681                 {
4682                         EventInfo = ei;
4683                         this.loc = loc;
4684                         eclass = ExprClass.EventAccess;
4685
4686                         add_accessor = TypeManager.GetAddMethod (ei);
4687                         remove_accessor = TypeManager.GetRemoveMethod (ei);
4688                         if (add_accessor.IsStatic || remove_accessor.IsStatic)
4689                                 is_static = true;
4690
4691                         if (EventInfo is MyEventBuilder){
4692                                 MyEventBuilder eb = (MyEventBuilder) EventInfo;
4693                                 type = eb.EventType;
4694                                 eb.SetUsed ();
4695                         } else
4696                                 type = EventInfo.EventHandlerType;
4697                 }
4698
4699                 public override string Name {
4700                         get {
4701                                 return EventInfo.Name;
4702                         }
4703                 }
4704
4705                 public override bool IsInstance {
4706                         get {
4707                                 return !is_static;
4708                         }
4709                 }
4710
4711                 public override bool IsStatic {
4712                         get {
4713                                 return is_static;
4714                         }
4715                 }
4716
4717                 public override Type DeclaringType {
4718                         get {
4719                                 return EventInfo.DeclaringType;
4720                         }
4721                 }
4722
4723                 public override Expression ResolveMemberAccess (EmitContext ec, Expression left, Location loc,
4724                                                                 SimpleName original)
4725                 {
4726                         //
4727                         // If the event is local to this class, we transform ourselves into a FieldExpr
4728                         //
4729
4730                         if (EventInfo.DeclaringType == ec.ContainerType ||
4731                             TypeManager.IsNestedChildOf(ec.ContainerType, EventInfo.DeclaringType)) {
4732                                 EventField mi = TypeManager.GetEventField (EventInfo);
4733
4734                                 if (mi != null) {
4735                                         if (!ec.IsInObsoleteScope)
4736                                                 mi.CheckObsoleteness (loc);
4737
4738                                         FieldExpr ml = new FieldExpr (mi.FieldBuilder, loc);
4739
4740                                         InstanceExpression = null;
4741                                 
4742                                         return ml.ResolveMemberAccess (ec, left, loc, original);
4743                                 }
4744                         }
4745
4746                         return base.ResolveMemberAccess (ec, left, loc, original);
4747                 }
4748
4749
4750                 bool InstanceResolve (EmitContext ec, bool must_do_cs1540_check)
4751                 {
4752                         if (is_static) {
4753                                 InstanceExpression = null;
4754                                 return true;
4755                         }
4756
4757                         if (InstanceExpression == null) {
4758                                 SimpleName.Error_ObjectRefRequired (ec, loc, GetSignatureForError ());
4759                                 return false;
4760                         }
4761
4762                         InstanceExpression = InstanceExpression.DoResolve (ec);
4763                         if (InstanceExpression == null)
4764                                 return false;
4765
4766                         //
4767                         // This is using the same mechanism as the CS1540 check in PropertyExpr.
4768                         // However, in the Event case, we reported a CS0122 instead.
4769                         //
4770                         if (must_do_cs1540_check && InstanceExpression != EmptyExpression.Null &&
4771                             InstanceExpression.Type != ec.ContainerType &&
4772                             ec.ContainerType.IsSubclassOf (InstanceExpression.Type)) {
4773                                 Report.SymbolRelatedToPreviousError (EventInfo);
4774                                 ErrorIsInaccesible (loc, TypeManager.CSharpSignature (EventInfo));
4775                                 return false;
4776                         }
4777
4778                         return true;
4779                 }
4780
4781                 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
4782                 {
4783                         return DoResolve (ec);
4784                 }
4785
4786                 public override Expression DoResolve (EmitContext ec)
4787                 {
4788                         bool must_do_cs1540_check;
4789                         if (!(IsAccessorAccessible (ec.ContainerType, add_accessor, out must_do_cs1540_check) &&
4790                               IsAccessorAccessible (ec.ContainerType, remove_accessor, out must_do_cs1540_check))) {
4791                                 Report.SymbolRelatedToPreviousError (EventInfo);
4792                                 ErrorIsInaccesible (loc, TypeManager.CSharpSignature (EventInfo));
4793                                 return null;
4794                         }
4795
4796                         if (!InstanceResolve (ec, must_do_cs1540_check))
4797                                 return null;
4798                         
4799                         return this;
4800                 }               
4801
4802                 public override void Emit (EmitContext ec)
4803                 {
4804                         if (InstanceExpression is This)
4805                                 Report.Error (79, loc, "The event `{0}' can only appear on the left hand side of += or -=", GetSignatureForError ());
4806                         else
4807                                 Report.Error (70, loc, "The event `{0}' can only appear on the left hand side of += or -= "+
4808                                               "(except on the defining type)", Name);
4809                 }
4810
4811                 public override string GetSignatureForError ()
4812                 {
4813                         return TypeManager.CSharpSignature (EventInfo);
4814                 }
4815
4816                 public void EmitAddOrRemove (EmitContext ec, Expression source)
4817                 {
4818                         BinaryDelegate source_del = source as BinaryDelegate;
4819                         if (source_del == null) {
4820                                 Emit (ec);
4821                                 return;
4822                         }
4823                         Expression handler = source_del.Right;
4824                         
4825                         Argument arg = new Argument (handler, Argument.AType.Expression);
4826                         ArrayList args = new ArrayList ();
4827                                 
4828                         args.Add (arg);
4829                         
4830                         if (source_del.IsAddition)
4831                                 Invocation.EmitCall (
4832                                         ec, false, IsStatic, InstanceExpression, add_accessor, args, loc);
4833                         else
4834                                 Invocation.EmitCall (
4835                                         ec, false, IsStatic, InstanceExpression, remove_accessor, args, loc);
4836                 }
4837         }
4838
4839         public class TemporaryVariable : Expression, IMemoryLocation
4840         {
4841                 LocalInfo li;
4842                 Variable var;
4843                 
4844                 public TemporaryVariable (Type type, Location loc)
4845                 {
4846                         this.type = type;
4847                         this.loc = loc;
4848                         eclass = ExprClass.Value;
4849                 }
4850                 
4851                 public override Expression DoResolve (EmitContext ec)
4852                 {
4853                         if (li != null)
4854                                 return this;
4855                         
4856                         TypeExpr te = new TypeExpression (type, loc);
4857                         li = ec.CurrentBlock.AddTemporaryVariable (te, loc);
4858                         if (!li.Resolve (ec))
4859                                 return null;
4860
4861                         if (ec.MustCaptureVariable (li)) {
4862                                 ScopeInfo scope = li.Block.CreateScopeInfo ();
4863                                 var = scope.AddLocal (li);
4864                                 type = var.Type;
4865                         }
4866                         
4867                         return this;
4868                 }
4869
4870                 public Variable Variable {
4871                         get { return var != null ? var : li.Variable; }
4872                 }
4873                 
4874                 public override void Emit (EmitContext ec)
4875                 {
4876                         Variable.EmitInstance (ec);
4877                         Variable.Emit (ec);
4878                 }
4879                 
4880                 public void EmitLoadAddress (EmitContext ec)
4881                 {
4882                         Variable.EmitInstance (ec);
4883                         Variable.EmitAddressOf (ec);
4884                 }
4885                 
4886                 public void Store (EmitContext ec, Expression right_side)
4887                 {
4888                         Variable.EmitInstance (ec);
4889                         right_side.Emit (ec);
4890                         Variable.EmitAssign (ec);
4891                 }
4892                 
4893                 public void EmitThis (EmitContext ec)
4894                 {
4895                         Variable.EmitInstance (ec);
4896                 }
4897                 
4898                 public void EmitStore (EmitContext ec)
4899                 {
4900                         Variable.EmitAssign (ec);
4901                 }
4902                 
4903                 public void AddressOf (EmitContext ec, AddressOp mode)
4904                 {
4905                         EmitLoadAddress (ec);
4906                 }
4907         }
4908         
4909 }