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